-
Notifications
You must be signed in to change notification settings - Fork 0
/
trklearn.py
334 lines (257 loc) · 11.5 KB
/
trklearn.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
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 10 17:17:41 2020
This script is for generating synthetic data.
You can use multi-class data to generate balance dataset.
Abdullah BAS
BME Bogazici University
Istanbul / Uskudar
@author: abas
"""
import numpy as np
from sklearn import neighbors
from sklearn.cluster import KMeans
def EuclidianDistance(data1,data2):
"""Euclidian Distance implementation
Args:
data1 (float): data point 1
data2 (float): data point 2
Returns:
[float]: distance between two data points
"""
dist=np.sqrt(sum([(np.square(x)) for x in np.array(data1)-np.array(data2)]))
return dist
class MinMaxNormalization():
"""
Min-Max Normalization. Was using in conjunction of ADASYN to test results
data: Data to be normalized
axis: 0 is by columns, 1 is by rows
returns: Normalized data
"""
def __init__(self, data, axis=0):
self.row_min = np.min(data, axis=axis)
self.row_max = np.max(data, axis=axis)
self.denominator = abs(self.row_max - self.row_min)
# Fix divide by zero, replace value with 1 because these usually happen for boolean columns
for index, value in enumerate(self.denominator):
if value == 0:
self.denominator[index] = 1
def __call__(self, data):
return np.divide((data - self.row_min), self.denominator)
#☻target=np.array(X.iloc[:,-1])
class ASUWO():
def ASUWO(Xnp,target,n,k,irt,de=-1,normalization=1):
"""ASUWO is supporting multi-class synthetic data generation.
Args:
Xnp (type:all): Input array must be numpy array
target (type:all): Corresponding response to Xnp
n ([type]):
k (int): Neighbours number
irt (float): Minimum imbalance ratio targeted
knn ([type]): [description]
de (int, optional): . Defaults to -1.
normalization (bool, optional): Switch for normalization. Defaults to 1.
"""
targetarry=np.unique(np.array(target))
targetNums=[]
targetClasses=[]
for classes in targetarry:
targetNums.append(sum(target==classes))
mi=max(targetNums)
ms=min(targetNums)
maxClassİnd=targetNums.index(mi)
tn=list(targetNums)
del tn[tn.index(mi)]
def semiUnsCls(Xnp,target,normalization=normalization):
"""This function is for clustering
Args:
Xnp (float): Input data
target (float): Target/Response data (gt)
normalization (bool, optional): Defaults to normalization.
"""
test=np.Inf
clf = neighbors.KNeighborsClassifier()
clf.fit(Xnp[target==targetarry[targetNums.index(mi)]], target[target==targetarry[targetNums.index(mi)]])
clf2 = neighbors.KNeighborsClassifier()
clf2.fit(Xnp, target)
Xsub=np.array(Xnp)
Xsub=Xnp[target==targetarry[targetNums.index(mi)]]
Xsub2=list(Xsub)
cond=0
indices2=[]
while len(Xsub2)>0:
xi=Xsub[cond]
cond=cond+1
neighbours = clf.kneighbors(xi.reshape(1,-1), n_neighbors=2, return_distance=True)
neig2=clf2.kneighbors(xi.reshape(1,-1), n_neighbors=2, return_distance=True)
neig3=clf2.kneighbors(Xsub[neighbours[1][0][1] ].reshape(1,-1),n_neighbors=2)
print( "{} değerli {} elemanın {} elemana en yakın".format(neighbours[0][0][1],neig2[1][0][0],neig3[1][0][1]) )
if neighbours[0][0][1]<test and neig2[1][0][0]==neig3[1][0][1]:
test=neighbours[0][0][1]
indices=[cond,int(neighbours[1][0][1])]
del Xsub2[indices[0]]
del Xsub2[indices[1]]
indices2.append(indices)
indices=[]
filteredClusters=[]
kmeans = KMeans(n_clusters=k, random_state=0).fit(Xnp)
clusters=kmeans.predict(Xnp)
targetarry=np.unique(np.array(target))
targetNums=[]
targetClasses=[]
for classes in targetarry:
targetNums.append(sum(target==classes))
mi=max(targetNums)
maxClassİnd=targetNums.index(mi)
tn=list(targetNums)
del tn[tn.index(mi)]
for i in range(k):
buff=(np.multiply((clusters==i),target+1))
for j in targetarry:
if irt<((sum(buff==j+1)+1)/(sum(buff==targetarry[targetNums.index(mi)]+1)+1)):
filteredClusters.append(i)
class ADASYN():
def ADASYN(Xnp,target,verbose=True,B=1,K=15,threshold=0.7):
""" This class is implementation of ADASYN.
Args:
Xnp (np.array): Input array must be numpy
target (np.array): response array
verbose (bool, optional): If zero will not output any verbose. Defaults to True.
B (int, optional): B is the balance ratio that you want to reach. Defaults to 1.
K (int, optional): Numbers of neighbours. Defaults to 15.
threshold (float, optional): Activation threshold. Above this balance ratio function will not work. Defaults to 0.7.
Returns:
[type]: [description]
"""
clf=neighbors.KNeighborsClassifier()
clf.fit(Xnp,target)
targetarry=np.unique(np.array(target))
targetNums=[]
targetClasses=[]
for classes in targetarry:
targetNums.append(sum(target==classes))
mi=max(targetNums)
maxClassİnd=targetNums.index(mi)
tn=list(targetNums)
del tn[tn.index(mi)]
r=[]
r2=[]
riP=[]
riP2=[]
si=[]
si2=np.zeros((1,Xnp.shape[1]+1))
for idx,ms in enumerate(tn):
d=ms/mi
if d<threshold:
G=(mi-ms)*B
msClass=Xnp[target==targetNums.index(ms)]
r2=[]
for idx2,xi in enumerate(msClass):
neighbours = clf.kneighbors(xi.reshape(1,-1), n_neighbors=K, return_distance=False)[0]
delta=sum(target[neighbours]==idx)
r2.append((K-delta)/K)
if verbose==True:
print("Class {} X{} R{}={}".format(idx,idx2,idx2,(K-delta)/K))
r.append(r2)
for idx3,ri in enumerate(r2):
riP2.append(ri/sum(r2))
if verbose==True:
print("riP{} have created = {}".format(idx3,ri/sum(r2)))
riP.append(riP2)
gi=np.multiply(riP2,G)
riP2=[]
gi=np.round(gi)
for idx4,num in enumerate(gi):
for idx5 in range(int(num)):
neighbours = clf.kneighbors(msClass[idx4,:].reshape(1,-1), n_neighbors=K, return_distance=False)[0]
buff=(msClass[idx4,:].reshape(1,-1)+np.multiply((Xnp[neighbours[np.random.randint(0,K)]]-
msClass[idx4,:].reshape(1,-1)),np.random.random(1)))
si2=np.vstack((si2,np.array(list(buff[0])+[(targetarry[targetNums.index(ms)])])))
if verbose==True:
print("{}.element of {}gi created which is the {}.element of created data ".format(idx5+1,idx4,idx4+idx5))
si.append(si2[1:-1,:])
r2=[]
si2=np.zeros((1,Xnp.shape[1]+1))
return si,riP,r,gi
def fit_resample(Xnp,target,B=1,K=15,threshold=0.7):
""" fit_resample stands for outputting the generated data combined with the input data
Args:
Xnp (float): Input data
target (float,int): Corresponding response.
B (int, optional): Balance ratio. It is the threshold for the generated data. Defaults to 1.
K (int, optional): K-neigbours. Defaults to 15.
threshold (float, optional): It is the threshold for imbalance ratio. Function runs only below this ratio. Defaults to 0.7.
Returns:
[float]: Output xnp
[float]: Output target
"""
si,riP,r,gi=ADASYN.ADASYN(Xnp,target,B=B,K=K,threshold=threshold)
for x in si:
Xnp=np.vstack((Xnp,x[:,:-1]))
target=np.array(list(target)+list(x[:,-1]))
return Xnp,target
class SMOTE():
def SMOTE(Xnp,target,N=-1,threshold=0.7,verbose=True):
"""Implementation of SMOTE algorithm
Args:
Xnp (float): Input data
target (float): Target/Response array
N (int, optional): Maximum class. If it is not known left it to default. Defaults to -1.
threshold (float, optional): [description]. Defaults to 0.7.
verbose (bool, optional): [description]. Defaults to True.
Returns:
[float]: xiP2 only generated synthetic data
"""
targetarry=np.unique(np.array(target))
targetNums=[]
targetClasses=[]
for classes in targetarry:
targetNums.append(sum(target==classes))
mi=max(targetNums)
maxClassİnd=targetNums.index(mi)
tn=list(targetNums)
del tn[tn.index(mi)]
clf = neighbors.KNeighborsClassifier()
clf.fit(Xnp, target)
xiP2=[]
xiP=np.zeros((1,Xnp.shape[1]+1))
for idx,Ins in enumerate(tn):
if N==-1:
N=np.ceil(mi/Ins).astype(int)
N=N-1
Xnsp=Xnp[target== targetarry[targetNums.index(Ins)],:]
clf = neighbors.KNeighborsClassifier()
clf.fit(Xnsp, target[target==targetarry[targetNums.index(Ins)]])
if verbose==True:
print("N is ={}".format(N))
for idx2,xi in enumerate(Xnsp):
neighbours = clf.kneighbors(xi.reshape(1,-1),
n_neighbors=N, return_distance=False)[0]
#print(neighbours)
for idx3,ik in enumerate(neighbours):
xki=Xnsp[ik,:]
xiP=np.vstack((xiP,np.array((list(xi+(np.random.random(1)*(xi-xki)))+
[targetarry[targetNums.index(Ins)]]))))
if verbose==True:
print("{}.element of minority class {} has been created.".format(idx2+idx3,targetarry[targetNums.index(Ins)]))
xiP2.append(xiP[1:-1,:])
xiP=np.zeros((1,Xnp.shape[1]+1))
return xiP2
def fit_resample(Xnp,target,N=-1,threshold=0.7,verbose=True):
"""fit_resample is the function that outputs the input data and generated data combined in one array.
Args:
Xnp (float): Input data
target (float): Target/Response array
N (int, optional): Class that has the maximum elements. Defaults to -1.
threshold (float, optional): Activation threshold of imbalance ratio. Below this threshold function will run. Defaults to 0.7.
verbose (bool, optional): Defaults to True.
Returns:
[float]: Xnp output
[float]: target output
"""
xiP=SMOTE.SMOTE(Xnp,target,N=N,threshold=threshold,verbose=verbose)
for x in xiP:
Xnp=np.vstack((Xnp,x[:,:-1]))
target=np.array(list(target)+list(x[:,-1]))
return Xnp,target