-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathproximal.py
More file actions
1405 lines (1126 loc) · 48.6 KB
/
Copy pathproximal.py
File metadata and controls
1405 lines (1126 loc) · 48.6 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
# -*- coding: utf-8 -*-
"""
The :mod:`parsimony.algorithms.proximal` module contains several algorithms
that involve proximal operators.
Algorithms may not store states. I.e., if they are classes, do not keep
references to objects with state in the algorithm objects. It should be
possible to copy and share algorithms between e.g. estimators, and thus they
should not depend on any state.
Created on Mon Jun 2 15:42:13 2014
Copyright (c) 2013-2014, CEA/DSV/I2BM/Neurospin. All rights reserved.
@author: Tommy Löfstedt, Edouard Duchesnay, Fouad Hadj-Selem
@email: lofstedt.tommy@gmail.com, edouard.duchesnay@cea.fr,
fouad.hadjselem@cea.fr
@license: BSD 3-clause.
"""
import numpy as np
import warnings
try:
from scipy.interpolate import PchipInterpolator as interp1
except ImportError:
from scipy.interpolate import interp1d as interp1
try:
from . import bases # Only works when imported as a package.
except (ValueError, SystemError):
import parsimony.algorithms.bases as bases # When run as a program.
import parsimony.utils as utils
import parsimony.utils.maths as maths
import parsimony.utils.consts as consts
from parsimony.algorithms.utils import Info
import parsimony.functions.properties as properties
__all__ = ["ISTA", "FISTA", "CONESTA", "StaticCONESTA",
"ADMM",
"DykstrasProjectionAlgorithm",
"ParallelDykstrasProjectionAlgorithm"]
class ISTA(bases.ExplicitAlgorithm,
bases.IterativeAlgorithm,
bases.InformationAlgorithm):
"""The iterative shrinkage-thresholding algorithm.
Parameters
----------
eps : float
Positive float. Tolerance for the stopping criterion.
info : List or tuple of utils.consts.Info
What, if any, extra run information should be stored. Default is an
empty list, which means that no run information is computed nor
returned.
max_iter : int
Non-negative integer. Maximum allowed number of iterations.
min_iter : int
Non-negative integer less than or equal to max_iter. Minimum number of
iterations that must be performed. Default is 1.
callback: Callable
A callable object that will be called at the end of each iteration with
locals() as arguments.
Examples
--------
>>> from parsimony.algorithms.proximal import ISTA
>>> from parsimony.functions import LinearRegressionL1L2TV
>>> import scipy.sparse as sparse
>>> import numpy as np
>>>
>>> np.random.seed(42)
>>> X = np.random.rand(100, 50)
>>> y = np.random.rand(100, 1)
>>> A = sparse.csr_matrix((50, 50)) # Unused here
>>> function = LinearRegressionL1L2TV(X, y, 0.0, 0.0, 0.0,
... A=A, mu=0.0)
>>> ista = ISTA(max_iter=10000)
>>> beta1 = ista.run(function, np.random.rand(50, 1))
>>> beta2 = np.dot(np.linalg.pinv(X), y)
>>> np.linalg.norm(beta1 - beta2) # doctest: +ELLIPSIS
0.00031215...
>>>
>>> np.random.seed(42)
>>> X = np.random.rand(100, 50)
>>> y = np.random.rand(100, 1)
>>> A = sparse.csr_matrix((50, 50)) # Unused here
>>> function = LinearRegressionL1L2TV(X, y, 0.1, 0.0, 0.0,
... A=A, mu=0.0)
>>> ista = ISTA(max_iter=10000)
>>> beta1 = ista.run(function, np.random.rand(50, 1))
>>> beta2 = np.dot(np.linalg.pinv(X), y)
>>> np.linalg.norm(beta1 - beta2) # doctest: +ELLIPSIS
0.82723303...
>>> int(np.linalg.norm(beta2.ravel(), 0))
50
>>> int(np.linalg.norm(beta1.ravel(), 0))
7
"""
INTERFACES = [properties.Function,
properties.Gradient,
properties.StepSize,
properties.ProximalOperator]
INFO_PROVIDED = [Info.ok,
Info.num_iter,
Info.time,
Info.fvalue, # <-- To be deprecated!
Info.func_val,
Info.converged]
def __init__(self, eps=consts.TOLERANCE, info=[],
max_iter=20000, min_iter=1, callback=None):
super(ISTA, self).__init__(info=info,
max_iter=max_iter,
min_iter=min_iter)
self.eps = eps
self.callback = callback
@bases.force_reset
@bases.check_compatibility
def run(self, function, beta):
"""Find the minimiser of the given function, starting at beta.
Parameters
----------
function : Function. The function to minimise.
beta : Numpy array. The start vector.
"""
if self.info_requested(Info.ok):
self.info_set(Info.ok, False)
step = function.step(beta)
betanew = betaold = beta
if self.info_requested(Info.time):
t = []
if self.info_requested(Info.fvalue) \
or self.info_requested(Info.func_val):
f = []
if self.info_requested(Info.converged):
self.info_set(Info.converged, False)
for i in range(1, self.max_iter + 1):
if self.info_requested(Info.time):
tm = utils.time_cpu()
step = function.step(betanew)
betaold = betanew
betanew = function.prox(betaold - step * function.grad(betaold),
step,
eps=1.0 / (float(i) ** (2.0 + consts.FLOAT_EPSILON)),
max_iter=self.max_iter)
if self.info_requested(Info.time):
t.append(utils.time_cpu() - tm)
if self.info_requested(Info.fvalue) \
or self.info_requested(Info.func_val):
f.append(function.f(betanew))
if self.callback is not None:
self.callback(locals())
if (1.0 / step) * maths.norm(betanew - betaold) < self.eps \
and i >= self.min_iter:
if self.info_requested(Info.converged):
self.info_set(Info.converged, True)
break
self.num_iter = i
if self.info_requested(Info.num_iter):
self.info_set(Info.num_iter, i)
if self.info_requested(Info.time):
self.info_set(Info.time, t)
if self.info_requested(Info.fvalue):
self.info_set(Info.fvalue, f)
if self.info_requested(Info.func_val):
self.info_set(Info.func_val, f)
if self.info_requested(Info.ok):
self.info_set(Info.ok, True)
return betanew
class FISTA(bases.ExplicitAlgorithm,
bases.IterativeAlgorithm,
bases.InformationAlgorithm):
"""The fast iterative shrinkage-thresholding algorithm.
Parameters
----------
eps : float
Must be positive. The tolerance for the stopping criterion.
use_gap : bool
If true, FISTA will use a dual gap, from the interface DualFunction, in
the stopping criterion as
if function.gap(beta) < eps:
break
Default is False, since the gap may be very expensive to compute.
info : List or tuple of utils.consts.Info
What, if any, extra run information should be stored. Default is an
empty list, which means that no run information is computed nor
returned.
max_iter : int
Non-negative integer. Maximum allowed number of iterations.
min_iter : int
Non-negative integer less than or equal to max_iter. Minimum number of
iterations that must be performed. Default is 1.
callback: Callable
A callable object that will be called at the end of each iteration with
locals() as arguments.
Example
-------
>>> from parsimony.algorithms.proximal import FISTA
>>> from parsimony.functions import LinearRegressionL1L2TV
>>> import scipy.sparse as sparse
>>> import numpy as np
>>>
>>> np.random.seed(42)
>>> X = np.random.rand(100, 50)
>>> y = np.random.rand(100, 1)
>>> A = sparse.csr_matrix((50, 50)) # Unused here
>>> function = LinearRegressionL1L2TV(X, y, 0.0, 0.0, 0.0,
... A=A, mu=0.0)
>>> fista = FISTA(max_iter=10000)
>>> beta1 = fista.run(function, np.random.rand(50, 1))
>>> beta2 = np.dot(np.linalg.pinv(X), y)
>>> np.linalg.norm(beta1 - beta2) # doctest: +ELLIPSIS
4.618281...e-06
>>>
>>> np.random.seed(42)
>>> X = np.random.rand(100, 50)
>>> y = np.random.rand(100, 1)
>>> A = sparse.csr_matrix((50, 50)) # Unused here
>>> function = LinearRegressionL1L2TV(X, y, 0.1, 0.0, 0.0,
... A=A, mu=0.0)
>>> fista = FISTA(max_iter=10000)
>>> beta1 = fista.run(function, np.random.rand(50, 1))
>>> beta2 = np.dot(np.linalg.pinv(X), y)
>>> np.linalg.norm(beta1 - beta2) # doctest: +ELLIPSIS
0.82723292...
>>> int(np.linalg.norm(beta2.ravel(), 0))
50
>>> int(np.linalg.norm(beta1.ravel(), 0))
7
"""
INTERFACES = [properties.Function,
properties.Gradient,
properties.StepSize,
properties.ProximalOperator]
INFO_PROVIDED = [Info.ok,
Info.num_iter,
Info.time,
Info.fvalue, # <-- To be deprecated!
Info.func_val,
Info.converged,
Info.gap,
Info.verbose]
def __init__(self, use_gap=False,
info=[], eps=consts.TOLERANCE, max_iter=10000, min_iter=1,
callback=None,
simulation=False,
return_best=False):
super(FISTA, self).__init__(info=info,
max_iter=int(max_iter),
min_iter=int(min_iter))
self.use_gap = bool(use_gap)
self.eps = max(consts.FLOAT_EPSILON, float(eps))
self.callback = callback
self.simulation = bool(simulation)
self.return_best = bool(return_best)
@bases.force_reset
@bases.check_compatibility
def run(self, function, beta):
"""Find the minimiser of the given function, starting at beta.
Parameters
----------
function : Function. The function to minimise.
beta : Numpy array. The start vector.
"""
if self.info_requested(Info.ok):
self.info_set(Info.ok, False)
z = betanew = betaold = beta
if self.info_requested(Info.time):
t_ = []
if self.info_requested(Info.fvalue) \
or self.info_requested(Info.func_val):
f_ = []
if self.info_requested(Info.converged):
self.info_set(Info.converged, False)
if self.info_requested(Info.gap):
gap_ = []
if self.return_best:
best_f = np.inf
best_beta = None
#print("########", max(self.min_iter, self.max_iter) + 1)
for i in range(1, max(self.min_iter, self.max_iter) + 1):
if self.info_requested(Info.time):
tm = utils.time_cpu()
z = betanew + ((i - 2.0) / (i + 1.0)) * (betanew - betaold)
step = function.step(z)
betaold = betanew
betanew = function.prox(z - step * function.grad(z),
step,
eps=1.0 / (float(i) ** (4.0 + consts.FLOAT_EPSILON)),
max_iter=self.max_iter)
if self.info_requested(Info.time):
t_.append(utils.time_cpu() - tm)
if self.info_requested(Info.fvalue) \
or self.info_requested(Info.func_val):
func_val = function.f(betanew)
f_.append(func_val)
if self.return_best and func_val < best_f:
best_f = func_val
best_beta = betanew
if self.callback is not None:
self.callback(locals())
if self.use_gap:
gap = function.gap(betanew,
eps=self.eps,
max_iter=self.max_iter)
# TODO: Warn if G_new < -consts.TOLERANCE.
gap = np.abs(gap) # May happen close to machine epsilon.
if self.info_requested(Info.gap):
gap_.append(gap)
if not self.simulation:
if self.info_requested(Info.verbose):
print("FISTA ite:%i, gap:%g" % (i, gap))
if np.all(gap < self.eps):
if self.info_requested(Info.converged):
self.info_set(Info.converged, True)
break
else:
if not self.simulation:
eps_cur = maths.norm(betanew - z, axis=0)
if self.info_requested(Info.verbose):
print("FISTA ite: %i, eps_cur:%g" % (i, eps_cur))
if np.all(step > 0.0):
converged = (1.0 / step) * eps_cur < self.eps
if np.all(converged) \
and i >= self.min_iter:
if self.info_requested(Info.converged):
self.info_set(Info.converged, True)
break
else: # TODO: Fix this!
converged = maths.norm(betanew - z, axis=0) < self.eps
if np.all(converged) \
and i >= self.min_iter:
if self.info_requested(Info.converged):
self.info_set(Info.converged, True)
break
self.num_iter = i
if self.info_requested(Info.num_iter):
self.info_set(Info.num_iter, i)
if self.info_requested(Info.time):
self.info_set(Info.time, t_)
if self.info_requested(Info.fvalue):
self.info_set(Info.fvalue, f_)
if self.info_requested(Info.func_val):
self.info_set(Info.func_val, f_)
if self.info_requested(Info.gap):
self.info_set(Info.gap, gap_)
if self.info_requested(Info.ok):
self.info_set(Info.ok, True)
if self.return_best and best_beta is not None:
return best_beta
else:
return betanew
class CONESTA(bases.ExplicitAlgorithm,
bases.IterativeAlgorithm,
bases.InformationAlgorithm):
"""COntinuation with NEsterov smoothing in a Soft-Thresholding Algorithm,
or CONESTA for short.
Parameters
----------
mu_min : float
A non-negative float. A "very small" mu to use as a lower bound for mu.
tau : float
A float between 0 < tau < 1. The rate at which eps is decreasing.
Default is 0.5.
eps : float
A positive float. Tolerance for the stopping criterion.
info : List or tuple of utils.Info.
What, if any, extra run information should be stored. Default is an
empty list, which means that no run information is computed nor
returned.
max_iter : int
Non-negative integer. Maximum allowed number of iterations.
min_iter : int
Non-negative integer less than or equal to max_iter. Minimum number of
iterations that must be performed. Default is 1.
eps_max: float
A maximum value for eps computed from the gap. If
np.isfinite(tau * gap(beta)) then use eps_max to avoid NaN. Default is
a large value: 10.
callback: Callable
A callable object that will be called at the end of each iteration with
locals() as arguments.
"""
INTERFACES = [properties.NesterovFunction,
properties.StepSize,
properties.ProximalOperator,
properties.Continuation,
properties.DualFunction]
INFO_PROVIDED = [Info.ok,
Info.converged,
Info.num_iter,
Info.continuations,
Info.time,
Info.fvalue,
Info.func_val,
Info.gap,
Info.mu,
Info.verbose]
def __init__(self, mu_min=consts.TOLERANCE, tau=0.5,
info=[], eps=consts.TOLERANCE, max_iter=10000, min_iter=1,
eps_max=10.,
callback=None,
simulation=False):
super(CONESTA, self).__init__(info=info,
max_iter=max_iter, min_iter=min_iter)
self.mu_min = max(consts.FLOAT_EPSILON, float(mu_min))
self.eps_max = eps_max
self.tau = max(consts.TOLERANCE,
min(float(tau), 1.0 - consts.TOLERANCE))
self.eps = max(consts.TOLERANCE, float(eps))
self.callback = callback
self.simulation = bool(simulation)
@bases.force_reset
@bases.check_compatibility
def run(self, function, beta):
# Copy the allowed info keys for FISTA.
fista_info = list()
for nfo in self.info_copy():
if nfo in FISTA.INFO_PROVIDED:
fista_info.append(nfo)
# CONESTA always asks for the gap.
if Info.gap not in fista_info:
fista_info.append(Info.gap)
# Create the inner algorithm.
algorithm = FISTA(use_gap=True, info=fista_info, eps=self.eps,
max_iter=self.max_iter, min_iter=self.min_iter)
# Not ok until the end.
if self.info_requested(Info.ok):
self.info_set(Info.ok, False)
# Time the init computation (essentialy Lipchitz constant in mu_opt).
if self.info_requested(Info.time):
init_time = utils.time_cpu()
# Compute current gap, precision eps (gap decreased by tau) and mu.
function.set_mu(consts.TOLERANCE)
gap = function.gap(beta, eps=self.eps, max_iter=self.max_iter)
eps = self.tau * np.abs(gap)
# Warning below if gap < -consts.TOLERANCE: See Special case 1
gM = function.eps_max(1.0)
loop = True
# Special case 1: gap is very small: stopping criterion satisfied
if np.any(gap < self.eps): # "- mu * gM" has been removed since mu == 0
warnings.warn(
"Stopping criterion satisfied before the first iteration."
" Either beta_start a the solution (given eps)."
" If beta_start is null the problem might be over-penalized. "
" Then try smaller penalization.")
if np.all(gap < self.eps):
loop = False
# Special case 2: gap infinite or NaN => eps is not finite or NaN
# => mu is NaN etc. Force eps to a large value, to force some FISTA
# iteration to get better starting point
eps[~np.isfinite(eps)] = self.eps_max
# if not np.isfinite(eps):
# eps = self.eps_max
if loop: # mu is useless if loop is False
mu = function.mu_opt(eps)
function.set_mu(mu)
# Initialise info variables. Info variables have the suffix "_".
if self.info_requested(Info.time):
t_ = []
init_time = utils.time_cpu() - init_time
if self.info_requested(Info.fvalue) \
or self.info_requested(Info.func_val):
f_ = []
if self.info_requested(Info.gap):
gap_ = []
if self.info_requested(Info.converged):
self.info_set(Info.converged, False)
if self.info_requested(Info.mu):
mu_ = []
i = 0 # Iteration counter.
while loop:
# Current precision.
eps_mu = np.maximum(eps, self.eps) - mu * gM
# Set current parameters to algorithm.
algorithm.set_params(eps=eps_mu,
max_iter=self.max_iter - self.num_iter)
# Run FISTA.
beta = algorithm.run(function, beta)
# Update global iteration counter.
self.num_iter += algorithm.num_iter
# Get info from algorithm.
if Info.time in algorithm.info and \
self.info_requested(Info.time):
t_ += algorithm.info_get(Info.time)
if i == 0: # Add init time to first iteration.
t_[0] += init_time
if Info.func_val in algorithm.info and \
self.info_requested(Info.func_val):
f_ += algorithm.info_get(Info.func_val)
elif Info.fvalue in algorithm.info and \
self.info_requested(Info.fvalue):
f_ += algorithm.info_get(Info.fvalue)
if self.info_requested(Info.mu):
mu_ += [mu] * algorithm.num_iter
if self.info_requested(Info.gap):
gap_ += algorithm.info_get(Info.gap)
# Obtain the gap from the last FISTA run. May be small and negative
# close to machine epsilon.
gap_mu = np.abs(algorithm.info_get(Info.gap)[-1])
# TODO: Warn if gap_mu < -consts.TOLERANCE.
if not self.simulation:
converged = gap_mu + mu * gM < self.eps
if np.all(converged):
if self.info_requested(Info.converged):
self.info_set(Info.converged, converged)
if self.callback is not None:
self.callback(locals())
if self.info_requested(Info.verbose):
print("CONESTA ite:%i, gap_mu: %g, eps: %g, mu: %g, "
"eps_mu: %g" % (i, gap_mu, eps, mu, eps_mu))
# Stopping criteria.
if (np.all(converged) or self.num_iter >= self.max_iter) \
and self.num_iter >= self.min_iter:
break
# Update the precision eps.
# eps = self.tau * (gap_mu + mu * gM)
eps = np.maximum(self.eps, self.tau * (gap_mu + mu * gM))
# Compute and update mu.
# mu = max(self.mu_min, min(function.mu_opt(eps), mu))
mu = np.minimum(function.mu_opt(eps), mu)
function.set_mu(mu)
i = i + 1
if self.info_requested(Info.num_iter):
self.info_set(Info.num_iter, self.num_iter)
if self.info_requested(Info.continuations):
self.info_set(Info.continuations, i + 1)
if self.info_requested(Info.time):
self.info_set(Info.time, t_)
if self.info_requested(Info.func_val):
self.info_set(Info.func_val, f_)
if self.info_requested(Info.fvalue):
self.info_set(Info.fvalue, f_)
if self.info_requested(Info.gap):
self.info_set(Info.gap, gap_)
if self.info_requested(Info.mu):
self.info_set(Info.mu, mu_)
if self.info_requested(Info.ok):
self.info_set(Info.ok, True)
return beta
class StaticCONESTA(bases.ExplicitAlgorithm,
bases.IterativeAlgorithm,
bases.InformationAlgorithm):
"""COntinuation with NEsterov smoothing in a Soft-Thresholding Algorithm,
or CONESTA for short, with a statically decreasing sequence of eps and mu.
Parameters
----------
mu_min : float
Non-negative. A "very small" mu to use as a lower bound for mu.
tau : float
Within 0 < tau < 1. The rate at which eps is decreasing. Default is
0.5.
exponent : float
Within [1.001, 2.0]. The assumed convergence rate of
||beta* - beta_k||_2 for k=1,2,... is O(1 / k^exponent). Default is
1.5.
eps : float
Positive float. Tolerance for the stopping criterion.
info : List or tuple of utils.Info.
What, if any, extra run information should be stored. Default is an
empty list, which means that no run information is computed nor
returned.
max_iter : int
Non-negative integer. Maximum allowed number of iterations.
min_iter : int
Non-negative integer less than or equal to max_iter. Minimum number of
iterations that must be performed. Default is 1.
callback: Callable
A callable object that will be called at the end of each iteration with
locals() as arguments.
Example
-------
>>> from parsimony.algorithms.proximal import StaticCONESTA
>>> from parsimony.functions.nesterov import l1tv
>>> from parsimony.functions import LinearRegressionL1L2TV
>>> import scipy.sparse as sparse
>>> import numpy as np
>>>
>>> np.random.seed(42)
>>> X = np.random.rand(100, 50)
>>> y = np.random.rand(100, 1)
>>> A = sparse.csr_matrix((50, 50)) # Unused here
>>> function = LinearRegressionL1L2TV(X, y, 0.0, 0.0, 0.0,
... A=[A], mu=0.0)
>>> static_conesta = StaticCONESTA(max_iter=10000)
>>> beta1 = static_conesta.run(function, np.random.rand(50, 1))
>>> beta2 = np.dot(np.linalg.pinv(X), y)
>>> round(np.linalg.norm(beta1 - beta2), 13)
3.0183961e-06
>>>
>>> np.random.seed(42)
>>> X = np.random.rand(100, 50)
>>> y = np.random.rand(100, 1)
>>> A = sparse.csr_matrix((50, 50))
>>> function = LinearRegressionL1L2TV(X, y, 0.1, 0.0, 0.0,
... A=[A], mu=0.0)
>>> static_conesta = StaticCONESTA(max_iter=10000)
>>> beta1 = static_conesta.run(function, np.random.rand(50, 1))
>>> beta2 = np.dot(np.linalg.pinv(X), y)
>>> np.linalg.norm(beta1 - beta2) # doctest: +ELLIPSIS
0.82723295...
>>> int(np.linalg.norm(beta2.ravel(), 0))
50
>>> int(np.linalg.norm(beta1.ravel(), 0))
7
>>>
>>> np.random.seed(42)
>>> X = np.random.rand(100, 50)
>>> y = np.random.rand(100, 1)
>>> A = l1tv.linear_operator_from_shape((1, 1, 50), 50)
>>> function = LinearRegressionL1L2TV(X, y, 0.1, 0.1, 0.1,
... A=A, mu=0.0)
>>> static_conesta = StaticCONESTA(max_iter=10000)
>>> beta1 = static_conesta.run(function, np.zeros((50, 1)))
>>> beta2 = np.dot(np.linalg.pinv(X), y)
>>> np.linalg.norm(beta1 - beta2) # doctest: +ELLIPSIS
0.96629070...
"""
INTERFACES = [properties.NesterovFunction,
properties.StepSize,
properties.ProximalOperator,
properties.Continuation,
properties.DualFunction]
INFO_PROVIDED = [Info.ok,
Info.converged,
Info.num_iter,
Info.continuations,
Info.time,
Info.fvalue,
Info.func_val,
Info.mu,
Info.verbose]
def __init__(self, mu_min=consts.TOLERANCE, tau=0.5, exponent=1.52753,
info=[], eps=consts.TOLERANCE, max_iter=10000, min_iter=1,
callback=None,
simulation=False):
super(StaticCONESTA, self).__init__(info=info,
max_iter=max_iter,
min_iter=min_iter)
self.mu_min = max(consts.FLOAT_EPSILON, float(mu_min))
self.tau = max(consts.TOLERANCE,
min(float(tau), 1.0 - consts.TOLERANCE))
self.exponent = max(1.001, min(float(exponent), 2.0))
self.eps = max(consts.TOLERANCE, float(eps))
self.callback = callback
self.simulation = bool(simulation)
self._harmonic = None
def _harmonic_number_approx(self):
if self._harmonic is None:
x = [1.001, 1.00125, 1.0025, 1.005, 1.01, 1.025, 1.05, 1.075, 1.1,
1.2, 1.3, 1.4, 1.5, 1.52753, 1.6, 1.7, 1.8, 1.9, 1.95, 2.0]
y = [1000.58, 800.577, 400.577, 200.578, 100.578, 40.579, 20.5808,
13.916, 10.5844, 5.59158, 3.93195, 3.10555, 2.61238, 2.50988,
2.28577, 2.05429, 1.88223, 1.74975, 1.69443, 1.6449340668]
f = interp1(x, y)
self._harmonic = f(self.exponent)
return self._harmonic
def _approximate_eps(self, function, beta0):
old_mu = function.set_mu(self.mu_min)
step = function.step(beta0)
D1 = maths.norm(function.prox(-step * function.grad(beta0),
step,
# Arbitrary eps ...
eps=np.sqrt(consts.TOLERANCE),
max_iter=self.max_iter))
function.set_mu(old_mu)
return (2.0 / step) * D1 * self._harmonic_number_approx()
@bases.force_reset
@bases.check_compatibility
def run(self, function, beta):
# Copy the allowed info keys for FISTA.
fista_info = list()
for nfo in self.info_copy():
if nfo in FISTA.INFO_PROVIDED:
fista_info.append(nfo)
# Create the inner algorithm.
algorithm = FISTA(info=fista_info, eps=self.eps,
max_iter=self.max_iter, min_iter=self.min_iter)
# Not ok until the end.
if self.info_requested(Info.ok):
self.info_set(Info.ok, False)
# Time the init computation.
if self.info_requested(Info.time):
init_time = utils.time()
# Estimate the initial precision, eps, and the smoothing parameter mu.
gM = function.eps_max(1.0) # gamma * M
if maths.norm(beta) > consts.TOLERANCE:
mu = function.estimate_mu(beta)
eps = mu * gM
else:
eps = self._approximate_eps(function, beta)
mu = eps / gM
function.set_mu(mu)
# Initialise info variables. Info variables have the suffix "_".
if self.info_requested(Info.time):
t_ = []
init_time = utils.time() - init_time
if self.info_requested(Info.fvalue) \
or self.info_requested(Info.func_val):
f_ = []
if self.info_requested(Info.converged):
self.info_set(Info.converged, False)
if self.info_requested(Info.mu):
mu_ = []
i = 0 # Iteration counter.
while True:
converged = False
# Give current parameters to the algorithm.
algorithm.set_params(eps=eps,
max_iter=self.max_iter - self.num_iter)
# Run FISTA.
beta_new = algorithm.run(function, beta)
# Update global iteration count.
self.num_iter += algorithm.num_iter
# Get info from algorithm.
if Info.time in algorithm.info and \
self.info_requested(Info.time):
t_ += algorithm.info_get(Info.time)
if i == 0: # Add init time to first iteration.
t_[0] += init_time
if Info.func_val in algorithm.info \
and self.info_requested(Info.func_val):
f_ += algorithm.info_get(Info.func_val)
elif Info.fvalue in algorithm.info \
and self.info_requested(Info.fvalue):
f_ += algorithm.info_get(Info.fvalue)
if self.info_requested(Info.mu):
mu_ += [mu] * algorithm.num_iter
# Unless this is a simulation, you want the algorithm to stop when
# it has converged.
if not self.simulation:
# Stopping criterion.
step = function.step(beta_new)
if maths.norm(beta_new - beta) < step * self.eps:
if self.info_requested(Info.converged):
self.info_set(Info.converged, True)
converged = True
beta = beta_new
if self.callback is not None:
self.callback(locals())
if self.info_requested(Info.verbose):
print("StaticCONESTA ite: %i, eps: %g, mu: %g" % (i, eps, mu))
# All combined stopping criteria.
if (converged or self.num_iter >= self.max_iter) \
and self.num_iter >= self.min_iter:
break
# Update the precision eps.
eps = self.tau * eps
# Compute and update mu.
mu = max(self.mu_min, eps / gM)
function.set_mu(mu)
i = i + 1
if self.info_requested(Info.num_iter):
self.info_set(Info.num_iter, self.num_iter)
if self.info_requested(Info.continuations):
self.info_set(Info.continuations, i + 1)
if self.info_requested(Info.time):
self.info_set(Info.time, t_)
if self.info_requested(Info.func_val):
self.info_set(Info.func_val, f_)
if self.info_requested(Info.fvalue):
self.info_set(Info.fvalue, f_)
if self.info_requested(Info.mu):
self.info_set(Info.mu, mu_)
if self.info_requested(Info.ok):
self.info_set(Info.ok, True)
return beta
#class ProjectionADMM(bases.ExplicitAlgorithm):
# """ The Alternating direction method of multipliers, where the functions
# have projection operators onto the corresponding convex sets.
# """
# INTERFACES = [properties.Function,
# properties.ProjectionOperator]
#
# def __init__(self, output=False,
# eps=consts.TOLERANCE,
# max_iter=consts.MAX_ITER, min_iter=1):
#
# self.output = output
# self.eps = eps
# self.max_iter = max_iter
# self.min_iter = min_iter
#
# def run(self, function, x):
# """Finds the projection onto the intersection of two sets.
#
# Parameters
# ----------
# function : List or tuple with two Functions. The two functions.
#
# x : Numpy array. The point that we wish to project.
# """
# self.check_compatibility(function[0], self.INTERFACES)
# self.check_compatibility(function[1], self.INTERFACES)
#
# z = x
# u = np.zeros(x.shape)
# for i in xrange(1, self.max_iter + 1):
# x = function[0].proj(z - u)
# z = function[1].proj(x + u)
# u = u + x - z
#
# if maths.norm(z - x) / maths.norm(z) < self.eps \
# and i >= self.min_iter:
# break
#
# return z
class ADMM(bases.ExplicitAlgorithm,
bases.IterativeAlgorithm,
bases.InformationAlgorithm):
"""The alternating direction method of multipliers (ADMM). Computes the
minimum of the sum of two functions with associated proximal or projection
operators. Solves problems on the form
min. f(x, y) = g(x) + h(y)
s.t. y = x
The functions have associated proximal or projection operators.
Parameters
----------
rho : Positive float. The penalty parameter.
mu : Float, greater than 1. The factor within which the primal and dual
variables should be kept. Set to less than or equal to 1 if you
don't want to update the penalty parameter rho dynamically.
tau : Float, greater than 1. Increase rho by a factor tau.
info : List or tuple of utils.consts.Info. What, if any, extra run
information should be stored. Default is an empty list, which means
that no run information is computed nor returned.
eps : Positive float. Tolerance for the stopping criterion.
max_iter : Non-negative integer. Maximum allowed number of iterations.