-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFQRC.py
400 lines (323 loc) · 12.6 KB
/
FQRC.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
# -*- coding: utf-8 -*-
"""
@author: ChernHong Lim
"""
import numpy as np
import matplotlib.pyplot as plt
import copy
def CL_FQRC_Train(X_train, y_train, binNum, visualize):
yUnique = np.unique(y_train)
fqmf = [];
fqmf_mu = [];
for i in yUnique:
X_filt = X_train[y_train == i]
mf,mu = build4tuplesMF(X_filt , binNum)
fqmf.append(mf)
fqmf_mu.append(mu)
if(visualize):
mfVisualize(fqmf)
histVisualize(fqmf, fqmf_mu)
return fqmf
def CL_FQRC_Predict(X_test, fqmf, visualize):
output,feaDegreeMF = inference(X_test, fqmf)
if(visualize):
infVisualize(X_test, fqmf, feaDegreeMF)
return output
def build4tuplesMF(feaMat , binNum):
# Parameters initialization
B = binNum #num of bin
feaMat = feaMat #feature matrix
J = feaMat.shape[1] #num of features (also indicate that num of 4-tuples membership function will be builded at the end)
mf = np.zeros((J,4))
mu = [];
for j in range(0,J): #start building MF
# calculate the bin width, v
v = (float(np.amax(feaMat[:,j])) - float(np.amin(feaMat[:,j]))) / float(B)
# count the ocurrence of the data in the bin and represent in histogram
h = np.histogram(feaMat[:,j],B);
N = h[0]
xout = h[1]
# calculate how many bins which have distributed data > 0 (denoted as b)
b = 0
for n in range(0,len(N)):
if (N[n] > 0):
b = b + 1;
# Calculate mean value (mu) for the histogram
histMean = float(sum(N)) / b;
"""
% Find 4-tuple trapezoid position from histogram
% _________
% /| |\
% / | | \
% / | | \
% c a b d
%
% a-c : alpha
% d-b : beta
% 4-tuple = [a,b,alpha,beta]
"""
# Scan from left to right to obtain a value
for n in range(0,len(N)):
if(N[n] >= histMean):
a = xout[n] #include the offset to get the lower boundary of that bar
break
# Scan from right to left to obtain b value
for n in range(len(N)-1,-1,-1):
if(N[n] >= histMean):
b = xout[n+1] #include the offset to get the upper boundary of that bar
break
# obtain a value
c = xout[0] - v;
# obtain b value
d = xout[len(xout)-1] + v;
# compute alpha
alpha = a - c;
# compute beta
beta = d - b;
# Output
mf[j,:] = [a,b,alpha,beta]
mu.append([histMean, N, xout])
# #Plot hist for visualization
# width = 0.9 * (xout[1] - xout[0])
# center = (xout[:-1] + xout[1:]) / 2
# plt.bar(center, N, align='center', width=width)
# plt.plot([a,b],[histMean,histMean],'ro')
# datax = [c,a,b,d]
# datay = np.array([0,histMean,histMean,0])
# plt.plot(datax,datay,'r--')
# plt.show()
return mf,mu
def inference( feaVec, fqmf):
J = len(fqmf[0]) #num of feature
K = len(fqmf) #num of class
# Obtain degree of membership for each feature value
feaDegreeMF = np.zeros((K,J))
for k in range(0,K):
for j in range(0,J):
degreeMF = membershipVal(feaVec[j], fqmf[k][j]);
feaDegreeMF[k][j] = degreeMF;
temp = copy.copy(feaDegreeMF)
temp[feaDegreeMF > 0] = 1
hitCount = np.sum(temp,axis=1)
sumOfdegreeMF = np.sum(feaDegreeMF,axis=1)
ratio = np.divide(sumOfdegreeMF, np.amax(hitCount))
sumRatio = sum(ratio)
normOfdegreeMF = np.divide(ratio,sumRatio) #Normalization
output = normOfdegreeMF
if(np.isnan(sum(output))==True or np.isinf(sum(output))==True):
output = np.zeros((1,K))
return output, feaDegreeMF
def membershipVal(fvalue, mf):
# mf -> 4-tuples number retrieve from FQRC (mf = [a b alpha beta])
a = mf[0]
b = mf[1]
alpha = mf[2]
beta = mf[3]
if (fvalue >= a and fvalue <= b): # f_value within [a,b]
degreeMF = 1
elif (fvalue >= a-alpha and fvalue < a): # x within [a-alpha,a]
degreeMF = (fvalue - a + alpha) / alpha
elif (fvalue > b and fvalue <= b+beta): # x within [b,b+beta]
degreeMF = (b + beta - fvalue) / beta
else:
degreeMF = 0
return degreeMF
def histVisualize(fqmf, fqmf_mu):
if(type(fqmf) is list):
J = len(fqmf_mu[0]) #num of feature
K = len(fqmf_mu) #num of class
fig, axes = plt.subplots(J, K, figsize=(6,J*2))
# fig.subplots_adjust(top=0.85)
# fig..autoscale_view(True,True,True)
fig.tight_layout()
for k in range(0,K):
mf = fqmf[k]
mu = fqmf_mu[k]
for j in range(0,J):
#convert back to [c a b d] fuzzy tuple
c = mf[j,0] - mf[j,2]
a = mf[j,0]
b = mf[j,1]
d = mf[j,1] + mf[j,3]
xout = mu[j][2]
N = mu[j][1]
histMean = mu[j][0]
#Plot hist for visualization
width = 0.9 * (xout[1] - xout[0])
center = (xout[:-1] + xout[1:]) / 2
datax = [c,a,b,d]
datay = np.array([0,histMean,histMean,0])
axes[j,k].bar(center, N, align='center', width=width)
axes[j,k].plot([a,b],[histMean,histMean],'ro')
axes[j,k].plot(datax,datay,'r--')
# plt.show()
#
else:
mf = copy.copy(fqmf)
mu = copy.copy(fqmf_mu)
J = len(mf)
fig, axes = plt.subplots(J)
fig.tight_layout()
for j in range(0,J):
#convert back to [c a b d] fuzzy tuple
c = mf[j,0] - mf[j,2]
a = mf[j,0]
b = mf[j,1]
d = mf[j,1] + mf[j,3]
xout = mu[j][2]
N = mu[j][1]
histMean = mu[j][0]
#Plot hist for visualization
width = 0.9 * (xout[1] - xout[0])
center = (xout[:-1] + xout[1:]) / 2
datax = [c,a,b,d]
datay = np.array([0,histMean,histMean,0])
axes[j].bar(center, N, align='center', width=width)
axes[j].plot([a,b],[histMean,histMean],'ro')
axes[j].plot(datax,datay,'r--')
# plt.show()
plt.show()
def mfVisualize(fqmf):
if(type(fqmf) is list): # to solve issue if only one class in the mf
J = len(fqmf[0]) #num of feature
K = len(fqmf) #num of class
fig, axes = plt.subplots(J, K, figsize=(6,J*2))
fig.tight_layout()
for k in range(0,K):
mf = fqmf[k]
xmin = np.amin(mf[:,0:2])-np.amax(mf[:,2:4])
xmax = np.amax(mf[:,0:2])+np.amax(mf[:,2:4])
for j in range(0,J):
#convert back to [c a b d] fuzzy tuple
c = mf[j,0] - mf[j,2]
a = mf[j,0]
b = mf[j,1]
d = mf[j,1] + mf[j,3]
datax = [c,a,b,d]
datay = np.array([0,1,1,0])
axes[j,k].plot(datax,datay)
axes[j,k].set_xlim(xmin,xmax)
axes[j,k].set_ylim(0,1.1)
# plt.ylabel('Degree of Membership')
# plt.axis([-1, 10, 0, 1.1])
# plt.show()
else:
mf = copy.copy(fqmf)
J = len(mf)
fig, axes = plt.subplots(J)
fig.tight_layout()
xmin = np.amin(mf[:,0:2])-np.amax(mf[:,2:4])
xmax = np.amax(mf[:,0:2])+np.amax(mf[:,2:4])
for j in range(0,J):
#convert back to [c a b d] fuzzy tuple
c = mf[j,0] - mf[j,2]
a = mf[j,0]
b = mf[j,1]
d = mf[j,1] + mf[j,3]
datax = [c,a,b,d]
datay = np.array([0,1,1,0])
axes[j].plot(datax,datay)
# axes[j].ylabel('Degree of Membership')
axes[j].set_xlim(xmin,xmax)
axes[j].set_ylim(0,1.1)
plt.show()
def infVisualize(feaVec, fqmf, feaDegreeMF):
if(type(fqmf) is list): # to solve issue if only one class in the mf
J = len(fqmf[0]) #num of feature
K = len(fqmf) #num of class
fig, axes = plt.subplots(J, figsize=(4,J*1.5))
fig.tight_layout()
for j in range(0,J):
# xminFinal = 0
# xmaxFinal = 0
for k in range(0,K):
mf = fqmf[k]
# xmin = np.amin(mf[:,0:2])-np.amax(mf[:,2:4])
# xmax = np.amax(mf[:,0:2])+np.amax(mf[:,2:4])
#
# if(xmin < xminFinal):
# xminFinal = xmin
#
# if(xmax > xmaxFinal):
# xmaxFinal = xmax
c = mf[j,0] - mf[j,2]
a = mf[j,0]
b = mf[j,1]
d = mf[j,1] + mf[j,3]
datax = [c,a,b,d]
datay = np.array([0,1,1,0])
axes[j].plot(datax,datay)
axes[j].legend((feaDegreeMF[:,j]))
axes[j].set_title("Degree of Membership")
# axes[j].set_xlim(xminFinal,xmaxFinal)
for j in range(0,J):
axes[j].plot([feaVec[j],feaVec[j]],[0,1.1],'r--')
for (n), subplot in np.ndenumerate(axes):
# subplot.set_xlim(xminFinal,xmaxFinal)
subplot.set_ylim(0,1.1)
else:
mf = copy.copy(fqmf)
J = len(mf)
fig, axes = plt.subplots(J)
xmin = np.amin(mf[:,0:2])-np.amax(mf[:,2:4])
xmax = np.amax(mf[:,0:2])+np.amax(mf[:,2:4])
for j in range(0,J):
#convert back to [c a b d] fuzzy tuple
c = mf[j,0] - mf[j,2]
a = mf[j,0]
b = mf[j,1]
d = mf[j,1] + mf[j,3]
datax = [c,a,b,d]
datay = np.array([0,1,1,0])
axes[j].plot(datax,datay)
# axes[j].ylabel('Degree of Membership')
axes[j].set_xlim(xmin,xmax)
axes[j].set_ylim(0,1.1)
axes[j].plot([feaVec[j],feaVec[j]],[0,1.1],'r-')
axes[j].legend((feaDegreeMF[:,j]))
axes[j].set_title("Degree of Membership")
plt.show()
"""""""""""""""""""""
Test build mf
"""""""""""""""""""""
#a = np.array([(1,4,6),(2,5,7),(2,5,8),(3,4,8),(3,5,7),(2,6,9)])
#mf,mu = build4tuplesMF(a,3)
#mfVisualize(mf)
#histVisualize(mf,mu)
"""""""""""""""""""""
Test build mf
"""""""""""""""""""""
#mf = np.array([4, 5, 1, 1])
#membership_degree = membershipVal(3.7, mf)
"""""""""""""""""""""
Test inference
"""""""""""""""""""""
#a = np.array([(1,4,6),(2,5,7),(2,5,8),(3,4,8),(3,5,7),(2,6,9)]) # Class 1
#mf_a,mu_a = build4tuplesMF(a,3)
##mfVisualize(mf_a)
##histVisualize(mf_a,mu_a)
#
#b = np.array([(4,6,9),(4,7,10),(3,7,11),(5,7,10),(4,8,10),(5,8,11)]) # Class 2
#mf_b,mu_b = build4tuplesMF(b,3)
##mfVisualize(mf_b)
##histVisualize(mf_b,mu_b)
#
#mf_all = [] # To append membership functions for all classes
#mf_all.append(mf_a)
#mf_all.append(mf_b)
#
#feaVec = np.array([2.5,4.5,9.5]) # New input with feature values
#output,feaDegreeMF = inference(feaVec, mf_all)
#infVisualize(feaVec, mf_all, feaDegreeMF)
#print output
"""""""""""""""""""""
Test CL_FQRC_Train and CL_FQRC_Predict
"""""""""""""""""""""
#a = np.array([(1,4,6),(2,5,7),(2,5,8),(3,4,8),(3,5,7),(2,6,9),(4,6,9),(4,7,10),(3,7,11),(5,7,10),(4,8,10),(5,8,11)])
#a_groundTruth = np.array([0,0,0,0,0,0,1,1,1,1,1,1])
#
#fqmf = CL_FQRC_Train(a, a_groundTruth, 3, True) # Training step
#
#feaVec = np.array([2.5,4.5,9.5]) #--> new testing input
#output = CL_FQRC_Predict(feaVec, fqmf, True) # Prediction step
#print 'output:' + str(output)