-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
1396 lines (1155 loc) · 48.7 KB
/
utils.py
File metadata and controls
1396 lines (1155 loc) · 48.7 KB
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import random
import re
from string import punctuation
import matplotlib.pyplot as plt
import numpy as np
import scipy
np.random.seed(42)
def qp_lc(h, c, I, e=None):
"""
Notes:
- use active set method to solve quadratic programming-linear constraint problem
- if there is equality, remember to initialize x to be satisfied, if you have equality more than
1, change line 10
- only for positive definite matrix
:param e: augmented matrix
:param i: augmented matrix, must be smaller or equal than b
"""
m = len(c)
x = np.zeros(m) # must satisfy equality, remember to change it
if e is not None:
# assume there is only one equality
A = np.concatenate((I[:,:-1], np.expand_dims(e[:-1],axis=0)), axis=0)
b = np.concatenate((I[:,-1],np.expand_dims(e[-1],axis=0)),axis=0)
e_len = 1
else:
A = I[:, :-1]
b = I[:, -1]
e_len = 0
w = []
# assume x=0 satisfy all equality
for i in range(A.shape[0]):
if A[i] @ x == b[i]:
w.append(i)
A_w = A[w]
b_w = b[w]
StopFlag = 0
k = 0
while not StopFlag:
# solve QP-SUB to get d
g = h @ x + c
d = - np.linalg.inv(h) @ (np.eye(m) - A_w.T @ np.linalg.inv((A_w @ np.linalg.inv(h) @ A_w.T)+1e-8*np.eye(A_w.shape[0]))
@ A_w @ np.linalg.inv(h)) @ g
if np.all(d <= 1e-8):
Lambda = - np.linalg.inv((A_w @ np.linalg.inv(h) @ A_w.T)) @ (A_w @ np.linalg.inv(h) @ c + b_w)
if e_len == 0:
Lambda_q = np.min(Lambda)
q = np.argmin(Lambda)
else:
Lambda_q = np.min(Lambda[:-e_len])
q = np.argmin(Lambda[:-e_len])
if Lambda_q >= 0:
StopFlag = 1
else:
A_w = np.concatenate((A_w[:q],A_w[q+1:]), axis=0)
b_w = np.concatenate((b_w[:q],b_w[q+1:]), axis=0)
else:
index = np.where(A@d > 1e-8)[0]
temp = np.min((b[index] - A[index] @ x) / (A[index] @ d))
p = np.argmin((b[index] - A[index] @ x) / (A[index] @ d))
p = index[p]
alpha = np.min((temp, 1))
x = x + alpha * d
if temp <= 1:
A_w = np.concatenate((np.expand_dims(A[p],axis=0), A_w), axis=0)
b_w = np.concatenate((np.expand_dims(b[p], axis=0), b_w), axis=0)
k += 1
return x
# use for language process
with open('stopwords.txt', 'r', encoding='utf-8') as file:
stopwords = file.read().splitlines()
stopwords_set = set(stopwords)
def one_hot_encoding(y):
cats = np.unique(y)
i = 0
one_hot_y = np.zeros((len(y), len(cats)))
for cat in cats:
t = np.zeros(len(cats))
t[i] = 1
one_hot_y[y==cat] = t
i += 1
return one_hot_y
def plot_loss(loss):
x = np.arange(0,len(loss)) + 1
plt.plot(x,loss)
plt.xlabel('epochs')
plt.ylabel('loss')
plt.show()
def k_fold(x,y,k):
"""
Examples:
folds = k_fold(train_matrix,train_labels,10)
for (x_train, y_train, x_val, y_val) in folds:
training process..
"""
m = len(y)
n = m // k
folds = []
data = np.c_[x, y]
np.random.shuffle(data)
for i in range(k):
start = i * n
end = start + n if i != k - 1 else m
val_set = data[start:end]
train_set = np.vstack((data[:start], data[end:]))
x_train, y_train = train_set[:, :-1], train_set[:, -1]
x_val, y_val = val_set[:, :-1], val_set[:, -1]
folds.append((x_train, y_train, x_val, y_val))
return folds
def create_voca(x):
"""
Args:
x: a list of sentences
Returns: a vocabulary which contains the word that appear in the list(at least 5 times)
"""
words = []
voca = []
for sentence in x:
re_punc = re.sub(f"[{re.escape(punctuation)}]", "", sentence).split()
word_lower = [word.lower() for word in re_punc]
words.extend(word_lower)
words, counts = np.unique(np.array(words), return_counts=True)
for word, count in zip(words, counts):
if count >= 5:
voca.append(word)
# dict[word] = count
return voca
def voca_frequency(x, voca):
"""
Args:
x: a list of sentences
voca: vocabulary return form function create_voca
Returns: a matrix of the frequency of each word in voca
"""
k = len(voca)
x_matrix = np.zeros((len(x),k))
i = 0
for sentence in x:
word_list = []
words_count = np.zeros(k)
re_punc = re.sub(f"[{re.escape(punctuation)}]", "", sentence).split()
word_lower = [word.lower() for word in re_punc]
for word in word_lower:
if word in voca:
word_list.append(word)
words, counts = np.unique(np.array(word_list), return_counts=True)
for word, count in zip(words, counts):
if word in voca:
idx = voca.index(word)
words_count[idx] = count
x_matrix[i,:] = words_count
i+=1
return x_matrix
def plot(model,x,y, if_svm=False):
"""
Notes:
* would only take the first and second feature of your sample
* only apply to binary classification
* plot from 3 dim to 2 dim
"""
# x = model.count(x)
x1,x2 = np.meshgrid(np.linspace(x[:,0].min()-1,x[:,0].max()+1,20),np.linspace(x[:,1].min()-1,x[:,1].max()+1,20))
if if_svm:
z = model.predict(np.c_[x1.ravel(),x2.ravel()], plot=True)
else:
z = model.predict(np.c_[x1.ravel(), x2.ravel()])
z = z.reshape(x1.shape)
plt.figure(figsize=(12,8))
plt.contourf(x1,x2,z, levels=[-float('inf'),0,float('inf')],colors=['orange','cyan'])
plt.scatter(x[:, 0], x[:, 1], c=y)
plt.show()
def rbf_kernel(xi,x,sigma=1):
return np.exp(-(xi-x)@(xi-x)/(2*sigma**2))
def rbf_kernel_matrix(x, predict=False, ori_x=None, radius=0.5):
square = np.sum(x*x,axis=1)
if predict:
if ori_x is None:
raise ValueError('in predict mode, you have to give ori_x')
ori_square=np.sum(ori_x*ori_x,axis=1)
gram = x @ ori_x.T
K = np.exp(- (square.reshape(-1,1)+ori_square.reshape(1,-1)-2*gram) / (2 * radius**2))
else:
gram = x @ x.T
K = np.exp(- (square.reshape(-1, 1) + square.reshape(1, -1) - 2 * gram) / (2 * radius ** 2))
return K
def poly_kernel(x,p):
temp = x @ x.T
K = (temp + np.ones(temp.shape))**p
return K
def sign(x):
if x >= 0:
x = 1
else:
x = 0
return x
def add_intercept(x):
m,n = x.shape
x_new = np.zeros((m,n+1))
x_new[:,0] = 1
x_new[:,1:] = x
return x_new
def load_data(path, intercept=False, inverse=False):
# data and label are in the same file
data = np.loadtxt(path,delimiter=',',skiprows=1)
if inverse:
x = data[:, 1:]
y = data[:, 0]
else:
x = data[:,:-1]
y = data[:,-1]
if intercept:
x = add_intercept(x)
return x,y
def matrix_inv(h):
"""
singular matrix is also OK
"""
if np.linalg.det(h) == 0:
h_inv = np.linalg.pinv(h)
else:
h_inv = np.linalg.inv(h)
return h_inv
def sigmoid(x,theta, if_single_input=False):
"""
x is m * n, theta is n * 1, the dimension will be reduced
"""
if if_single_input:
return 1/(1+np.exp(-x))
else:
return 1/(1+np.exp(-x@theta))
class LogisticRegression:
"""
(Newton's Method)
Examples:
lr = utils.LogisticRegression()
lr.fit(x_train,y_train)
lr.predict(x_valid)
lr.precision(x_valid,y_valid)
lr.plot(x_valid,y_valid)
plt.show()
"""
def __init__(self):
self.theta=None
def fit(self,x,y):
"""
use Newton's Method
epsilon = 1e-5
"""
def hessian(x,theta):
w=np.expand_dims(sigmoid(x,theta),1)@np.expand_dims((1-sigmoid(x,theta)),1).T
w=np.diag(np.diag(w))
h=-x.T@w@x
return h
def gradient(x,y,theta):
return x.T@(y-sigmoid(x,theta))
m,n = x.shape
epsilon = 1e-5
theta = np.zeros(n)
theta_next = theta - matrix_inv(hessian(x,theta))@gradient(x,y,theta)
while np.linalg.norm(theta_next-theta,1) >= epsilon:
theta = theta_next
# though is maximum problem, it's still minus, because hessian would be minus
theta_next = theta - matrix_inv(hessian(x, theta)) @ gradient(x, y, theta)
self.theta = theta_next
def predict(self,x):
return np.round(sigmoid(x,self.theta))
def precision(self, x, y):
print(np.mean(self.predict(x) == y))
def plot(self,x,y):
"""
plot 2-dimension hyperplane
"""
bi_y = np.unique(y)
plt.plot(x[y == bi_y[0], -2], x[y == bi_y[0], -1], 'bx', linewidth=2)
plt.plot(x[y == bi_y[1], -2], x[y == bi_y[1], -1], 'go', linewidth=2)
margin1 = (max(x[:, -2]) - min(x[:, -2])) * 0.2
margin2 = (max(x[:, -1]) - min(x[:, -1])) * 0.2
x1 = np.arange(min(x[:, -2]) - margin1, max(x[:, -2]) + margin1, 0.01)
x2 = -(self.theta[0]+self.theta[1]*x1)/self.theta[2]
plt.plot(x1, x2, c='red', linewidth=2)
plt.xlim(x[:, -2].min() - margin1, x[:, -2].max() + margin1)
plt.ylim(x[:, -1].min() - margin2, x[:, -1].max() + margin2)
plt.xlabel('x1')
plt.ylabel('x2')
class GDA(LogisticRegression):
"""
the same usage as LogisticRegression
"""
def __init__(self):
super().__init__()
self.sigma = None
self.miu0 = None
self.miu1 = None
self.fai = None
self.N0 = None
self.N1 = None
def fit(self,x,y):
"""
don't give intercept
"""
x_new = x[:,1:]
x = x_new
m,n = x.shape
self.N1 = sum(y)
self.N0 = sum(1-y)
self.fai = self.N1/m
self.miu1 = x.T @ y/self.N1
self.miu0 = x.T @ (1-y)/self.N0
s1 = (x[y==1]-self.miu1).T @ (x[y==1]-self.miu1)
s0 = (x[y==0]-self.miu0).T @ (x[y==0]-self.miu0)
self.sigma = (s1+s0)/m
self.theta = np.zeros(n+1)
self.theta[1:] = matrix_inv(self.sigma)@(self.miu1-self.miu0)
self.theta[0] = -1/2*(self.miu1+self.miu0)@self.theta[1:]-(self.N1-self.N0)/2*\
np.log(2*np.pi)-np.log((1-self.fai)/self.fai)
class LocallyWeightedLinearRegression():
"""
Examples:
llr = utils.LocallyWeightedLinearRegression()
llr.fit(x_train,y_train)
llr.predict(x_valid)
llr.MSE(y_valid)
llr.plot(x_valid,y_valid)
plt.show()
"""
def __init__(self):
self.y = None
self.x = None
self.pred = None
def fit(self,x,y):
self.x = x
self.y = y
def predict(self,x,tau=0.5):
l, n = x.shape
self.pred = np.zeros(l)
for i in range(l):
w = np.exp(-np.linalg.norm(self.x - x[i],2,1)/(2*tau**2))
w = np.diag(w)
theta = matrix_inv(self.x.T@w@self.x)@(self.x.T@w@self.y)
self.pred[i] = x[i] @ theta
def MSE(self,y):
print(np.linalg.norm(self.pred-y,2))
def plot(self,x,y):
plt.scatter(x[:,-1],y,marker='x',c='b',linewidths=2,label='validation set')
plt.scatter(x[:,-1],self.pred,marker='o',c='r',linewidths=2,label='prediction')
plt.legend()
plt.show()
class NaiveBayes():
"""
Notes:
* y can be any pair str, the only thing you have to change is in line 236,237 and 260,261
Args:
y: str of binary class
x: sentences
Examples:
nb = utils.NaiveBayes()
nb.fit(x_train,y_train)
y_pred = nb.predict(x_valid)
print('precision:', np.mean(y_pred==y_valid))
"""
def __init__(self):
self.fai = None
self.fai_neg = None
self.fai_pos = None
self.email_len = []
self.voca = []
self.dict = {}
self.k = int # the category of words
def count(self,x):
words = []
words_count = np.zeros(self.k)
for sentence in x:
word_list = []
re_punc = re.sub(f"[{re.escape(punctuation)}]", "", sentence).split()
word_lower = [word.lower() for word in re_punc]
for word in word_lower:
if word in self.voca:
word_list.append(word)
words.extend(word_list)
words, counts = np.unique(np.array(words), return_counts=True)
for word, count in zip(words, counts):
if word in self.voca:
idx = self.voca.index(word)
words_count[idx] = count
return words_count
def creat_voca(self,x):
words = []
for sentence in x:
re_punc = re.sub(f"[{re.escape(punctuation)}]", "", sentence).split()
word_lower = [word.lower() for word in re_punc]
words.extend(word_lower)
words, counts = np.unique(np.array(words), return_counts=True)
for word, count in zip(words, counts):
if count >= 5:
self.voca.append(word)
self.dict[word] = count
self.k = len(self.voca)
for sentence in x:
word_list = []
re_punc = re.sub(f"[{re.escape(punctuation)}]", "", sentence).split()
word_lower = [word.lower() for word in re_punc]
for word in word_lower:
if word in self.voca:
word_list.append(word)
self.email_len.append(len(word_list))
def fit(self,x,y):
# y_new = np.zeros(len(y))
# y_new[y=='ham'] = 0
# y_new[y=='spam'] = 1 #define spam as positive
# y = y_new
self.creat_voca(x)
pos_de = y@self.email_len + self.k
neg_de = (1-y)@self.email_len + self.k
x_pos = np.array(x)[y==1]
x_neg = np.array(x)[y==0]
self.fai_pos = (self.count(x_pos)+1)/pos_de
self.fai_neg = (self.count(x_neg)+1)/neg_de
self.fai = sum(y)/len(y)
def predict(self,x):
pred = np.zeros(len(x))
i = 0
for sentence in x:
x_count = self.count(sentence)
pred[i] = np.round(1/(1+np.exp(x_count@(np.log(self.fai_neg)-np.log(self.fai_pos))+np.log((1-self.fai)/self.fai))))
i += 1
# pred_new = np.zeros(len(pred))
# pred_new = np.array(pred_new, dtype=object)
# pred_new[pred==1] = 'spam'
# pred_new[pred==0] = 'ham'
# pred = pred_new
return pred
class Perceptron:
"""
Notes:
* this is a perceptron with kernel trick
* activation: sign(x)
Examples:
per = Perceptron()
kernel = rbf_kernel
for x,y in zip(train_x,train_y):
per.update_state(kernel,x,y)
total = 0
for xi in test_x:
total += per.predict(xi) == test_y
print('precision:',np.mean(total))
per.plot(test_x,test_y)
plt.show()
"""
def __init__(self):
self.kernel = None
self.state = []
def update_state(self,kernel,x_i,y_i,learning_rate=0.5):
self.kernel = kernel
beta_i = learning_rate*(y_i-sign(sum(beta * self.kernel(x,x_i) for beta,x in self.state)))
self.state.append((beta_i,x_i))
def predict(self,x_i):
return sign(sum(beta * self.kernel(x,x_i) for beta,x in self.state))
def plot(self,x,y):
x1,x2 = np.meshgrid(np.linspace(-10,10,20),np.linspace(-10,10,20))
z = np.zeros(x1.shape)
for i in range(x1.shape[0]):
for j in range(x1.shape[1]):
z[i, j] = self.predict([x1[i, j], x2[i, j]])
plt.figure(figsize=(12,8))
plt.contourf(x1,x2,z, levels=[-float('inf'),0,float('inf')],colors=['orange','cyan'])
x_1 = x[y==1]
x_0 = x[y==0]
plt.scatter(x_1[:,-1],x_1[:,-2],marker='x',c='r')
plt.scatter(x_0[:,-1],x_0[:,-2],marker='o',c='g')
class DecisionTree:
"""
Args:
both str and int are OK, if it's str, set if_init=True
max_feature: only consider a maximum number of features in
a node, it's useful in random forest
Todo:
* add a predict function
* AdaBoost
Examples:
df = pd.read_excel('../data/dt_train.xlsx')
data = df.to_numpy()
x_train = data[:,1:-1] #skip id column
y_train = data[:,-1]
dt = utils.DecisionTree(x_train,y_train,if_init=True)
root_index = np.arange(0, dt.m)
dt.tree_recursive(root_index, 'Root', 2)
"""
def __init__(self, x, y, max_feature=None, if_init=True):
self.x = x
self.y = y
self.ls = []
self.m, self.n = self.x.shape
if max_feature is None:
self.max_feature = self.n
else:
self.max_feature = max_feature
if if_init:
self.init_xy()
self.tree = []
def init_xy(self):
self.x = np.array(self.x)
for i in range(self.n):
dict = {}
if type(self.x[:,i][0]) == str:
strs = np.unique(self.x[:,i])
for j in range(len(strs)):
self.x[:,i][self.x[:,i] == strs[j]] = j
dict[j] = strs[j]
self.ls.append(dict)
dict = {}
if type(self.y[0]) == str:
strs = np.unique(self.y)
for i in range(len(strs)):
self.y[self.y == strs[i]] = i
dict[i] = strs[i]
self.ls.append(dict)
def entropy(self, y):
m = len(y)
entropy = 0
if m != 0:
p = sum(y)/m
if p != 0 and p != 1:
entropy = - p*np.log(p) - (1-p) * np.log(1-p)
return entropy
def ratio(self, root_index, root_entropy):
ratio = []
features = np.random.choice(self.n, self.max_feature, replace=False)
for i in features:
cats, counts = np.unique(self.x[root_index,i], return_counts=True)
total_entropy = 0
weights = []
indices = [root_index[np.where(cat == self.x[root_index, i])[0]] for cat in cats]
for indice, count in zip(indices, counts):
cat_y = self.y[indice]
cat_entropy = self.entropy(cat_y)
weight = count / sum(counts)
weights.append(weight)
total_entropy += cat_entropy * weight
weights = np.array(weights)
weights_entropy = - weights @ np.log(weights).T
if weights_entropy == 0:
weights_entropy = -1
ratio.append((root_entropy - total_entropy) / weights_entropy)
return ratio
def best_split(self, root_index):
end = False
root_entropy = self.entropy(self.y[root_index])
ratio = self.ratio(root_index,root_entropy)
if len(set(ratio)) == 1:
end = True
best_feature = None
return best_feature, end
ratio = np.array(ratio)
best_feature = np.argmax(ratio)
return best_feature,end
def split(self, best_feature, root_index):
cats = np.unique(self.x[root_index,best_feature])
indices = [root_index[cat == self.x[root_index,best_feature]] for cat in cats]
return indices, cats
def tree_recursive(self, root_index, branch_name, max_depth, current_depth=0):
formatting = '-' * current_depth
if all(self.y[root_index] == np.zeros(len(self.y[root_index]))):
print('%s Depth %d, %s: negative'%(formatting, current_depth, branch_name))
return
if all(self.y[root_index] == np.ones(len(self.y[root_index]))):
print('%s Depth %d, %s: positive'%(formatting, current_depth, branch_name))
return
if current_depth == max_depth:
formatting = ' ' * current_depth + '-' * current_depth
print(formatting, '%s leaf node with indices' %branch_name,
root_index, ', with label %s' %self.y[root_index],', hit the max depth')
return
best_feature, end = self.best_split(root_index)
self.tree.append((current_depth, branch_name, best_feature, root_index))
if end:
formatting = ' ' * current_depth + '-' * current_depth
print(formatting, '%s leaf node with indices' % branch_name,
root_index, ', with label %s' % self.y[root_index], ', all features have the same ratio, end')
return
print('%s Depth %d, %s: Split on feature: %d'%(formatting, current_depth,
branch_name, best_feature))
indices, cats = self.split(best_feature,root_index)
name = 0
for i in indices:
self.tree_recursive(i, self.ls[best_feature][cats[name]], max_depth, current_depth+1)
name += 1
return
class NeuralNetwork:
"""
Notes:
* only for o and 1 binary classification
* activation func is sigmoid function, loss func is Cross-Entropy
* three hidden layers, number of neurons can be adjusted in xavier_init
Examples:
nn = utils.NeuralNetwork(x_train,y_train,epoch=3000,learning_rate=0.001)
nn.fit()
pred = nn.predict(x_test)
utils.plot(nn,x_test,y_test)
print('precision:', np.mean(pred[0] == y_test))
"""
def __init__(self, x, y, learning_rate=0.1, epoch=50):
self.epoch = epoch
self.alpha = learning_rate
self.m, self.n = x.shape
self.x, self.y = x.T, y.reshape(1,self.m)
self.xavier_init()
def sigmoid(self, x):
return 1/(1+np.exp(-x))
def de_sigmoid(self, x):
return self.sigmoid(x) * (1-self.sigmoid(x))
def delta(self, w, ori_delta, z):
return w.T @ ori_delta * self.de_sigmoid(z)
def xavier_init(self):
n1 = 16 # number of neurons in the first layer
n2 = 16
n3 = 4
self.w1 = np.random.normal(0,(2/(n1+self.n))**(1/4),size=(n1,self.n))
self.w2 = np.random.normal(0,(2/n1+n2)**(1/4),size=(n2,n1))
self.w3 = np.random.normal(0,(2/n3+n2)**(1/4),size=(n3,n2))
self.w4 = np.random.normal(0,(2/n3+1)**(1/4),size=(1,n3))
self.b1 = np.random.normal(0,(2/(n1+self.n))**(1/4),size=(n1,self.m))
self.b2 = np.random.normal(0,(2/n1+n2)**(1/4),size=(n2,self.m))
self.b3 = np.random.normal(0,(2/n3+n2)**(1/4),size=(n3,self.m))
self.b4 = np.random.normal(0,(2/n3+1)**(1/4),size=(1,self.m))
def fwprop(self):
self.z1 = self.w1 @ self.x + self.b1
self.a1 = self.sigmoid(self.z1)
self.z2 = self.w2 @ self.a1 + self.b2
self.a2 = self.sigmoid(self.z2)
self.z3 = self.w3 @ self.a2 + self.b3
self.a3 = self.sigmoid(self.z3)
self.z4 = self.w4 @ self.a3 + self.b4
self.a4 = self.sigmoid(self.z4)
def bwprop(self):
eps = 1e-8 # avoid dividing 0
de_crossentropy = (1-self.y) / (eps + 1-self.a4) - self.y / (eps + self.a4)
self.delta4 = de_crossentropy * self.de_sigmoid(self.z4)
self.delta3 = self.delta(self.w4, self.delta4, self.z3)
self.delta2 = self.delta(self.w3, self.delta3, self.z2)
self.delta1 = self.delta(self.w2, self.delta2, self.z1)
def gd(self):
self.w4 -= self.alpha * self.delta4 @ self.a3.T
self.w3 -= self.alpha * self.delta3 @ self.a2.T
self.w2 -= self.alpha * self.delta2 @ self.a1.T
self.w1 -= self.alpha * self.delta1 @ self.x.T
self.b4 -= self.alpha * self.delta4
self.b3 -= self.alpha * self.delta3
self.b2 -= self.alpha * self.delta2
self.b1 -= self.alpha * self.delta1
def loss(self):
return - (1-self.y) @ (np.log(1-self.a4)).T - self.y @ (np.log(self.a4)).T
def fit(self):
loss = []
for i in range(self.epoch):
self.fwprop()
self.bwprop()
self.gd()
loss.append(self.loss()[0][0])
plot_loss(loss)
def predict(self, x):
x = x.T
z1 = self.w1 @ x + np.mean(self.b1,axis=1,keepdims=True)
a1 = self.sigmoid(z1)
z2 = self.w2 @ a1 + np.mean(self.b2,axis=1,keepdims=True)
a2 = self.sigmoid(z2)
z3 = self.w3 @ a2 + np.mean(self.b3,axis=1,keepdims=True)
a3 = self.sigmoid(z3)
z4 = self.w4 @ a3 + np.mean(self.b4,axis=1,keepdims=True)
a4 = self.sigmoid(z4)
return np.round(a4)
class GMM:
"""
Gaussian Mixture Model
Notes:
# if it's semi supervised, z must be given
Args:
k: number of categories
alpha: weight for the labeled examples
Examples:
a) unsupervised:
gmm = utils.GMM(x_train)
gmm.fit()
pred = gmm.predict()
plt.figure(figsize=(12,8))
plt.scatter(x_train[:,0],x_train[:,1],c=pred)
plt.show()
b) semi-supervised:
gmm = utils.GMM(x_train, y_train, is_semi_supervised=True)
gmm.fit()
pred = gmm.predict()
plt.figure(figsize=(12,8))
plt.scatter(x_train[y_train!=-1,0], x_train[y_train!=-1, 1], c=y_train[y_train!=-1])
plt.scatter(x_train[y_train==-1,0],x_train[y_train==-1,1],c=pred)
plt.show()
"""
def __init__(self, x, z=None, is_semi_supervised=False, k=4, alpha=20):
self.z = z
self.is_semi_supervised = is_semi_supervised
if self.is_semi_supervised:
UNLABELED = -1
labeled_idx = (z != UNLABELED)
self.x = x[~labeled_idx, :]
self.m, self.n = self.x.shape
self.x_tilde = x[labeled_idx, :]
else:
self.m, self.n = x.shape
self.x = x
self.mu = []
self.sigma = []
self.k = k
self.alpha = alpha # Weight for the labeled examples
# Initialize mu, sigma, phi and w
self._init()
def _init(self):
# Initialize mu and sigma by splitting the m data points uniformly at random
# into k groups, then calculating the sample mean and covariance for each group
index = np.arange(0, self.m)
np.random.shuffle(index)
number = self.m // self.k
for i in range(self.k):
start = i * number
end = start + number if i != self.k - 1 else self.m
data = self.x[index[start:end], :]
self.mu.append(np.mean(data, axis=0))
self.sigma.append(np.cov(data, rowvar=False))
# Initialize phi by placing equal probability on each Gaussian
# phi should be a numpy array of shape (k,)
phi = np.ones(self.k)
self.phi = phi / self.k
# Initialize w by placing equal probability on each Gaussian
# w should be a numpy array of shape (m, k)
w = np.ones((self.m, self.k))
self.w = w / self.k
def fit(self):
"""
Args:
self.x: shape (m, n)
self.x_tilde: shape (m_tilde, n)
self.z: shape (m_tilde, )
self.w: shape (m, k)
self.phi: shape (k, )
self.mu: k arrays of shape (n, )
self.sigma: k arrays of shape (n, n)
"""
eps = 1e-3 # Convergence threshold
max_iter = 1000
if self.is_semi_supervised:
UNLABELED = -1
labeled_idx = (self.z != UNLABELED)
z = self.z[labeled_idx]
it = 0
ll = prev_ll = None
m_tilde, n_tilde = self.x_tilde.shape
temp = np.zeros((self.m ,self.k))
temp_super = np.zeros(self.k)
label_sum = np.zeros(self.k)
while it < max_iter and (prev_ll is None or np.abs(ll - prev_ll) >= eps):
for i in range(self.k):
label_sum[i] = np.sum(z == i)
# E-step: Update w
for i in range(self.k):
tempj = np.exp(- 1 / 2 * (self.x - self.mu[i].reshape(1, self.n)) @ np.linalg.inv(self.sigma[i]) @ (
self.x - self.mu[i].reshape(1, self.n)).T).diagonal()
temp[:, i] = tempj
w = temp * self.phi.reshape(1, self.k) * (1 / np.sqrt(np.linalg.det(self.sigma))).reshape(1, -1)
row_sum = np.sum(w, axis=1, keepdims=True)
self.w = w / row_sum
# M-step: Update phi, mu, and sigma
self.phi = (np.sum(self.w, axis=0) + self.alpha * label_sum) / (self.m + self.alpha * m_tilde)
for i in range(self.k):
self.mu[i] = (self.w[:, i].reshape(1, -1) @ self.x + self.alpha * np.sum(self.x_tilde[z == i, :], axis=0)) / (
np.sum(self.w[:, i]) + self.alpha * label_sum[i])
self.sigma[i] = (((self.x.T - self.mu[i].reshape(self.n, 1)) * self.w[:, i].reshape(1, -1)) @ (self.x - self.mu[i].reshape(1, self.n))
+ self.alpha * (self.x_tilde[z == i, :].T - self.mu[i].reshape(self.n, 1)) @ (
self.x_tilde[z == i, :] - self.mu[i].reshape(1, self.n))) / (np.sum(
self.w[:, i]) + self.alpha * label_sum[i])
# Compute the log-likelihood of the data to check for convergence
for i in range(self.k):
tempj = np.exp(- 1 / 2 * (self.x - self.mu[i].reshape(1, self.n)) @ np.linalg.inv(self.sigma[i]) @ (
self.x - self.mu[i].reshape(1, self.n)).T).diagonal()
temp[:, i] = tempj
prev_ll = ll
ll = np.sum(np.log(np.sum(
temp * self.phi.reshape(1, self.k) * (1 / np.sqrt(np.linalg.det(self.sigma))).reshape(1, -1) * (2 * np.pi) ** (
- self.k / 2),
axis=1)))
for i in range(self.k):
tempj = (np.exp(
- 1 / 2 * (self.x_tilde[z == i] - self.mu[i].reshape(1, self.n)) @ np.linalg.inv(self.sigma[i]) @ (self.x_tilde[z == i]
- self.mu[i].reshape(
1, self.n)).T).diagonal() * (1 / np.sqrt(np.linalg.det(self.sigma[i])))
* (2 * np.pi) ** (-self.k / 2)) * label_sum[i] / m_tilde
temp_super[i] = np.sum(np.log(tempj))
l_super = self.alpha * np.sum(temp_super)
ll = ll + l_super
it += 1
else:
it = 0
ll = prev_ll = None
temp = np.zeros((self.m, self.k))
while it < max_iter and (prev_ll is None or np.abs(ll - prev_ll) >= eps):
# E-step: Update w
for i in range(self.k):
tempj = np.exp(- 1 / 2 * (self.x - self.mu[i].reshape(1, self.n)) @ np.linalg.inv(self.sigma[i]) @ (
self.x - self.mu[i].reshape(1, self.n)).T).diagonal()
temp[:, i] = tempj
w = temp * self.phi.reshape(1, self.k) * (1 / np.sqrt(np.linalg.det(self.sigma))).reshape(1, -1)
row_sum = np.sum(w, axis=1, keepdims=True)
self.w = w / row_sum
# M-step: Update phi, mu, and sigma
self.phi = np.sum(self.w, axis=0) / self.m
for i in range(self.k):
self.mu[i] = self.w[:, i].reshape(1, self.m) @ self.x / np.sum(self.w[:, i])
self.sigma[i] = ((self.x.T - self.mu[i].reshape(self.n, 1)) * self.w[:, i].reshape(1, self.m)) @ (
self.x - self.mu[i].reshape(1, -1)) / np.sum(self.w[:, i])
# Compute the log-likelihood of the data to check for convergence
for i in range(self.k):
tempj = np.exp(- 1 / 2 * (self.x - self.mu[i].reshape(1, -1)) @ np.linalg.inv(self.sigma[i]) @ (
self.x - self.mu[i].reshape(1, -1)).T).diagonal()
temp[:, i] = tempj
prev_ll = ll
ll = np.sum(np.log(np.sum(
temp * self.phi.reshape(1, self.k) * (1 / np.sqrt(np.linalg.det(self.sigma))).reshape(1, -1) * (2 * np.pi) ** (
-self.k / 2), axis=1)))
it += 1
return
def predict(self):
return np.argmax(self.w, axis=1)
class KMeans:
"""
Examples(image compression):
kmeans = utils.KMeans(path=your image path, is_image=True)
img = kmeans.fit()
plt.imshow(img)