-
Notifications
You must be signed in to change notification settings - Fork 0
/
anfis_ejm.py
425 lines (315 loc) · 14.6 KB
/
anfis_ejm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import sys
import os
# Importar la función para tomar la derivada parcial de las funciones de membresía
# Requerida para el aprendizaje.
import numpy as np
def partial_dMF(x, mf_definition, partial_parameter):
"""Calculates the partial derivative of a membership function at a point x.
Parameters
------
Returns
------
"""
mf_name = mf_definition[0]
if mf_name == 'gaussmf':
sigma = mf_definition[1]['sigma']
mean = mf_definition[1]['mean']
if partial_parameter == 'sigma':
result = (2./sigma**3) * np.exp(-(((x-mean)**2)/(sigma)**2))*(x-mean)**2
elif partial_parameter == 'mean':
result = (2./sigma**2) * np.exp(-(((x-mean)**2)/(sigma)**2))*(x-mean)
elif mf_name == 'gbellmf':
a = mf_definition[1]['a']
b = mf_definition[1]['b']
c = mf_definition[1]['c']
if partial_parameter == 'a':
result = (2. * b * np.power((c-x),2) * np.power(np.absolute((c-x)/a), ((2 * b) - 2))) / \
(np.power(a, 3) * np.power((np.power(np.absolute((c-x)/a),(2*b)) + 1), 2))
elif partial_parameter == 'b':
result = -1 * (2 * np.power(np.absolute((c-x)/a), (2 * b)) * np.log(np.absolute((c-x)/a))) / \
(np.power((np.power(np.absolute((c-x)/a), (2 * b)) + 1), 2))
elif partial_parameter == 'c':
result = (2. * b * (c-x) * np.power(np.absolute((c-x)/a), ((2 * b) - 2))) / \
(np.power(a, 2) * np.power((np.power(np.absolute((c-x)/a),(2*b)) + 1), 2))
elif mf_name == 'sigmf':
b = mf_definition[1]['b']
c = mf_definition[1]['c']
if partial_parameter == 'b':
result = -1 * (c * np.exp(c * (b + x))) / \
np.power((np.exp(b*c) + np.exp(c*x)), 2)
elif partial_parameter == 'c':
result = ((x - b) * np.exp(c * (x - b))) / \
np.power((np.exp(c * (x - c))) + 1, 2)
return result
# Importar las funciones de membresía
from skfuzzy import gaussmf, gbellmf, sigmf
class MemFuncs:
'Common base class for all employees'
funcDict = {'gaussmf': gaussmf, 'gbellmf': gbellmf, 'sigmf': sigmf}
def __init__(self, MFList):
self.MFList = MFList
def evaluateMF(self, rowInput):
if len(rowInput) != len(self.MFList):
print ("Number of variables does not match number of rule sets")
return [[self.funcDict[self.MFList[i][k][0]](rowInput[i],**self.MFList[i][k][1]) for k in range(len(self.MFList[i]))] for i in range(len(rowInput))]
import itertools
import numpy as np
import copy
class ANFIS:
"""Class to implement an Adaptive Network Fuzzy Inference System: ANFIS"
Attributes:
X
Y
XLen
memClass
memFuncs
memFuncsByVariable
rules
consequents
errors
memFuncsHomo
trainingType
"""
def __init__(self, X, Y, memFunction):
self.X = np.array(copy.copy(X))
self.Y = np.array(copy.copy(Y))
self.XLen = len(self.X)
self.memClass = copy.deepcopy(memFunction)
self.memFuncs = self.memClass.MFList
self.memFuncsByVariable = [[x for x in range(len(self.memFuncs[z]))] for z in range(len(self.memFuncs))]
self.rules = np.array(list(itertools.product(*self.memFuncsByVariable)))
self.consequents = np.empty(self.Y.ndim * len(self.rules) * (self.X.shape[1] + 1))
self.consequents.fill(0)
self.errors = np.empty(0)
self.memFuncsHomo = all(len(i)==len(self.memFuncsByVariable[0]) for i in self.memFuncsByVariable)
self.trainingType = 'Not trained yet'
def LSE(self, A, B, initialGamma = 1000.):
coeffMat = A
rhsMat = B
S = np.eye(coeffMat.shape[1])*initialGamma
x = np.zeros((coeffMat.shape[1],1)) # need to correct for multi-dim B
for i in range(len(coeffMat[:,0])):
a = coeffMat[i,:]
b = np.array(rhsMat[i])
S = S - (np.array(np.dot(np.dot(np.dot(S,np.matrix(a).transpose()),np.matrix(a)),S)))/(1+(np.dot(np.dot(S,a),a)))
x = x + (np.dot(S,np.dot(np.matrix(a).transpose(),(np.matrix(b)-np.dot(np.matrix(a),x)))))
return x
def trainHybridJangOffLine(self, epochs=5, tolerance=1e-5, initialGamma=1000, k=0.01):
self.trainingType = 'trainHybridJangOffLine'
convergence = False
epoch = 1
while (epoch < epochs) and (convergence is not True):
#layer four: forward pass
[layerFour, wSum, w] = forwardHalfPass(self, self.X)
#layer five: least squares estimate
layerFive = np.array(self.LSE(layerFour,self.Y,initialGamma))
self.consequents = layerFive
layerFive = np.dot(layerFour,layerFive)
#error
error = np.sum((self.Y-layerFive.T)**2)
print ('current error: ', error)
average_error = np.average(np.absolute(self.Y-layerFive.T))
self.errors = np.append(self.errors,error)
if len(self.errors) != 0:
if self.errors[len(self.errors)-1] < tolerance:
convergence = True
# back propagation
if convergence is not True:
cols = range(len(self.X[0,:]))
dE_dAlpha = list(backprop(self, colX, cols, wSum, w, layerFive) for colX in range(self.X.shape[1]))
if len(self.errors) >= 4:
if (self.errors[-4] > self.errors[-3] > self.errors[-2] > self.errors[-1]):
k = k * 1.1
if len(self.errors) >= 5:
if (self.errors[-1] < self.errors[-2]) and (self.errors[-3] < self.errors[-2]) and (self.errors[-3] < self.errors[-4]) and (self.errors[-5] > self.errors[-4]):
k = k * 0.9
## handling of variables with a different number of MFs
t = []
for x in range(len(dE_dAlpha)):
for y in range(len(dE_dAlpha[x])):
for z in range(len(dE_dAlpha[x][y])):
t.append(dE_dAlpha[x][y][z])
eta = k / np.abs(np.sum(t))
if(np.isinf(eta)):
eta = k
## handling of variables with a different number of MFs
dAlpha = copy.deepcopy(dE_dAlpha)
if not(self.memFuncsHomo):
for x in range(len(dE_dAlpha)):
for y in range(len(dE_dAlpha[x])):
for z in range(len(dE_dAlpha[x][y])):
dAlpha[x][y][z] = -eta * dE_dAlpha[x][y][z]
else:
dAlpha = -eta * np.array(dE_dAlpha)
for varsWithMemFuncs in range(len(self.memFuncs)):
for MFs in range(len(self.memFuncsByVariable[varsWithMemFuncs])):
paramList = sorted(self.memFuncs[varsWithMemFuncs][MFs][1])
for param in range(len(paramList)):
self.memFuncs[varsWithMemFuncs][MFs][1][paramList[param]] = self.memFuncs[varsWithMemFuncs][MFs][1][paramList[param]] + dAlpha[varsWithMemFuncs][MFs][param]
epoch = epoch + 1
self.fittedValues = predict(self,self.X)
self.residuals = self.Y - self.fittedValues[:,0]
return self.fittedValues
def plotErrors(self):
if self.trainingType == 'Not trained yet':
print (self.trainingType)
else:
import matplotlib.pyplot as plt
plt.plot(range(len(self.errors)),self.errors,'ro', label='errors')
plt.ylabel('Pérdida (MSE)')
plt.xlabel('Época')
plt.title('Error del Modelo ANFIS')
plt.show()
def plotMF(self, x, inputVar):
import matplotlib.pyplot as plt
from skfuzzy import gaussmf, gbellmf, sigmf
for mf in range(len(self.memFuncs[inputVar])):
if self.memFuncs[inputVar][mf][0] == 'gaussmf':
y = gaussmf(x,**self.memClass.MFList[inputVar][mf][1])
elif self.memFuncs[inputVar][mf][0] == 'gbellmf':
y = gbellmf(x,**self.memClass.MFList[inputVar][mf][1])
elif self.memFuncs[inputVar][mf][0] == 'sigmf':
y = sigmf(x,**self.memClass.MFList[inputVar][mf][1])
plt.plot(x,y,'r')
plt.show()
def plotResults(self):
if self.trainingType == 'Not trained yet':
print (self.trainingType)
else:
import matplotlib.pyplot as plt
plt.plot(range(len(self.fittedValues)),self.fittedValues,'r',linestyle='-', label='trained')
plt.plot(range(len(self.Y)),self.Y,'b', linestyle='--',label='original')
plt.title('Resultados del Modelo ANFIS')
plt.legend(loc='upper left')
plt.ylabel('Valor Experimental o Teórico')
plt.xlabel('Índice de Muestra')
plt.show()
def forwardHalfPass(ANFISObj, Xs):
layerFour = np.empty(0,)
wSum = []
for pattern in range(len(Xs[:,0])):
#layer one
layerOne = ANFISObj.memClass.evaluateMF(Xs[pattern,:])
#layer two
miAlloc = [[layerOne[x][ANFISObj.rules[row][x]] for x in range(len(ANFISObj.rules[0]))] for row in range(len(ANFISObj.rules))]
layerTwo = np.array([np.prod(x) for x in miAlloc]).T
if pattern == 0:
w = layerTwo
else:
w = np.vstack((w,layerTwo))
#layer three
wSum.append(np.sum(layerTwo))
if pattern == 0:
wNormalized = layerTwo/wSum[pattern]
else:
wNormalized = np.vstack((wNormalized,layerTwo/wSum[pattern]))
#prep for layer four (bit of a hack)
layerThree = layerTwo/wSum[pattern]
rowHolder = np.concatenate([x*np.append(Xs[pattern,:],1) for x in layerThree])
layerFour = np.append(layerFour,rowHolder)
w = w.T
wNormalized = wNormalized.T
layerFour = np.array(np.array_split(layerFour,pattern + 1))
return layerFour, wSum, w
def backprop(ANFISObj, columnX, columns, theWSum, theW, theLayerFive):
paramGrp = [0]* len(ANFISObj.memFuncs[columnX])
for MF in range(len(ANFISObj.memFuncs[columnX])):
parameters = np.empty(len(ANFISObj.memFuncs[columnX][MF][1]))
timesThru = 0
for alpha in sorted(ANFISObj.memFuncs[columnX][MF][1].keys()):
bucket3 = np.empty(len(ANFISObj.X))
for rowX in range(len(ANFISObj.X)):
varToTest = ANFISObj.X[rowX,columnX]
tmpRow = np.empty(len(ANFISObj.memFuncs))
tmpRow.fill(varToTest)
bucket2 = np.empty(ANFISObj.Y.ndim)
for colY in range(ANFISObj.Y.ndim):
rulesWithAlpha = np.array(np.where(ANFISObj.rules[:,columnX]==MF))[0]
adjCols = np.delete(columns,columnX)
senSit = partial_dMF(ANFISObj.X[rowX,columnX],ANFISObj.memFuncs[columnX][MF],alpha)
# produces d_ruleOutput/d_parameterWithinMF
dW_dAplha = senSit * np.array([np.prod([ANFISObj.memClass.evaluateMF(tmpRow)[c][ANFISObj.rules[r][c]] for c in adjCols]) for r in rulesWithAlpha])
bucket1 = np.empty(len(ANFISObj.rules[:,0]))
for consequent in range(len(ANFISObj.rules[:,0])):
fConsequent = np.dot(np.append(ANFISObj.X[rowX,:],1.),ANFISObj.consequents[((ANFISObj.X.shape[1] + 1) * consequent):(((ANFISObj.X.shape[1] + 1) * consequent) + (ANFISObj.X.shape[1] + 1)),colY])
acum = 0
if consequent in rulesWithAlpha:
acum = dW_dAplha[np.where(rulesWithAlpha==consequent)] * theWSum[rowX]
acum = acum - theW[consequent,rowX] * np.sum(dW_dAplha)
acum = acum / theWSum[rowX]**2
bucket1[consequent] = fConsequent * acum
sum1 = np.sum(bucket1)
if ANFISObj.Y.ndim == 1:
bucket2[colY] = sum1 * (ANFISObj.Y[rowX]-theLayerFive[rowX,colY])*(-2)
else:
bucket2[colY] = sum1 * (ANFISObj.Y[rowX,colY]-theLayerFive[rowX,colY])*(-2)
sum2 = np.sum(bucket2)
bucket3[rowX] = sum2
sum3 = np.sum(bucket3)
parameters[timesThru] = sum3
timesThru = timesThru + 1
paramGrp[MF] = parameters
return paramGrp
def predict(ANFISObj, varsToTest):
[layerFour, wSum, w] = forwardHalfPass(ANFISObj, varsToTest)
#layer five
layerFive = np.dot(layerFour,ANFISObj.consequents)
return layerFive
if __name__ == "__main__":
print ("I am main!")
#import numpy as np
#import pandas as pd
# Leer el dataset desde un archivo Excel
#file_path = r"C:\Users\cesar\Desktop\Proyecto-Gas Natural\resultados_parcial.xlsx"
#df = pd.read_excel(file_path)
# Seleccionar las primeras tres columnas como entradas (Ppr, Tpr, X)
#X = df.iloc[:, 0:3].values
# Seleccionar la cuarta columna como salida (Z_exp)
#Y = df.iloc[:, 3].values
# Mostrar estadísticas descriptivas del dataset
#print("Estadísticas descriptivas del dataset:")
#print(df.describe())
# Diseñar las funciones de membresía especificando la media y sigma
#mf = [
# [['gaussmf', {'mean': 2.6, 'sigma': .25}],
# ['gaussmf', {'mean': 2.2, 'sigma': .25}],
# ['gaussmf', {'mean': 1.8, 'sigma': .25}],
# ['gaussmf', {'mean': 1.4, 'sigma': .25}]],
#
# [['gaussmf', {'mean': 2.6, 'sigma': .24}],
# ['gaussmf', {'mean': 2.2, 'sigma': .24}],
# ['gaussmf', {'mean': 1.8, 'sigma': .24}],
# ['gaussmf', {'mean': 1.4, 'sigma': .24}]],
#
# [['gaussmf', {'mean': 2.6, 'sigma': .23}],
# ['gaussmf', {'mean': 2.2, 'sigma': .23}],
# ['gaussmf', {'mean': 1.8, 'sigma': .23}],
# ['gaussmf', {'mean': 1.4, 'sigma': .23}]]
#]
# Crear un objeto para las funciones de membresía
#mfc = MemFuncs(mf)
# Crear un objeto ANFIS
#anf = ANFIS(X, Y, mfc)
# Método de entrenamiento híbrido fuera de línea
#print("Entrenando el modelo ANFIS...")
#Pred = anf.trainHybridJangOffLine(epochs=20)
#print("Entrenamiento completo.")
# Graficar el error
#print("Graficando el error...")
#anf.plotErrors()
# Mostrar los resultados
#print("Resultados:")
#anf.plotResults()
# Calcular y mostrar el error cuadrático medio (RMSE)
#rmse = np.sqrt(((Pred - Y) ** 2).mean())
#print(f"Root Mean Square Error (RMSE): {rmse}")
#Agregar predicciones al DataFrame
#df['Z(ANFIS)'] = Pred
# Guardar el DataFrame en un archivo Excel
#df.to_excel(r'C:\Users\cesar\Desktop\Proyecto-Gas Natural\resultados_final.xlsx', index=False)
# Nuevos datos de entrada para predecir (Ppr, Tpr, X)
#new_data = np.array([[10.61, 1.72, 6.1686]])
# Realizar predicciones
#predictions = predict(anf,new_data)
#print("Predicciones realizadas:")
#print(predictions)