forked from nanshe-org/spams-python
-
Notifications
You must be signed in to change notification settings - Fork 3
/
spams.py
2670 lines (2261 loc) · 113 KB
/
spams.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
"""
This module makes some functions of the SPAMS library usable
with numpy and scipy.
"""
import spams_wrap
import numpy as np
import scipy.sparse as ssp
########### linalg ##############
def sort(X,mode=True):
"""
sort the elements of X using quicksort
Args:
X: double vector of size n
mode: false for decreasing order (true by default)
Returns:
Y: double vector of size n
Authors:
Julien MAIRAL, 2010 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
"""
y = np.copy(X)
spams_wrap.sort(y,mode)
return y
def calcAAt(A):
"""
Compute efficiently AAt = A*A', when A is sparse
and has a lot more columns than rows. In some cases, it is
up to 20 times faster than the equivalent python expression
AAt=A*A';
Args:
A: double sparse m x n matrix
Returns:
AAt: double m x m matrix
Authors:
Julien MAIRAL, 2009 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
"""
if A.ndim != 2:
raise ValueError("calcAAt: not a matrix")
m = A.shape[0]
AAt = np.empty((m,m),dtype=A.dtype,order="FORTRAN")
spams_wrap.AAt(A,AAt)
return AAt
def calcXAt(X,A):
"""
Compute efficiently XAt = X*A', when A is sparse and has a
lot more columns than rows. In some cases, it is up to 20 times
faster than the equivalent python expression;
Args:
X: double m x n matrix
A: double sparse p x n matrix
Returns:
XAt: double m x p matrix
Authors:
Julien MAIRAL, 2009 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
"""
if A.ndim != 2:
raise ValueError("calcAAt: not a matrix")
m = X.shape[0]
n = A.shape[0]
XAt = np.empty((m,n),dtype=A.dtype,order="FORTRAN")
spams_wrap.XAt(A,X,XAt)
return XAt
def mult(X,Y,transX = False, transY = False):
if transX:
m = X.shape[1]
else:
m = X.shape[0]
if transY:
n = Y.shape[0]
else:
n = Y.shape[1]
XY = np.empty((m,n),dtype=X.dtype,order="FORTRAN")
spams_wrap.mult(X,Y,XY,transX,transY,1,0)
return XY
def calcXY(X,Y):
"""
Compute Z=XY using the BLAS library used by SPAMS.
Args:
X: double m x n matrix
Y: double n x p matrix
Returns:
Z: double m x p matrix
Authors:
Julien MAIRAL, 2009 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
"""
return mult(X,Y,False,False)
def calcXYt(X,Y):
"""
Compute Z=XY' using the BLAS library used by SPAMS.
Args:
X: double m x n matrix
Y: double p x n matrix
Returns:
Z: double m x p matrix
Authors:
Julien MAIRAL, 2009 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
"""
return mult(X,Y,False,True)
def calcXtY(X,Y):
"""
Compute Z=X'Y using the BLAS library used by SPAMS.
Args:
X: double n x m matrix
Y: double n x p matrix
Returns:
Z: double m x p matrix
Authors:
Julien MAIRAL, 2009 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
"""
return mult(X,Y,True,False)
def bayer(X,offset):
"""
bayer applies a Bayer pattern to an image X.
There are four possible offsets.
Args:
X: double m x n matrix
offset: scalar, 0,1,2 or 3
Returns:
Y: double m x m matrix
Authors:
Julien MAIRAL, 2009 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
"""
y = np.copy(X)
spams_wrap.applyBayerPattern(y,offset)
return y
def conjGrad(A,b,x0 = None,tol = 1e-10,itermax = None):
"""
Conjugate gradient algorithm, sometimes faster than the
equivalent python function solve. In order to solve Ax=b;
Args:
A: double square n x n matrix. HAS TO BE POSITIVE DEFINITE
b: double vector of length n.
x0: double vector of length n. (optional) initial guess.
tol: (optional) tolerance.
itermax: (optional) maximum number of iterations.
Returns:
x: double vector of length n.
Authors:
Julien MAIRAL, 2009 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
"""
n = A.shape[1]
if x0 == None:
x = np.zeros((n),dtype = A.dtype)
else:
x = np.copy(x0)
if itermax == None:
itermax = n
spams_wrap.conjugateGradient(A,b,x,tol,itermax)
return x
def invSym(A):
"""
returns the inverse of a symmetric matrix A
Args:
A: double n x n matrix
Returns:
B: double n x n matrix
Authors:
Julien MAIRAL, 2009 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
"""
B = np.copy(A)
spams_wrap.invSym(B)
return B
def normalize(A):
"""
rescale the columns of X so that they have
unit l2-norm.
Args:
X: double m x n matrix
Returns:
Y: double m x n matrix
Authors:
Julien MAIRAL, 2010 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
"""
B = np.copy(A)
spams_wrap.normalize(B)
return B
########### END linalg ##############
##################################################
########### decomp ##################
#### constraint_type definitions
L1COEFFS = spams_wrap.L1COEFFS
L2ERROR = spams_wrap.L2ERROR
PENALTY = spams_wrap.PENALTY
SPARSITY = spams_wrap.SPARSITY
L2ERROR2 = spams_wrap.L2ERROR2
PENALTY2 = spams_wrap.PENALTY2
####
def sparseProject(U,thrs = 1.0,mode = 1,lambda1 = 0.0,lambda2 = 0.0,
lambda3 = 0.0,pos = 0,numThreads = -1):
"""
sparseProject solves various optimization
problems, including projections on a few convex sets.
It aims at addressing the following problems
for all columns u of U in parallel
1) when mode=1 (projection on the l1-ball)
min_v ||u-v||_2^2 s.t. ||v||_1 <= thrs
2) when mode=2
min_v ||u-v||_2^2 s.t. ||v||_2^2 + lamuda1||v||_1 <= thrs
3) when mode=3
min_v ||u-v||_2^2 s.t ||v||_1 + 0.5lamuda1||v||_2^2 <= thrs
4) when mode=4
min_v 0.5||u-v||_2^2 + lamuda1||v||_1 s.t ||v||_2^2 <= thrs
5) when mode=5
min_v 0.5||u-v||_2^2 + lamuda1||v||_1 +lamuda2 FL(v) + ...
0.5lamuda_3 ||v||_2^2
where FL denotes a "fused lasso" regularization term.
6) when mode=6
min_v ||u-v||_2^2 s.t lamuda1||v||_1 +lamuda2 FL(v) + ...
0.5lamuda3||v||_2^2 <= thrs
When pos=true and mode <= 4,
it solves the previous problems with positivity constraints
Args:
U: double m x n matrix (input signals)
m is the signal size
n is the number of signals to project
Kwargs:
thrs: (parameter)
lambda1: (parameter)
lambda2: (parameter)
lambda3: (parameter)
mode: (see above)
pos: (optional, false by default)
numThreads: (optional, number of threads for exploiting
multi-core / multi-cpus. By default, it takes the value -1,
which automatically selects all the available CPUs/cores).
Returns:
V: double m x n matrix (output matrix)
Authors:
Julien MAIRAL, 2009 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
Note:
this function admits a few experimental usages, which have not
been extensively tested:
- single precision setting
"""
m = U.shape[0];
n = U.shape[1];
# paramlist = [('thrs',1.0),('mode',1),('lambda1',0.0),('lambda2',0.0),('lambda3',0.0),('pos',0),('numThreads',-1)]
V = np.empty((m,n),dtype=U.dtype,order="FORTRAN")
params = (thrs,mode,lambda1,lambda2,lambda3,pos,numThreads)
spams_wrap.sparseProject(U,V,thrs,mode,lambda1,lambda2,lambda3,pos,numThreads)
return V
def lasso(X,D= None,Q = None,q = None,return_reg_path = False,L= -1,lambda1= None,lambda2= 0.,
mode= spams_wrap.PENALTY,pos= False,ols= False,numThreads= -1,
max_length_path= -1,verbose=False,cholesky= False):
"""
lasso is an efficient implementation of the
homotopy-LARS algorithm for solving the Lasso.
If the function is called this way spams.lasso(X,D = D, Q = None,...),
it aims at addressing the following problems
for all columns x of X, it computes one column alpha of A
that solves
1) when mode=0
min_{alpha} ||x-Dalpha||_2^2 s.t. ||alpha||_1 <= lambda1
2) when mode=1
min_{alpha} ||alpha||_1 s.t. ||x-Dalpha||_2^2 <= lambda1
3) when mode=2
min_{alpha} 0.5||x-Dalpha||_2^2 + lambda1||alpha||_1 +0.5 lambda2||alpha||_2^2
If the function is called this way spams.lasso(X,D = None, Q = Q, q = q,...),
it solves the above optimisation problem, when Q=D'D and q=D'x.
Possibly, when pos=true, it solves the previous problems
with positivity constraints on the vectors alpha
Args:
X: double m x n matrix (input signals)
m is the signal size
n is the number of signals to decompose
D: double m x p matrix (dictionary)
p is the number of elements in the dictionary
Q: p x p double matrix (Q = D'D)
q: p x n double matrix (q = D'X)
verbose: verbose mode
return_reg_path:
if true the function will return a tuple of matrices.
Kwargs:
lambda1: (parameter)
lambda2: (optional parameter for solving the Elastic-Net)
for mode=0 and mode=1, it adds a ridge on the Gram Matrix
L: (optional), maximum number of steps of the homotopy algorithm (can
be used as a stopping criterion)
pos: (optional, adds non-negativity constraints on the
coefficients, false by default)
mode: (see above, by default: 2)
numThreads: (optional, number of threads for exploiting
multi-core / multi-cpus. By default, it takes the value -1,
which automatically selects all the available CPUs/cores).
cholesky: (optional, default false), choose between Cholesky
implementation or one based on the matrix inversion Lemma
ols: (optional, default false), perform an orthogonal projection
before returning the solution.
max_length_path: (optional) maximum length of the path, by default 4*p
Returns:
A: double sparse p x n matrix (output coefficients)
path: optional, returns the regularisation path for the first signal
A = spams.lasso(X,return_reg_path = False,...)
(A,path) = spams.lasso(X,return_reg_path = True,...)
Authors:
Julien MAIRAL, 2009 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
Note:
this function admits a few experimental usages, which have not
been extensively tested:
- single precision setting (even though the output alpha is double
precision)
Examples:
::
import numpy as np
m = 5;n = 10;nD = 5
np.random.seed(0)
X = np.asfortranarray(np.random.normal(size=(m,n)))
X = np.asfortranarray(X / np.tile(np.sqrt((X*X).sum(axis=0)),(X.shape[0],1)))
D = np.asfortranarray(np.random.normal(size=(100,200)))
D = np.asfortranarray(D / np.tile(np.sqrt((D*D).sum(axis=0)),(D.shape[0],1)))
alpha = spams.lasso(X,D = D,return_reg_path = FALSE,lambda1 = 0.15)
"""
# Note : 'L' and 'max_length_path' default to -1 so that their effective default values
# will be set in spams.h
# paramlist = [('L', -1),('lambda', None),('lambda2', 0.),
# ('mode', spams_wrap.PENALTY),('pos', False),('ols', False),('numThreads', -1),
# ('max_length_path', -1),('verbose',True),('cholesky', False)]
if Q != None:
if q == None:
raise ValueError("lasso : q is needed when Q is given")
else:
if D == None:
raise ValueError("lasso : you must give D or Q and q")
if lambda1 == None:
raise ValueError("lasso : lambda1 must be defined")
path = None
if(q != None):
if return_reg_path:
((indptr,indices,data,shape),path) = spams_wrap.lassoQq(X,Q,q,return_reg_path,L,lambda1,lambda2,mode,pos,ols,numThreads,max_length_path,verbose,cholesky)
else:
(indptr,indices,data,shape) = spams_wrap.lassoQq(X,Q,q,return_reg_path,L,lambda1,lambda2,mode,pos,ols,numThreads,max_length_path,verbose,cholesky)
else:
if return_reg_path:
((indptr,indices,data,shape),path) = spams_wrap.lassoD(X,D,return_reg_path,L,lambda1,lambda2,mode,pos,ols,numThreads,max_length_path,verbose,cholesky)
else:
(indptr,indices,data,shape) = spams_wrap.lassoD(X,D,return_reg_path,L,lambda1,lambda2,mode,pos,ols,numThreads,max_length_path,verbose,cholesky)
alpha = ssp.csc_matrix((data,indices,indptr),shape)
if return_reg_path:
return (alpha,path)
else:
return alpha
def lassoMask(X,D,B,L= -1,lambda1= None,lambda2= 0.,
mode= spams_wrap.PENALTY,pos= False,numThreads= -1,verbose = False):
"""
lasso is a variant of lasso that handles
binary masks. It aims at addressing the following problems
for all columns x of X, and beta of B, it computes one column alpha of A
that solves
1) when mode=0
min_{alpha} ||diag(beta)(x-Dalpha)||_2^2 s.t. ||alpha||_1 <= lambda1
2) when mode=1
min_{alpha} ||alpha||_1 s.t. ||diag(beta)(x-Dalpha)||_2^2
<= lambda1*||beta||_0/m
3) when mode=2
min_{alpha} 0.5||diag(beta)(x-Dalpha)||_2^2 +
lambda1*(||beta||_0/m)*||alpha||_1 +
(lambda2/2)||alpha||_2^2
Possibly, when pos=true, it solves the previous problems
with positivity constraints on the vectors alpha
Args:
X: double m x n matrix (input signals)
m is the signal size
n is the number of signals to decompose
D: double m x p matrix (dictionary)
p is the number of elements in the dictionary
B: boolean m x n matrix (mask)
p is the number of elements in the dictionary
verbose: verbose mode
Kwargs:
lambda1: (parameter)
L: (optional, maximum number of elements of each
decomposition)
pos: (optional, adds positivity constraints on the
coefficients, false by default)
mode: (see above, by default: 2)
lambda2: (optional parameter for solving the Elastic-Net)
for mode=0 and mode=1, it adds a ridge on the Gram Matrix
numThreads: (optional, number of threads for exploiting
multi-core / multi-cpus. By default, it takes the value -1,
which automatically selects all the available CPUs/cores).
Returns:
A: double sparse p x n matrix (output coefficients)
Authors:
Julien MAIRAL, 2010 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
Note:
this function admits a few experimental usages, which have not
been extensively tested:
- single precision setting (even though the output alpha is double
precision)
"""
# Note : 'L' and 'max_length_path' default to -1 so that their effective default values
# will be set in spams.h
if lambda1 == None:
raise ValueError("lassoMask : lambda1 must be defined")
(indptr,indices,data,shape) = spams_wrap.lassoMask(X,D,B,L,lambda1,lambda2,mode,pos,numThreads,verbose)
alpha = ssp.csc_matrix((data,indices,indptr),shape)
return alpha
def lassoWeighted(X,D,W,L= -1,lambda1= None,
mode= spams_wrap.PENALTY,pos= False,numThreads= -1,verbose = False):
"""
lassoWeighted is an efficient implementation of the
LARS algorithm for solving the weighted Lasso. It is optimized
for solving a large number of small or medium-sized
decomposition problem (and not for a single large one).
It first computes the Gram matrix D'D and then perform
a Cholesky-based OMP of the input signals in parallel.
For all columns x of X, and w of W, it computes one column alpha of A
which is the solution of
1) when mode=0
min_{alpha} ||x-Dalpha||_2^2 s.t.
||diag(w)alpha||_1 <= lambda1
2) when mode=1
min_{alpha} ||diag(w)alpha||_1 s.t.
||x-Dalpha||_2^2 <= lambda1
3) when mode=2
min_{alpha} 0.5||x-Dalpha||_2^2 +
lambda1||diag(w)alpha||_1
Possibly, when pos=true, it solves the previous problems
with positivity constraints on the vectors alpha
Args:
X: double m x n matrix (input signals)
m is the signal size
n is the number of signals to decompose
D: double m x p matrix (dictionary)
p is the number of elements in the dictionary
W: double p x n matrix (weights)
verbose: verbose mode
Kwargs:
lambda1: (parameter)
L: (optional, maximum number of elements of each
decomposition)
pos: (optional, adds positivity constraints on the
coefficients, false by default)
mode: (see above, by default: 2)
numThreads: (optional, number of threads for exploiting
multi-core / multi-cpus. By default, it takes the value -1,
which automatically selects all the available CPUs/cores).
Returns:
A: double sparse p x n matrix (output coefficients)
Authors:
Julien MAIRAL, 2009 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
Note:
this function admits a few experimental usages, which have not
been extensively tested:
- single precision setting (even though the output alpha is double
precision)
"""
# Note : 'L' and 'max_length_path' default to -1 so that their effective default values
# will be set in spams.h
if lambda1 == None:
raise ValueError("lassoWeighted : lambda1 must be defined")
(indptr,indices,data,shape) = spams_wrap.lassoWeighted(X,D,W,L,lambda1,mode,pos,numThreads,verbose)
alpha = ssp.csc_matrix((data,indices,indptr),shape)
return alpha
def omp(X,D,L=None,eps= None,lambda1 = None,return_reg_path = False, numThreads = -1):
"""
omp is an efficient implementation of the
Orthogonal Matching Pursuit algorithm. It is optimized
for solving a large number of small or medium-sized
decomposition problem (and not for a single large one).
It first computes the Gram matrix D'D and then perform
a Cholesky-based OMP of the input signals in parallel.
X=[x^1,...,x^n] is a matrix of signals, and it returns
a matrix A=[alpha^1,...,alpha^n] of coefficients.
it addresses for all columns x of X,
min_{alpha} ||alpha||_0 s.t ||x-Dalpha||_2^2 <= eps
or
min_{alpha} ||x-Dalpha||_2^2 s.t. ||alpha||_0 <= L
or
min_{alpha} 0.5||x-Dalpha||_2^2 + lambda1||alpha||_0
Args:
X: double m x n matrix (input signals)
m is the signal size
n is the number of signals to decompose
D: double m x p matrix (dictionary)
p is the number of elements in the dictionary
All the columns of D should have unit-norm !
return_reg_path:
if true the function will return a tuple of matrices.
Kwargs:
L: (optional, maximum number of elements in each decomposition,
min(m,p) by default)
eps: (optional, threshold on the squared l2-norm of the residual,
0 by default
lambda1: (optional, penalty parameter, 0 by default
numThreads: (optional, number of threads for exploiting
multi-core / multi-cpus. By default, it takes the value -1,
which automatically selects all the available CPUs/cores).
Returns:
A: double sparse p x n matrix (output coefficients)
path (optional): double dense p x L matrix (regularization path of the first signal)
A = spams.omp(X,D,L,eps,return_reg_path = False,...)
(A,path) = spams.omp(X,D,L,eps,return_reg_path = True,...)
Authors:
Julien MAIRAL, 2009 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
Note:
this function admits a few experimental usages, which have not
been extensively tested:
- single precision setting (even though the output alpha is double
precision)
- Passing an int32 vector of length n to L provides
a different parameter L for each input signal x_i
- Passing a double vector of length n to eps and or lambda1
provides a different parameter eps (or lambda1) for each input signal x_i
"""
path = None
given_L = False
given_eps = False
given_lambda1 = False
if L == None:
L = np.array([0],dtype=np.int32)
else:
given_L = True
if str(type(L)) != "<type 'numpy.ndarray'>":
L = np.array([L],dtype=np.int32)
if eps == None:
eps = np.array([0.],dtype=X.dtype)
else:
given_eps = True
if str(type(eps)) != "<type 'numpy.ndarray'>":
eps = np.array([eps],dtype=X.dtype)
if lambda1 == None:
lambda1 = np.array([0.],dtype=X.dtype)
else:
given_lambda1 = True
if str(type(lambda1)) != "<type 'numpy.ndarray'>":
lambda1 = np.array([lambda1],dtype=X.dtype)
if return_reg_path:
((indptr,indices,data,shape),path) = spams_wrap.omp(X,D,return_reg_path,given_L,L,given_eps,eps,given_lambda1,lambda1,numThreads)
else:
(indptr,indices,data,shape) = spams_wrap.omp(X,D,return_reg_path,given_L,L,given_eps,eps,given_lambda1,lambda1,numThreads)
alpha = ssp.csc_matrix((data,indices,indptr),shape)
if return_reg_path:
return (alpha,path)
else:
return alpha
def ompMask(X,D,B,L=None,eps= None,lambda1 = None,return_reg_path = False, numThreads = -1):
"""
ompMask is a variant of omp that allow using
a binary mask B
for all columns x of X, and columns beta of B, it computes a column
alpha of A by addressing
min_{alpha} ||alpha||_0 s.t ||diag(beta)*(x-Dalpha)||_2^2
<= eps*||beta||_0/m
or
min_{alpha} ||diag(beta)*(x-Dalpha)||_2^2 s.t. ||alpha||_0 <= L
or
min_{alpha} 0.5||diag(beta)*(x-Dalpha)||_2^2 + lambda1||alpha||_0
Args:
X: double m x n matrix (input signals)
m is the signal size
n is the number of signals to decompose
D: double m x p matrix (dictionary)
p is the number of elements in the dictionary
All the columns of D should have unit-norm !
B: boolean m x n matrix (mask)
p is the number of elements in the dictionary
return_reg_path:
if true the function will return a tuple of matrices.
Kwargs:
L: (optional, maximum number of elements in each decomposition,
min(m,p) by default)
eps: (optional, threshold on the squared l2-norm of the residual,
0 by default
lambda1: (optional, penalty parameter, 0 by default
numThreads: (optional, number of threads for exploiting
multi-core / multi-cpus. By default, it takes the value -1,
which automatically selects all the available CPUs/cores).
Returns:
A: double sparse p x n matrix (output coefficients)
path (optional): double dense p x L matrix
(regularization path of the first signal)
A = spams.ompMask(X,D,B,L,eps,return_reg_path = False,...)
(A,path) = spams.ompMask(X,D,B,L,eps,return_reg_path = True,...)
Authors:
Julien MAIRAL, 2010 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
Note:
this function admits a few experimental usages, which have not
been extensively tested:
- single precision setting (even though the output alpha is double
precision)
- Passing an int32 vector of length n to L provides
a different parameter L for each input signal x_i
- Passing a double vector of length n to eps and or lambda1
provides a different parameter eps (or lambda1) for each input signal x_i
"""
path = None
given_L = False
given_eps = False
given_lambda1 = False
if L == None:
L = np.array([0],dtype=np.int32)
else:
given_L = True
if str(type(L)) != "<type 'numpy.ndarray'>":
L = np.array([L],dtype=np.int32)
if eps == None:
eps = np.array([0.],dtype=X.dtype)
else:
given_eps = True
if str(type(eps)) != "<type 'numpy.ndarray'>":
eps = np.array([eps],dtype=X.dtype)
if lambda1 == None:
lambda1 = np.array([0.],dtype=X.dtype)
else:
given_lambda1 = True
if str(type(lambda1)) != "<type 'numpy.ndarray'>":
lambda1 = np.array([lambda1],dtype=X.dtype)
if return_reg_path:
((indptr,indices,data,shape),path) = spams_wrap.ompMask(X,D,B,return_reg_path,given_L,L,given_eps,eps,given_lambda1,lambda1,numThreads)
else:
(indptr,indices,data,shape) = spams_wrap.ompMask(X,D,B,return_reg_path,given_L,L,given_eps,eps,given_lambda1,lambda1,numThreads)
alpha = ssp.csc_matrix((data,indices,indptr),shape)
if return_reg_path:
return (alpha,path)
else:
return alpha
def cd(X,D,A0,lambda1 = None,mode= spams_wrap.PENALTY,itermax=100,tol = 0.001,numThreads =-1):
"""
cd addresses l1-decomposition problem with a
coordinate descent type of approach.
It is optimized for solving a large number of small or medium-sized
decomposition problem (and not for a single large one).
It first computes the Gram matrix D'D.
This method is particularly well adapted when there is low
correlation between the dictionary elements and when one can benefit
from a warm restart.
It aims at addressing the two following problems
for all columns x of X, it computes a column alpha of A such that
2) when mode=1
min_{alpha} ||alpha||_1 s.t. ||x-Dalpha||_2^2 <= lambda1
For this constraint setting, the method solves a sequence of
penalized problems (corresponding to mode=2) and looks
for the corresponding Lagrange multplier with a simple but
efficient heuristic.
3) when mode=2
min_{alpha} 0.5||x-Dalpha||_2^2 + lambda1||alpha||_1
Args:
X: double m x n matrix (input signals)
m is the signal size
n is the number of signals to decompose
D: double m x p matrix (dictionary)
p is the number of elements in the dictionary
All the columns of D should have unit-norm !
A0: double sparse p x n matrix (initial guess)
Kwargs:
lambda1: (parameter)
mode: (optional, see above, by default 2)
itermax: (maximum number of iterations)
tol: (tolerance parameter)
numThreads: (optional, number of threads for exploiting
multi-core / multi-cpus. By default, it takes the value -1,
which automatically selects all the available CPUs/cores).
Returns:
A: double sparse p x n matrix (output coefficients)
Authors:
Julien MAIRAL, 2009 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
Note:
this function admits a few experimental usages, which have not
been extensively tested:
- single precision setting (even though the output alpha
is double precision)
"""
if lambda1 == None:
raise ValueError("cd : lambda1 must be defined")
(indptr,indices,data,shape) = spams_wrap.cd(X,D,A0,lambda1,mode,itermax,tol,numThreads)
alpha = ssp.csc_matrix((data,indices,indptr),shape)
return alpha
def somp(X,D,list_groups,L = None,eps = 0.,numThreads = -1):
"""
somp is an efficient implementation of a
Simultaneous Orthogonal Matching Pursuit algorithm. It is optimized
for solving a large number of small or medium-sized
decomposition problem (and not for a single large one).
It first computes the Gram matrix D'D and then perform
a Cholesky-based OMP of the input signals in parallel.
It aims at addressing the following NP-hard problem
X is a matrix structured in groups of signals, which we denote
by X=[X_1,...,X_n]
for all matrices X_i of X,
min_{A_i} ||A_i||_{0,infty} s.t ||X_i-D A_i||_2^2 <= eps*n_i
where n_i is the number of columns of X_i
or
min_{A_i} ||X_i-D A_i||_2^2 s.t. ||A_i||_{0,infty} <= L
Args:
X: double m x N matrix (input signals)
m is the signal size
N is the total number of signals
D: double m x p matrix (dictionary)
p is the number of elements in the dictionary
All the columns of D should have unit-norm !
list_groups: int32 vector containing the indices (starting at 0)
of the first elements of each groups.
Kwargs:
L: (maximum number of elements in each decomposition)
eps: (threshold on the squared l2-norm of the residual
numThreads: (optional, number of threads for exploiting
multi-core / multi-cpus. By default, it takes the value -1,
which automatically selects all the available CPUs/cores).
Returns:
alpha: double sparse p x N matrix (output coefficients)
Authors:
Julien MAIRAL, 2010 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
Note:
this function admits a few experimental usages, which have not
been extensively tested:
- single precision setting (even though the output alpha is double
precision)
"""
if L == None:
raise ValueError("somp : L must be defined")
(indptr,indices,data,shape) = spams_wrap.somp(X,D,list_groups,L,eps,numThreads)
alpha = ssp.csc_matrix((data,indices,indptr),shape)
return alpha
def l1L2BCD(X,D,alpha0,list_groups,lambda1 = None, mode= spams_wrap.PENALTY, itermax = 100, tol = 1e-3,numThreads = -1):
"""
l1L2BCD is a solver for a
Simultaneous signal decomposition formulation based on block
coordinate descent.
X is a matrix structured in groups of signals, which we denote
by X=[X_1,...,X_n]
if mode=2, it solves
for all matrices X_i of X,
min_{A_i} 0.5||X_i-D A_i||_2^2 + lambda1/sqrt(n_i)||A_i||_{1,2}
where n_i is the number of columns of X_i
if mode=1, it solves
min_{A_i} ||A_i||_{1,2} s.t. ||X_i-D A_i||_2^2 <= n_i lambda1
Args:
X: double m x N matrix (input signals)
m is the signal size
N is the total number of signals
D: double m x p matrix (dictionary)
p is the number of elements in the dictionary
alpha0: double dense p x N matrix (initial solution)
list_groups: int32 vector containing the indices (starting at 0)
of the first elements of each groups.
Kwargs:
lambda1: (regularization parameter)
mode: (see above, by default 2)
itermax: (maximum number of iterations, by default 100)
tol: (tolerance parameter, by default 0.001)
numThreads: (optional, number of threads for exploiting
multi-core / multi-cpus. By default, it takes the value -1,
which automatically selects all the available CPUs/cores).
Returns:
alpha: double sparse p x N matrix (output coefficients)
Authors:
Julien MAIRAL, 2010 (spams, matlab interface and documentation)
Jean-Paul CHIEZE 2011-2012 (python interface)
Note:
this function admits a few experimental usages, which have not
been extensively tested:
- single precision setting (even though the output alpha is double
precision)
"""
if lambda1 == None:
raise ValueError("l1L2BCD : lambda1 must be defined")
alpha = np.copy(alpha0)
spams_wrap.l1L2BCD(X,D,alpha,list_groups,lambda1,mode,itermax,tol,numThreads)
return alpha
########### END decomp ##############
##################################################
########### prox ##################
def fistaFlat(
Y,X,W0,return_optim_info = False,numThreads =-1,max_it =1000,L0=1.0,
fixed_step=False,gamma=1.5,lambda1=1.0,delta=1.0,lambda2=0.,lambda3=0.,
a=1.0,b=0.,c=1.0,tol=0.000001,it0=100,max_iter_backtracking=1000,
compute_gram=False,lin_admm=False,admm=False,intercept=False,
resetflow=False,regul="",loss="",verbose=False,pos=False,clever=False,
log=False,ista=False,subgrad=False,logName="",is_inner_weights=False,
inner_weights=None,size_group=1,groups = None,sqrt_step=True,transpose=False,linesearch_mode=0):
"""
fistaFlat solves sparse regularized problems.
X is a design matrix of size m x p
X=[x^1,...,x^n]', where the x_i's are the rows of X
Y=[y^1,...,y^n] is a matrix of size m x n
It implements the algorithms FISTA, ISTA and subgradient descent.
- if loss='square' and regul is a regularization function for vectors,
the entries of Y are real-valued, W = [w^1,...,w^n] is a matrix of size p x n
For all column y of Y, it computes a column w of W such that
w = argmin 0.5||y- X w||_2^2 + lambda1 psi(w)
- if loss='square' and regul is a regularization function for matrices
the entries of Y are real-valued, W is a matrix of size p x n.
It computes the matrix W such that
W = argmin 0.5||Y- X W||_F^2 + lambda1 psi(W)
- loss='square-missing' same as loss='square', but handles missing data
represented by NaN (not a number) in the matrix Y
- if loss='logistic' and regul is a regularization function for vectors,
the entries of Y are either -1 or +1, W = [w^1,...,w^n] is a matrix of size p x n
For all column y of Y, it computes a column w of W such that
w = argmin (1/m)sum_{j=1}^m log(1+e^(-y_j x^j' w)) + lambda1 psi(w),
where x^j is the j-th row of X.
- if loss='logistic' and regul is a regularization function for matrices
the entries of Y are either -1 or +1, W is a matrix of size p x n
W = argmin sum_{i=1}^n(1/m)sum_{j=1}^m log(1+e^(-y^i_j x^j' w^i)) + lambda1 psi(W)
- if loss='multi-logistic' and regul is a regularization function for vectors,
the entries of Y are in {0,1,...,N} where N is the total number of classes
W = [W^1,...,W^n] is a matrix of size p x Nn, each submatrix W^i is of size p x N
for all submatrix WW of W, and column y of Y, it computes
WW = argmin (1/m)sum_{j=1}^m log(sum_{j=1}^r e^(x^j'(ww^j-ww^{y_j}))) + lambda1 sum_{j=1}^N psi(ww^j),
where ww^j is the j-th column of WW.
- if loss='multi-logistic' and regul is a regularization function for matrices,
the entries of Y are in {0,1,...,N} where N is the total number of classes
W is a matrix of size p x N, it computes
W = argmin (1/m)sum_{j=1}^m log(sum_{j=1}^r e^(x^j'(w^j-w^{y_j}))) + lambda1 psi(W)
where ww^j is the j-th column of WW.