-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions_l2.py
2694 lines (2388 loc) · 111 KB
/
functions_l2.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
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
# -*- coding: utf-8 -*-
# Written by i3s and the TIRO-lab - UCA, Nice, FRANCE (D.CHARDIN, M.BARLAUD)
# Last update : O5 august 2020
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <https://www.gnu.org/licenses/>.
import os
import sys
import numpy as np
from sklearn.preprocessing import OneHotEncoder
import pandas as pd
import seaborn as sns
import time
from sklearn.model_selection import KFold
from matplotlib import pyplot as plt
__all__=['proj_l1ball',
'proj_l21ball',
'proj_l12ball',
'proj_nuclear',
'sort_weighted_projection',
'sort_weighted_proj',
'centroids',
'class2indicator',
'nb_Genes',
'select_feature_w',
'compute_accuracy',
'predict_L1',
'predict_Fro',
'predict_FISTA',
'normest',
'merge_topGene_norm',
'merge_topGene_norm_acc',
'compare_2topGenes',
'heatmap_classification',
'heatmap_normW',
'drop_cells',
'FISTA_Primal',
'primal_dual_L1N',
'primal_dual_L1acc',
'primal_dual_L1OR',
'primal_dual_L1W',
'primal_dual_L2',
'primal_dual_Nuclear',
'primal_dual_L21',
'basic_run_eta',
'basic_run_tabeta',
'run_FISTA_eta',
'run_primal_dual_L1N_eta',
'run_primal_dual_L1acc_eta',
'run_primal_dual_L1OR_eta',
'run_primal_dual_L1W_eta',
'run_primal_dual_L2_eta',
'run_primal_dual_Nuclear_eta',
'run_primal_dual_L21_eta',
'run_FISTA_tabeta',
'run_primal_dual_L1N_tabeta',
'run_primal_dual_L1acc_tabeta',
'run_primal_dual_L1OR_tabeta',
'run_primal_dual_L1W_tabeta',
'run_primal_dual_L2_tabeta',
'run_primal_dual_L21_tabeta',
'run_primal_dual_Nuclear_tabEtastar'
]
help_info = '''
This file contains functions as follow:
| Functions | Input | Output | Type |
| :--------------------------------- | :--------------------------------------------------------------------------: | :-----------------------: | -------: |
| proj_l1ball | y, eta | Vproj | Function |
| sort_weighted_projection | y, eta, w, n | Vproj | Function |
| sort_weighted_proj | y, eta, w, n | Vproj | Function |
| centroids | XW, Y, k | mu | Function |
| class2indicator | y, k | Y | Function |
| nb_Genes | w | nbG,indGene_w | Function |
| select_feature_w | w, featurenames | features,normW | Function |
| compute_accuracy | idxR, idx, k | Acc_glob,tab_acc | Function |
| predict_L1 | Xtest, W, mu | Y_predict | Function |
| predict_Fro | Xtest, W, mu | Y_predict | Function |
| predict_FISTA | Xtest, W, mu | Y_predict | Function |
| normest | X, tol, maxiter | norm_e | Function |
| merge_topGene_norm | topGenes, normW, clusternames | df_topGenes_normW | Function |
| merge_topGene_norm_acc | topGenes, normW, clusternames, acctest, saveres, file_tag, outputPath | df_topGenes_normW | Function |
| compare_2topGenes | topGenes1,topGenes2, normW1,normW2, lst_col, nbr_limit, printOut | out | Function |
| heatmap_classification | Ytest, YR, clusternames, rotate, draw_fig, save_fig, func_tag, outputPath | Heatmap_matrix | Function |
| heatmap_normW | normW, clusternames, nbr_L, rotate, draw_fig, save_fig, func_tag, outputPath | Heatmap_matrix | Function |
| drop_cells | X,Y,n_fold | X_new, Y_new | Function |
| FISTA_Primal | X,YR,k,param | w,mu,nbGenes_fin,loss | Function |
| primal_dual_L1N | X,YR,k,param | w,mu,nbGenes_fin,loss,Z | Function |
| primal_dual_L1acc | X,YR,k,param | w,mu,nbGenes_fin,loss,Z | Function |
| primal_dual_L1OR | X,YR,k,param | w,mu,nbGenes_fin,loss,Z | Function |
| primal_dual_L1W | X,YR,k,param | w,mu,nbGenes_fin,loss,Z | Function |
| primal_dual_Nuclear | X,YR,k,param | w,mu,nbGenes_fin,loss,Z | Function |
| primal_dual_L2 | X,YR,k,param | w,mu,nbGenes_fin,loss,Z | Function |
| primal_dual_L21 | X,YR,k,param | w,mu,nbGenes_fin,loss,Z | Function |
| basic_run_eta | (See funcion help info) | (See funcion help info) | Script |
| basic_run_tabeta | (See funcion help info) | (See funcion help info) | Script |
| run_FISTA_eta | (Same with basic_run_eta) | (Same with basic_run_eta) | Script |
| run_primal_dual_L1N_eta | (Same with basic_run_eta) | (Same with basic_run_eta) | Script |
| run_primal_dual_L1acc_eta | (Same with basic_run_eta) | (Same with basic_run_eta) | Script |
| run_primal_dual_L1OR_eta | (Same with basic_run_eta) | (Same with basic_run_eta) | Script |
| run_primal_dual_L1W_eta | (Same with basic_run_eta) | (Same with basic_run_eta) | Script |
| run_primal_dual_L2_eta | (Same with basic_run_eta) | (Same with basic_run_eta) | Script |
| run_primal_dual_Nuclear_eta | (Same with basic_run_eta) | (Same with basic_run_eta) | Script |
| run_primal_dual_L21_eta | (Same with basic_run_eta) | (Same with basic_run_eta) | Script |
| run_FISTA_tabeta | (Same with run_tabeta) | (Same with run_tabeta) | Script |
| run_primal_dual_L1N_tabeta | (Same with run_tabeta) | (Same with run_tabeta) | Script |
| run_primal_dual_L1acc_tabeta | (Same with run_tabeta) | (Same with run_tabeta) | Script |
| run_primal_dual_L1OR_tabeta | (Same with run_tabeta) | (Same with run_tabeta) | Script |
| run_primal_dual_L1W_tabeta | (Same with run_tabeta) | (Same with run_tabeta) | Script |
| run_primal_dual_L2_tabeta | (Same with run_tabeta) | (Same with run_tabeta) | Script |
| run_primal_dual_L21_tabeta | (Same with run_tabeta) | (Same with run_tabeta) | Script |
| run_primal_dual_nuclear_tabEtastar | (Same with run_tabeta) | (Same with run_tabeta) | Script |
'''
def proj_l1ball(V,eta,threshold=0.001):
'''
Note that the y should be better 1D or after some element-wise operation, the results will turn to be un predictable.
This function will automatically reshape the y as (m,), where m is the y.size, or the y.shape[0]*y.shape[1].
'''
if type(V) is not np.ndarray:
V = np.array(V)
if V.ndim >1:
V = np.reshape(V,(-1,))
w= np.maximum( np.absolute(V)-np.amax([np.amax( (np.cumsum(np.sort(np.absolute(V),axis = 0)[::-1],axis = 0) - eta)\
/(np.arange(V.shape[0])+1) ),0]), 0)*np.sign(V)
w[np.where(np.abs(w)<threshold)] = 0
return w
def proj_l21ball(V,eta,axis=1,threshold=0.001):
'''
w{np.array} the array to project
eta {int} the radius of l1 ball
axis{int, 2-tuple of ints, None}, optional
Axis or axes along which a norm is calculated
-If axis is an integer, it specifies the axis of x along which to compute
the vector norms.
-If axis is a 2-tuple, it specifies the axes that hold 2-D matrices, and
the matrix norms of these matrices are computed.
-If axis is None then either a vector norm (when x is 1-D) or a matrix norm
(when x is 2-D) is returned.
'''
w = V.copy()
Y = np.linalg.norm(V,2,axis=axis)
T = proj_l1ball(Y,eta).reshape(Y.shape)
max_TY = np.maximum(T,Y)
if axis==0:
w = np.multiply(w,np.divide(T,max_TY,out=np.zeros_like(T), where=max_TY!=0))
else:
order = tuple(np.arange(len(w.shape)))
new_order = (order[axis],)+order[:axis]+order[axis+1:]
reverse_order = (order[axis],)+(0,)+order[axis+1:]
w = np.multiply(np.transpose(w,new_order),np.divide(T,max_TY,out=np.zeros_like(T), where=max_TY!=0))
w = np.transpose(w,reverse_order)
w[np.where(np.abs(w)<threshold)] = 0
return w
def proj_l12ball(V,eta,axis=1,threshold=0.001):
'''
TO DO:
- tensor support
- optimization
'''
tol=0.001
lst_f = []
test=eta*eta
if axis==0:
V = V.T
Vshape = V.shape
lmbda = 0
p = np.ones(Vshape[0],dtype=int)*(Vshape[1]-1) # to change in case of tensor
delta = np.zeros(Vshape[0])
V_abs = np.abs(V) #maybe transposed if change the value of axis
V0 = np.sort(V_abs,axis=1)[:,::-1]
sgn = np.sign(V)
V_sum = np.cumsum(V0,axis=1)
# K = 10
# for k in range(K):
while test>tol :
# update lambda
sum0 = np.array(list(map(lambda x,y:y[x],p,V_sum)))
sum1 = np.sum(np.power(sum0/(1+lmbda*p),2))
sum2 = np.sum(p*(np.power(sum0,2)/np.power(1+lmbda*p,3)))
test = sum1-eta*eta
lmbda = lmbda + test/(2*sum2)
lst_f.append(test)
# update p
p = np.argmax(V_sum/(1+lmbda*np.arange(1,Vshape[1]+1)),axis=1)
delta = lmbda*(np.array(list(map(lambda x,y:y[x],p,V_sum)))/(1+lmbda*p))
W = V_abs-delta.reshape((-1,1))
W[W<0]=0
W = W*sgn
W[np.where(np.abs(W)<threshold)] = 0
return W
def proj_nuclear(V,eta_star,threshold=0.001):
L,S0,R = np.linalg.svd(V,full_matrices=False)
# norm_nuclear = S0.sum()
vs1 = proj_l1ball(S0.reshape((-1,)),eta_star)
S1 = vs1.reshape(S0.shape)
w = np.matmul(L, S1[..., None] * R)
w[np.where(np.abs(w)<threshold)] = 0
return w
def sort_weighted_projection(y, eta, w, n=None):
'''
Weighted projection on l1 ball.
When w = ones(y.shape) this function is equivalent to proj_l1ball(y,eta)
It's not a simple
Compared to the original version, we have modified :
* Changed a by eta
* Regard x as the output and give it a initial value of zeros
* Fixed n as the length of x if it's not given
'''
# ==== changed part
if type(y) is not np.ndarray:
y = np.array(y)
if y.ndim >1:
y = np.reshape(y,(-1,))
if w.ndim >1:
w = np.reshape(w,(-1,))
if np.any(w<0):
raise ValueError('sort_weighted_projection: The weight should be positive')
sign_y = np.sign(y)
y0 = y*sign_y
x = np.zeros(y.shape)
if n is None:
n = len(x)
z = np.divide(y0,w)
p = np.argsort(z)[::-1]
WYs = 0.0
Ws = 0.0
for j in p:
WYs += w[j]*y0[j]
Ws += w[j]*w[j]
if ((WYs - eta) / Ws) > z[j]:
break
WYs -= w[j]*y0[j]
Ws -= w[j]*w[j]
L = (WYs - eta) / Ws
if n == len(x):
x = np.maximum(0,y0-w*L)
else:
for i in range(n):
x[i] = max(0,y0[i]-w[i]*L)
x *= sign_y
return x
def sort_weighted_proj(y, eta, w, n=None):
'''
Weighted projection on l1 ball. V2
When w = ones(y.shape) this function is equivalent to proj_l1ball(y,eta)
It's not a simple
Instead of using for loop, we use np.cumsum
'''
# ==== changed part
if type(y) is not np.ndarray:
y = np.array(y)
if y.ndim >1:
y = np.reshape(y,(-1,))
if np.any(w<0):
raise ValueError('sort_weighted_projection: The weight should be positive')
sign_y = np.sign(y)
y0 = y*sign_y
x = np.zeros(y.shape)
if n is None:
n = len(x)
z = np.divide(y0,w)
p = np.argsort(z)[::-1]
yp=y0[p]
wp=w[p]
Wys = np.cumsum(yp*wp)
Ws = np.cumsum(wp*wp)
L = (Wys -eta) /Ws
ind = np.where(L>z[p])[0]
if ind.size==0:# all elements of (Wys -eta) /Ws are <z[p], so L is the last one
L = L[-1]
else:
L = L[ind[0]]
if n == len(x):
x = np.maximum(0,y0-w*L)
else:
x[0:n] = np.maximum(0,y0[0:n]-w[0:n]*L)
x *= sign_y
return x
def centroids(XW,Y,k):
Y = np.reshape(Y,-1)
d = XW.shape[1]
mu = np.zeros((k,d))
'''
since in python the index starts from 0 not from 1,
here the Y==i will be change to Y==(i+1)
Or the values in Y need to be changed
'''
for i in range(k):
C = XW[Y==(i+1),:]
mu[i,:] = np.mean(C,axis=0)
return mu
def class2indicator(y,k):
if len(y.shape)>1:
# Either throw exception or transform y, here the latter is chosen.
# Note that a list object has no attribute 'flatten()' as np.array do,
# We use x = np.reshape(y,-1) instead of x = y.flatten() in case of
# the type of 'list' of argument y
y = np.reshape(y,-1)
n = len(y)
Y = np.zeros((n,k)) # dtype=float by default
'''
since in python the index starts from 0 not from 1,
here the y==i in matlab will be change to y==(i+1)
'''
for i in range(k):
Y[:,i] = (y==(i+1))
return Y
def nb_Genes2(w):
# Return the number of selected genes from the matrix (numpy.ndarray) w
ind_genes = np.linalg.norm(w,axis=1)
indGene_w = np.where(ind_genes>0)[0]
nbG = indGene_w.nonzero()[0].size
return nbG,indGene_w
def nb_Genes(w):
# Return the number of selected genes from the matrix (numpy.ndarray) w
ind_genes = np.linalg.norm(w,axis=1)
indGene_w = np.where(ind_genes>0)[0]
nbG = len(w.reshape(-1).nonzero()[0])
return nbG,indGene_w
def select_feature_w(w,featurenames):
k = w.shape[1]
d = w.shape[0]
lst_features = []
lst_norm=[]
for i in range(k):
s_tmp = w[:,i] # the i-th column
f_tmp = np.abs(s_tmp) # the absolute values of this column
ind = np.argsort(f_tmp)[::-1] # the indices of the sorted abs column (descending order)
f_tmp = np.sort(f_tmp)[::-1] # the sorted abs column (descending order)
nonzero_inds = np.nonzero(f_tmp)[0] # the nonzero indices
lst_f = []
lst_n=[]
if len(nonzero_inds)>0:
nozero_ind = nonzero_inds[-1] #choose the last nonzero index
if nozero_ind ==0:
lst_f.append(featurenames[ind[0]])
lst_n.append(s_tmp[ind[0]])
else:
for j in range(nozero_ind+1):
lst_f.append(featurenames[ind[j]])
lst_n = s_tmp[ind[0:(nozero_ind+1)]]
lst_features.append(lst_f)
lst_norm.append(lst_n)
n_cols_f = len(lst_features)
n_rows_f = max(map(len,lst_features)) #maxmum subset length
n_cols_n = len(lst_norm)
n_rows_n = max(map(len,lst_norm))
for i in range(n_cols_f):
ft = np.array(lst_features[i])
ft.resize(n_rows_f,refcheck=False)
nt = np.array(lst_norm[i])
nt.resize(n_rows_n,refcheck=False)
if i ==0:
features = ft;normW=nt;continue
features = np.vstack((features,ft))
normW = np.vstack((normW,nt))
features = features.T
normW = normW.T
return features,normW
def compute_accuracy(idxR,idx,k):
"""
# ===============================
#----- INPUT
# idxR : real labels
# idx : estimated labels
# k : number of class
#----- OUTPUT
# ACC_glob : global accuracy
# tab_acc : accuracy per class
# ===============================
"""
# Note that Python native sum function works better on list than on numpy.array
# while numpy.sum function works better on numpy.array than on list.
# So it will choose numpy.array as the default type for idxR and idx
if type(idxR) is not np.array:
idxR = np.array(idxR)
if type(idx) is not np.array:
idx = np.array(idx)
if idxR.ndim==2 and 1 not in idxR.shape:
idxR = np.reshape(idxR,(-1,1))
if idx.ndim==1:
idx = np.reshape(idx,idxR.shape)
# Global accuracy
y = np.sum(idxR==idx)
ACC_glob = y/len(idxR)
# Accuracy per class
tab_acc = np.zeros((1,k))
'''
since in python the index starts from 0 not from 1,
here the idx(ind)==j in matlab will be change to idx[ind]==(j+1)
'''
for j in range(k):
ind = np.where(idxR==(j+1))[0]
if len(ind)==0:
tab_acc[0,j] = 0.0
else:
tab_acc[0,j] = int(np.sum(idx[ind]==(j+1)))/len(ind)
return ACC_glob,tab_acc
def predict_L1(Xtest,W,mu):
# Chambolle_Predict
k = mu.shape[0]
m = Xtest.shape[0]
Ytest = np.zeros((m,1))
for i in range(m):
distmu = np.zeros((1,k))
XWi = np.matmul(Xtest[i,:],W)
for j in range(k):
distmu[0,j] = np.linalg.norm(XWi - mu[j,:],1)
Ytest[i] = np.argmin(distmu)+1 #Since in Python the index starts from 0
return Ytest
def predict_Fro(Xtest,W,mu):
# Chambolle_Predict
k = mu.shape[0]
m = Xtest.shape[0]
Ytest = np.zeros((m,1))
for i in range(m):
distmu = np.zeros((1,k))
XWi = np.matmul(Xtest[i,:],W)
for j in range(k):
distmu[0,j] = np.linalg.norm(XWi - mu[j,:])
Ytest[i] = np.argmin(distmu)+1 #Since in Python the index starts from 0
return Ytest
def predict_FISTA(Xtest,W,mu):
# Chambolle_Predict
k = mu.shape[0]
m = Xtest.shape[0]
Ytest = np.zeros((m,1))
for i in range(m):
distmu = np.zeros((1,k))
XWi = np.matmul(Xtest[i,:],W)
for j in range(k):
distmu[0,j] = np.linalg.norm(XWi - mu[j,:],2)
Ytest[i] = np.argmin(distmu)+1 #Since in Python the index starts from 0
return Ytest
def normest(X,
tol=1.0e-6,
maxiter=100):
# import necessary modules
import scipy.sparse
import numpy as np
import warnings
if scipy.sparse.issparse(X):
x = np.array(np.sum(np.abs(X),axis=0))
x = np.reshape(x,max(x.shape))
elif type(X)==np.matrix:
x = np.sum(np.abs(np.asarray(X)),axis=0)
x = np.reshape(x,max(x.shape))
else:
x = np.sum(np.abs(X),axis=0)
norm_e = np.linalg.norm(x)
if norm_e == 0:
return norm_e
x = x/norm_e
norm_e0 = 0
count = 0
while np.abs(norm_e - norm_e0) > tol*norm_e:
norm_e0 = norm_e
Xx = np.matmul(X,x)
if np.count_nonzero(Xx)==0:
Xx = np.random.rand(Xx.shape[0])
x = np.matmul(X.T,Xx)
normx = np.linalg.norm(x)
norm_e = normx/np.linalg.norm(Xx)
x = x/normx
count+=1
if count > maxiter:
warnings.warn('Normest::NotConverge:the number of iterations exceeds {} times.\nThe error is {}, the tolerance is {}'\
.format(maxiter,np.abs(norm_e - norm_e0),tol),RuntimeWarning)
break
return norm_e
def merge_topGene_norm(topGenes,normW,clusternames):
"""
# =====================================================================
# It merge the two output from function select_features_w into a new
# pandas.DataFrame whose columns will be the elements in clusternames
# and each of the column will have two subcolumns: topGenes and weight
#
#----- INPUT
# topGenes : ndarray of top Genes chosen by select_features_w
# normW : normWeight of each genes given by select_features_w
# clusternames : A list of the names of each class.
#----- OUTPUT
# df_res : A DataFrame with each colum the first subcolumn the genes
# and second subcolumn their norm of weight
# =====================================================================
"""
if topGenes.shape!=normW.shape:
raise ValueError('The dimension of the two input should be the same')
m,n = topGenes.shape
nbC = len(clusternames)
res = np.dstack((topGenes,normW))
res = res.reshape(m,2*n)
lst_col = []
for i in range(nbC):
lst_col.append((clusternames[i],'topGenes'))
lst_col.append((clusternames[i],'Weights'))
df_res = pd.DataFrame(res,columns=lst_col)
df_res.columns = pd.MultiIndex.from_tuples(df_res.columns,names=['CluserNames','Attributes'])
return df_res
def merge_topGene_norm_acc(topGenes,normW,clusternames,acctest,nbr_features=30,
saveres=False,file_tag=None,outputPath='../results/'):
"""
# =============================================================================================== \n
# Based on the function merge_topGebe_norm, replace the column name for \n
# normW by the accuracy \n
#----- INPUT \n
# topGenes (ndarray or DataFrame) : Top Genes chosen by select_features_w \n
# normW (ndarray or DataFrame) : The normWeight of each genes given by select_features_w \n
# clusternames (list or array) : A list of the names of each class \n
# acctest (list or array) : The list of the test accuracy \n
# saveres (optional, boolean) : True if we want to save the result to local \n
# file_tag (optional, string) : A file tag which will be the prefix of the file name \n
# outputPath (optional, string) : The output Path of the file \n
# ----- OUTPUT \n
# df_res : A DataFrame with each colum the first subcolumn the genes \n
# and second subcolumn their norm of weight \n
# =============================================================================================== \n
"""
if type(topGenes) is pd.DataFrame:
topGenes = topGenes.values
if type(normW) is pd.DataFrame:
normW = normW.values
if topGenes.shape!=normW.shape:
raise ValueError('The dimension of the two input should be the same')
m,n = topGenes.shape
nbC = len(clusternames)
res = np.dstack((topGenes,normW))
res = res.reshape(m,2*n)
lst_col = []
acctest_mean=acctest.values.tolist()[4]
for i in range(nbC):
lst_col.append((clusternames[i],'topGenes'))
astr=str(acctest_mean[i])
lst_col.append((astr,'Weights'))
df_res = pd.DataFrame(res[0:nbr_features,:],columns=lst_col)
df_res.columns = pd.MultiIndex.from_tuples(df_res.columns,names=['CluserNames','Attributes'])
if saveres:
df_res.to_csv('{}{}_Heatmap of Acc_normW_Topgenes.csv'.format(outputPath,file_tag),sep=';')
return df_res
def compare_2topGenes(topGenes1,topGenes2,normW1=None,normW2=None,lst_col=None,nbr_limit=30,printOut=False):
"""
#=======================================================================================
# Compare column by column the elements between to topGenes, it choose for
# each column first "nbr" elements to check.
# The two topGenes should be in same size of columns
# ----- INPUT
# topGenes1, topGenes2 (DataFrame) : Two topGenes to be compared
# normW1, normW2 (DataFrame,optional): Two matrix of weights correspondent. Default: None
# lst_col (list, optional) : If given, only the chosen column will be compared. Default: None
# nbr_limit (scalar, optional) : Number of the lines to be compared. Default: 30
# printOut (boolean, optional) : If True, the comparison result will be shown on screen. Default: False
# ----- OUTPUT
# out (string) : It returns a string of the comparing result as output.
#=======================================================================================
"""
import pandas as pd
import numpy as np
if type(topGenes1) != type(topGenes2):
raise ValueError('The two topGenes to be compared should be of the same type.')
if type(topGenes1) is not pd.DataFrame:
col = ['C'+str(i) for i in topGenes1.shape[1]]
topGenes1=pd.DataFrame(topGenes1,columns=col)
topGenes2=pd.DataFrame(topGenes2,columns=col)
out = []
out.append('Comparing the two TopGenes:\n')
# After the benchmark, the appended list and then converted to whole string seems to be the least consuming
list_name = list(topGenes1.columns)
if lst_col is not None:
list_name = [list_name[ind] for ind in lst_col]
for name in list_name:
out.append('{0:{fill}{align}40}\n'.format(' Class %s '%name,fill='=',align='^'))
col_1 = np.array(topGenes1[[name]],dtype=str)
col_2 = np.array(topGenes2[[name]],dtype=str)
# Here np.nozero will return a tuple of 2 array corresponding the first
# and the second dimension while the value of second dimension will
# always be 0. So the first dimension's last location+1 will be the length
# of nonzero arrays and that it's just the location of the first zero
# element
length_nonzero_1 = np.nonzero(col_1)[0][-1] + 1
length_nonzero_2 = np.nonzero(col_2)[0][-1] + 1
# np.nonzero will not detect '0.0' as zero type
if all(col_1=='0.0'):
length_nonzero_1 = 0
if all(col_2=='0.0'):
length_nonzero_2 = 0
length_min = min(length_nonzero_1,length_nonzero_2)
# Check if at least one of the classes contains only zero and avoid the error
if length_min ==0 and length_nonzero_1==length_nonzero_2:
out.append('* Warning: No feature is selected for both two class\n Skipped for this class')
continue
elif length_min==0 and length_nonzero_1>0:
out.append('* Warning: No feature is selected for this class in TopGenes2\n')
out.append('* All {} elements are included only in topGenes1:\n'.format(min(length_nonzero_1,nbr_limit)))
for k in range(min(length_nonzero_1,nbr_limit)):
if normW1 is None:
out.append(' (%s)\n'%(str(col_1[k,0])))
else:
out.append(' (%s, %s)\n'%(str(col_1[k,0]),normW1[[name]].iloc[k,0]))
continue
elif length_min==0 and length_nonzero_2>0:
out.append('* Warning: No feature is selected for this class in TopGenes1\n')
out.append('* All {} elements are included only in topGenes2:\n'.format(min(length_nonzero_2,nbr_limit)))
for k in range(min(length_nonzero_2,nbr_limit)):
if normW2 is None:
out.append(' (%s)\n'%(str(col_2[k,0])))
else:
out.append(' (%s, %s)\n'%(str(col_2[k,0]),normW2[[name]].iloc[k,0]))
continue
if length_min < nbr_limit:
length = length_min
out.append('* Warning: In this column, the 1st topGenes has {} nozero elements\n* while the 2nd one has {} nonzero elements\n'\
.format(length_nonzero_1,length_nonzero_2))
out.append('* So only first %d elements are compared\n\n'%length_min)
else:
length = nbr_limit
set_1 = col_1[0:length]
set_2 = col_2[0:length]
set_common = np.intersect1d(set_1,set_2)# Have in common
set_o1=np.setdiff1d(set_1,set_2)#Exclusively in topGenes1
set_o2=np.setdiff1d(set_2,set_1)#Exclusively in topGenes2
lc=len(set_common)
# print exclusively in topGenes1
out.append('Included exclusively in first topGenes: {} elements in total.\n'\
.format(length-lc))
if length-lc >0:
if normW1 is None:
out.append('Details:(Name)\n')
else:
out.append('Details:(Name,Weight)\n')
idx_i,idx_j=np.where(topGenes1[[name]].isin(set_o1))
for i,j in zip(idx_i,idx_j):
if normW1 is None:
out.append(' (%s)\n'%str(set_1[i,j]))
else:
out.append(' (%s, %s)\n'%(str(set_1[i,j]),str(normW1[[name]].iloc[i,j])))
out.append('\nNumber of elements in common:{}\n'.format(lc))
# print exclusively in topGenes1
out.append('\nIncluded exclusively in second topGenes: {} elements in total.\n'\
.format(length-lc))
if length-lc >0:
if normW2 is None:
out.append('Details:(Name)\n')
else:
out.append('Details:(Name,Weight)\n')
idx_i,idx_j=np.where(topGenes2[[name]].isin(set_o2))
for i,j in zip(idx_i,idx_j):
if normW2 is None:
out.append(' (%s)\n'%str(set_2[i,j]))
else:
out.append(' (%s, %s)\n'%(str(set_2[i,j]),str(normW2[[name]].iloc[i,j])))
out.append('{:-<40}\n'.format(''))
out=''.join(out)
if printOut==True:
print(out)
return out
def heatmap_classification(Ytest,YR,clusternames,
rotate=45,
draw_fig=False,
save_fig=False,
func_tag=None,
outputPath='../results/'):
'''
#=====================================================
# It takes the predicted labels (Ytest), true labels (YR)
# and a list of the names of clusters (clusternames)
# as input and provide the heatmap matrix as the output
#=====================================================
'''
k = len(np.unique(YR)) # If we need to automatically find a k
Heatmap_matrix = np.zeros((k,k))
for i in (np.arange(k)+1):
for j in (np.arange(k)+1):
a = np.where(Ytest[YR==i]==j,1,0).sum()# number Ytest ==j where YR==i
b = np.where(YR==i,1,0).sum()
Heatmap_matrix[i-1,j-1] = a/b
# Plotting
if draw_fig == True:
plt.figure()
annot=False
if k >10:
annot=False
if clusternames is not None:
axes=sns.heatmap(Heatmap_matrix,
cmap='jet',annot=annot, fmt='.2f',
xticklabels=clusternames, yticklabels=clusternames)
else:
axes=sns.heatmap(Heatmap_matrix,
cmap='jet',annot=annot, fmt='.2f')
axes.set_xlabel('Predicted true positive',fontsize=14)
axes.set_ylabel('Ground true',fontsize=14)
axes.tick_params(labelsize=7)
plt.xticks(rotation=rotate)
axes.set_title('Heatmap of confusion Matrix',fontsize=14)
plt.tight_layout()
if save_fig == True:
plt.savefig('{}{}_Heatmap_of_confusion_Matrix.png'.format(outputPath,func_tag))
return Heatmap_matrix
def heatmap_normW(normW,clusternames=None,nbr_l=10,
rotate=45,
draw_fig=False,
save_fig=False,
func_tag=None,
outputPath='../results/'):
'''
#=====================================================
# It takes the predicted labels (Ytest), true labels (YR)
# and the number of clusters (k) as input and provide the
# heatmap matrix as the output
#=====================================================
'''
A = np.abs(normW)
AN = A/A[0,:]
if normW.shape[0]<nbr_l:
nbr_l = normW.shape[0]
ANR = AN[0:nbr_l,:]
annot=False
if draw_fig == True:
plt.figure(figsize=(10,6))
# axes2=sns.heatmap(ANR,cmap='jet',annot=annot,fmt='.3f')
if clusternames is None:
axes2=sns.heatmap(ANR,cmap='jet',annot=annot,fmt='.3f',
yticklabels=np.linspace(1,nbr_l,num=nbr_l,endpoint=True,dtype=int))
else:
axes2=sns.heatmap(ANR,cmap='jet',annot=annot,fmt='.3f',
xticklabels=clusternames,
yticklabels=np.linspace(1,nbr_l,num=nbr_l,endpoint=True,dtype=int))
plt.xticks(rotation=rotate)
axes2.set_ylabel('Features',fontsize=14)
axes2.set_xlabel('Clusters',fontsize=14)
axes2.tick_params(labelsize=7)
axes2.set_title('Heatmap of Matrix W',fontsize=14)
plt.tight_layout()
if save_fig == True:
plt.savefig('{}{}_Heatmap_of_signature.png'.format(outputPath,func_tag))
return ANR
def drop_cells(X,Y,n_fold):
"""
# ====================================================================
# This function will detect whether the size of the first dimension of
# X is divisible by n_fold. If not, it will remove the n_diff rows from
# the biggest class(with the largest size in Y) where n_diff=len(Y)%n_fold
#
# ---- Input
# X : The data
# Y : The label
# n_fold : The number of fold
# --- Output
# X_new, Y_new : The new data and the new label
# =====================================================================
"""
m,d = X.shape
if m%n_fold ==0:
return X,Y
n_diff = m%n_fold
# choose in the biggest class to delete
# Find the biggest class
lst_count = []
for i in np.unique(Y):
lst_count.append(np.where(Y==i,1,0).sum())
ind_max = np.unique(Y)[np.argmax(lst_count)]
lst_inds = np.where(Y==ind_max)[0]
# Delete n_diff elements in the biggest class
lst_del = np.random.choice(lst_inds,n_diff)
X_new = np.delete(X,lst_del,0)
Y_new = np.delete(Y,lst_del,0)
return X_new,Y_new
# ===================== Algorithms =======================================
def FISTA_Primal(X,YR,k,param):
"""
# ====================================================================
# ---- Input
# X : The data
# YR : The label. Note that this should be an 2D array.
# k : The number of class
# niter : The number of iterations
# gamma : The hyper parameter gamma
# eta : The eta to calculate the projection on l1 ball
# * isEpsilon is not used in the original file in Matlab
# --- Output
# w : The projection matrix
# mu : The centers
# nbGenes_fin : The number of genes of the final step
# loss : The loss for each iteration
# ====================================================================
"""
# === Check the validness of param and the initialization of the params ===
if type(param) is not dict:
raise TypeError('Wrong type of input argument param',type(param))
lst_params = ['niter', 'eta', 'gamma'] # necessary params
if any(x not in param.keys() for x in lst_params):
raise ValueError('Missing parameter in param.\n Need {}.\n Got {} '.format(lst_params,list(param.keys())))
niter = param['niter']
eta = param['eta']
gamma = param['gamma']
tol = 1.0e-3
a = 4 #chambolle method
n,d = X.shape
# === With class2indicator():
#Y = class2indicator(YR,k)
# === With Onehotencoder:
Y = OneHotEncoder(categories='auto').fit_transform(YR).toarray()
loss = np.zeros(niter)
XtX = np.matmul(X.T,X)
XtY = np.matmul(X.T,Y)
w = np.ones((d,k))
V = np.ones((d,k))
t_old = 1
for i in range(niter):
grad_w = np.matmul(XtX,w)-XtY
# gradient step
w_g = w - gamma*grad_w
#Projection on the l1 ball
V_new = proj_l1ball(np.reshape(w_g,d*k),eta,threshold=tol)
#V_new[np.where(np.abs(V_new)<tol)] = 0
# Reshape back
V_new = np.reshape(V_new,(d,k))
# Chambolle method
t_new = (i+a+1)/a
alpha = (t_old - 1)/t_new
w = V_new + alpha* (V_new - V)
V = V_new
t_old = t_new
loss[i] = np.linalg.norm(Y-np.matmul(X,w),'fro')**2
#end iteratons
#mu = centroids(np.matmul(X,w),YR,k)
mu = np.identity(k)
nbGenes_fin = nb_Genes(w)[0]
loss = loss/loss[0]
return w,mu,nbGenes_fin,loss
def FISTA_Primal_L21(X,YR,k,param):
"""
# ====================================================================
# ---- Input
# X : The data
# YR : The label. Note that this should be an 2D array.
# k : The number of class
# param : A type dict paramter which must have keys:
# 'niter', 'gamma', 'eta'
# --- Output
# w : The projection matrix of size (d,k)
# mu : The centers of classes
# nbGenes_fin : The number of genes of the final result
# loss : The loss for each iteration
# Z : The dual matrix of size (m,k)
# =====================================================================
"""
# === Check the validness of param and the initialization of the params ===
if type(param) is not dict:
raise TypeError('Wrong type of input argument param',type(param))
lst_params = ['niter', 'eta', 'gamma'] # necessary params
if any(x not in param.keys() for x in lst_params):
raise ValueError('Missing parameter in param.\n Need {}.\n Got {} '.format(lst_params,list(param.keys())))
niter = param['niter']
eta = param['eta']
gamma = param['gamma']
tol = 1.0e-3
a = 4 # prameter chambolle method
n,d = X.shape
Y = OneHotEncoder(categories='auto').fit_transform(YR).toarray()
loss = np.zeros(niter)
XtX = np.matmul(X.T,X)
XtY = np.matmul(X.T,Y)
w = np.ones((d,k))
V = np.ones((d,k))
t_old = 1
for i in range(niter):
grad_w = np.matmul(XtX,w)-XtY
# gradient step
w_g = w - gamma*grad_w
#Projection on the l1 ball
V_new = proj_l21ball(w_g,eta,axis=1,threshold=tol)
#V_new[np.where(np.abs(V_new)<tol)] = 0
# Chambolle method
t_new = (i+a+1)/a
alpha = (t_old - 1)/t_new
w = V_new + alpha* (V_new - V)
V = V_new
t_old = t_new
loss[i] = np.linalg.norm(Y-np.matmul(X,w),'fro')**2
#end iteratons
mu = centroids(np.matmul(X,w),YR,k)
nbGenes_fin = nb_Genes(w)[0]
loss = loss/loss[0]
return w,mu,nbGenes_fin,loss
def FISTA_Primal_L12(X,YR,k,param):
"""
# ====================================================================
# ---- Input
# X : The data
# YR : The label. Note that this should be an 2D array.
# k : The number of class
# param : A type dict paramter which must have keys:
# 'niter', 'gamma', 'eta'
# --- Output
# w : The projection matrix of size (d,k)
# mu : The centers of classes
# nbGenes_fin : The number of genes of the final result
# loss : The loss for each iteration
# Z : The dual matrix of size (m,k)
# =====================================================================
"""
# === Check the validness of param and the initialization of the params ===
if type(param) is not dict:
raise TypeError('Wrong type of input argument param',type(param))
lst_params = ['niter', 'eta', 'gamma'] # necessary params
if any(x not in param.keys() for x in lst_params):
raise ValueError('Missing parameter in param.\n Need {}.\n Got {} '.format(lst_params,list(param.keys())))
niter = param['niter']
eta = param['eta']
gamma = param['gamma']