-
Notifications
You must be signed in to change notification settings - Fork 2
/
lasso_regression_large.py
1574 lines (1121 loc) · 43 KB
/
lasso_regression_large.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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
from scipy.optimize import minimize_scalar, minimize
import datetime
import os
import networkx as nx
import pandas as pd
from gurobipy import*
from collections import Counter, defaultdict
from scipy.io import loadmat
from time import process_time
from matplotlib import ticker
import warnings
warnings.filterwarnings("ignore")
from autograd import grad as grad_a
from sklearn.preprocessing import StandardScaler
# # Oracles
# In[2]:
def line_search(x, d, gamma_max,func):
#line-search using Brent's rule in scipy
'''
Minimizes f over [x, y], i.e., f(x+gamma*d) as a function of scalar gamma in [0,gamma_max]
'''
def fun(gamma):
ls = x + gamma*d
return func(ls)
res = minimize_scalar(fun, bounds=(0, gamma_max), method='bounded')
gamma = res.x
ls = x + gamma*d
return ls, gamma
def segment_search(f, grad_f, x, y, tol=1e-6, stepsize=True):
#line-search using golden-section rule coded from scratch
'''
Minimizes f over [x, y], i.e., f(x+gamma*(y-x)) as a function of scalar gamma in [0,1]
'''
# restrict segment of search to [x, y]
d = (y-x).copy()
left, right = x.copy(), y.copy()
# if the minimum is at an endpoint
if np.dot(d, grad_f(x))*np.dot(d, grad_f(y)) >= 0:
if f(y) <= f(x):
return y, 1
else:
return x, 0
# apply golden-section method to segment
gold = (1+np.sqrt(5))/2
improv = np.inf
while improv > tol:
old_left, old_right = left, right
new = left+(right-left)/(1+gold)
probe = new+(right-new)/2
if f(probe) <= f(new):
left, right = new, right
else:
left, right = left, probe
improv = np.linalg.norm(f(right)-f(old_right))+np.linalg.norm(f(left)-f(old_left))
x_min = (left+right)/2
# compute step size gamma
gamma = 0
if stepsize == True:
for i in range(len(d)):
if d[i] != 0:
gamma = (x_min[i]-x[i])/d[i]
break
return x_min, gamma
def linear_oracle(A,b, c):
'''
General form LP solver that solves min c^Tx subject to Ax <= b
'''
m = Model("opt")
n = len(A.T)
#define variables
x = []
for i in range(n):
x.append(m.addVar(lb=-GRB.INFINITY, name='x_{}'.format(i)))
m.update()
objExp = np.dot(np.array(x),c)
m.setObjective(objExp, GRB.MINIMIZE)
m.update()
#feasibility constraints
for i in range(len(A)):
m.addConstr(np.dot(np.array(x),A[i]),'<=', b[i])
m.update()
#convex hull constraint
m.update()
#optimize
m.setParam( 'OutputFlag', False )
m.optimize()
return np.array([i.x for i in x])
def active_constraints_oracle(A,b,x):
'''
finding active constraints for polytope of the form Ax <= b
'''
b_prime = []
A_prime = []
A_not = []
b_not = []
for i in range(len(A)):
if np.abs(np.round(np.dot(A[i],x),4) - b[i]) < 0.01:
A_prime.append(list(A[i]))
b_prime.append(b[i])
else:
A_not.append(list(A[i]))
b_not.append(b[i])
return np.array(A_prime),np.array(b_prime),np.array(A_not),np.array(b_not)
def max_step_size(A,b,x, d):
'''
finding maximum step-size: argmax{\delta | x + \delta d \in P} where P is given by Ax <= b and d is a
feasible direction at x. Here we use Gurobi as a black box solver.
'''
m = Model("opt")
n = len(A.T)
lam = m.addVar(lb=-GRB.INFINITY, name='lam')
m.update()
objExp = lam
m.setObjective(objExp, GRB.MAXIMIZE)
m.update()
#feasibility constraints
for i in range(len(A)):
m.addConstr(np.dot(np.array(x),A[i]) + lam* np.dot(np.array(d),A[i]),'<=', b[i])
m.update()
#optimize
m.setParam( 'OutputFlag', False )
m.optimize()
return lam.x
def max_step_size_search(A,b,x, d):
'''
finding maximum step-size: argmax{\delta | x + \delta d \in P} where P is given by Ax <= b and d is a
feasible direction at x. Here we search over set of inactive constraints that might get violated.
'''
A_J,b_J = active_constraints_oracle(A,b,x)[2:]
slack = b_J - np.dot(A_J,x)
try:
if len(d) > 1:
denom = np.dot(A_J,d)
excess = [slack[i]/denom[i] for i in range(len(slack)) if denom[i] > 0]
gamma_max = min(excess)
return gamma_max
except:
return min(slack)
def shadow_oracle(A,b,x, d):
'''
Projecting d on set of feasible directions for polytope given by Ax <= b
'''
#find matrix of active constraints
A_I = active_constraints_oracle(A,b,x)[0]
m = Model("opt")
n = len(A_I.T)
z = []
for i in range(n):
z.append(m.addVar(lb=-GRB.INFINITY, name='z_{}'.format(i)))
m.update()
objExp = quicksum(np.square(np.array([d[k] -z[k] for k in range(n)])))
m.setObjective(objExp, GRB.MINIMIZE)
m.update()
#feasibility constraints
for i in range(len(A_I)):
m.addConstr(np.dot(np.array(z),A_I[i]),'<=', 0)
m.update()
#optimize
m.setParam( 'OutputFlag', False )
m.optimize()
der = [i.x for i in z]
return np.array(der)
def shadow_oracle_other(A,b,x, grad,M,vert_rep,vertices):
'''
Computing projection if we know an upper bound M on the value at which normal cone is not changing
'''
epsilon = M/2
if vert_rep == True:
g = projection_oracle_vertices(vertices,x - epsilon*grad)
der = (g -x)/epsilon
else:
projection_oracle(x - epsilon*grad,A,b)
der = (g -x)/epsilon
return der
return np.array(der)
def project_Null(A,d):
'''
Function to project the direction d onto the nullspace of matrix A
'''
if len(A) > 1:
return np.dot(np.eye(len(A.T)) - np.matmul(A.T,np.matmul(np.linalg.pinv(np.matmul(A,A.T)),A)),d)
else:
A = A[0]
return d - np.dot(A,d)*A/np.dot(A,A)
def in_face_shadow_oracle (A,b,x,d):
'''
Function to compute in-face shadow, i.e. project the direction d onto minimal face of x for polytope given by Ax <= b
'''
A_I = active_constraints_oracle(A,b,x)[0]
d_hat = project_Null(A_I,d)
return d_hat
def in_face_shadow_oracle_other(A,b,x, d):
'''
Function to compute in-face shadow, i.e. project the direction d onto minimal face of x for polytope given by Ax <= b
'''
#find matrix of active constraints
A_I = active_constraints_oracle(A,b,x)[0]
m = Model("opt")
n = len(A_I.T)
z = []
for i in range(n):
z.append(m.addVar(lb=-GRB.INFINITY, name='z_{}'.format(i)))
m.update()
objExp = quicksum(np.square(np.array([d[k] -z[k] for k in range(n)])))
m.setObjective(objExp, GRB.MINIMIZE)
m.update()
#feasibility constraints
for i in range(len(A_I)):
m.addConstr(np.dot(np.array(z),A_I[i]),'==', 0)
m.update()
#optimize
m.setParam( 'OutputFlag', False )
m.optimize()
der = [i.x for i in z]
return np.array(der)
def find_lam_hat(A_I, x_0,x,d,d_hat,gamma_total):
'''
Function to compute the maximum movement along the in-face shadow using a linear program
'''
m = Model("opt")
n = len(A_I.T)
#define variables
lam = m.addVar(name='lam')
#define variables
mu = []
for i in range(len(A_I)):
mu.append(m.addVar(lb=0, name='mu_{}'.format(i)))
m.update()
m.setObjective(lam, GRB.MAXIMIZE)
m.update()
#feasibility constraints
for i in range(n):
m.addConstr(np.dot(np.array(mu),A_I.T[i]),'==', x_0[i] + lam*d[i] - x[i] -(lam - gamma_total)*d_hat[i])
m.update()
m.setParam( 'OutputFlag', False )
m.setParam( 'DualReductions', 0)
#optimize
m.optimize()
if m.status == GRB.INFEASIBLE:
return 0
else:
return lam.x - gamma_total
def trace_in_face(A,b,x_0,x,d,d_hat, gamma_total, lmo):
'''
Function to run the trace-in-face procedure
'''
A_I = active_constraints_oracle(A,b,x)[0]
#line-search along d_hat
if all(np.round(d_hat,6) != 0):
gamma_max = max_step_size_search(A,b,x, d_hat)
#check weather this optimal by checking first order optimality
normal = x_0 + (gamma_max +gamma_total)*d - x - gamma_max*d_hat
if np.dot(normal, LO(-normal) - x - gamma_max*d_hat) <= 0:
lam_hat = gamma_max
else: #if not solve Lp to find max step size where normal cone does not change
lam_hat = find_lam_hat(A_I, x_0,x,d,d_hat,gamma_total)
else:
lam_hat = find_lam_hat(A_I, x_0,x,d,d_hat,gamma_total)
return lam_hat
# # Algorithms - FW Variants
# # FW
# In[3]:
def FW(x, lmo, epsilon,func,grad_f, f_tol, time_tol):
#record primal gap, function value, and time every iteration
now=datetime.datetime.now()
primal_gap = []
function_value=[func(x)]
time = [0]
f_improv = np.inf
#initialize iteration count
t = 0
while f_improv > f_tol and time[-1] < time_tol:
start = process_time()
#compute gradient
grad = grad_f(x)
#solve linear subproblem and compute FW direction
v = lmo(grad)
d_FW = v-x
#If primal gap is small enough - terminate
if np.dot(-grad,d_FW) <= epsilon:
break
else:
#update convergence data
primal_gap.append(np.dot(-grad,d_FW))
#Update next iterate by doing a feasible line-search
x, gamma = segment_search(func, grad_f, x, v)
end = process_time()
time.append(time[t] + end - start)
f_improv = function_value[-1] - func(x)
function_value.append(func(x))
t+=1
return x, function_value, time,t,primal_gap
# # AFW
# In[4]:
#Function to compute away vertex
def away_step(grad, S):
'''
Compute away vertex by searching over current active set
'''
costs = {}
for k,v in S.items():
cost = np.dot(k,grad)
costs[cost] = [k,v]
vertex, alpha = costs[max(costs.keys())]
return vertex,alpha
#Function to update active set
def update_S(S,gamma, Away, vertex):
'''
Update convex decompistion of active step after every iteration
'''
S = S.copy()
vertex = tuple(vertex)
if not Away:
if vertex not in S.keys():
S[vertex] = gamma
else:
S[vertex] *= (1-gamma)
S[vertex] += gamma
for k in S.keys():
if k != vertex:
S[k] *= (1-gamma)
else:
for k in S.keys():
if k != vertex:
S[k] *= (1+gamma)
else:
S[k] *= (1+gamma)
S[k] -= gamma
return {k:v for k,v in S.items() if np.round(v,3) > 0}
#AFW Algorithm
def AFW(x, lmo, epsilon,func,grad_f, f_tol, time_tol):
#record primal gap, function value, and time every iteration
now=datetime.datetime.now()
primal_gap = []
function_value=[func(x)]
time = [0]
f_improv = np.inf
#initialize starting point and active set
t = 0
S={tuple(x): 1}
while f_improv > f_tol and time[-1] < time_tol:
start = process_time()
#compute gradient
grad = grad_f(x)
#solve linear subproblem and compute FW direction
v = lmo(grad)
d_FW = v-x
#If primal gap is small enough - terminate
if np.dot(-grad,d_FW) <= epsilon:
break
else:
#update convergence data
primal_gap.append(np.dot(-grad,d_FW))
#Compute away vertex and direction
a,alpha_a = away_step(grad, S)
d_A = x - a
#Check if FW gap is greater than away gap
if np.dot(-grad,d_FW) >= np.dot(-grad,d_A):
#choose FW direction
d = d_FW
vertex = v
gamma_max = 1
Away = False
else:
#choose Away direction
d = d_A
vertex = a
gamma_max = alpha_a/(1-alpha_a)
Away = True
#Update next iterate by doing a feasible line-search
x, gamma = segment_search(func, grad_f, x, x + gamma_max *d)
#update active set based on direction chosen
S = update_S(S,gamma, Away, vertex)
end = process_time()
time.append(time[t] + end - start)
f_improv = function_value[-1] - func(x)
function_value.append(func(x))
t+=1
return x, function_value, time,t,primal_gap
# # Pairwise FW
# In[5]:
def update_S_PW(S,gamma, FW_vertex, Away_vertex):
'''
Update convex decompistion of active step after pairwise direction is chosen
'''
vertex1 = tuple(FW_vertex)
vertex2 = tuple(Away_vertex)
S = S.copy()
if vertex1 not in S.keys():
S[vertex1] = gamma
else:
S[vertex1] += gamma
S[vertex2] -= gamma
return {k:v for k,v in S.items() if np.round(v,4) > 0}
#PFW Algorithm
def PFW(x, lmo, epsilon,func,grad_f, f_tol, time_tol):
#record primal gap, function value, and time every iteration
primal_gap = []
function_value=[func(x)]
time = [0]
f_improv = np.inf
#initialize starting point and active set
t = 0
S={tuple(x): 1}
while f_improv > f_tol and time[-1] < time_tol:
start = process_time()
#compute gradient
grad = grad_f(x)
#solve linear subproblem and compute FW direction
v = lmo(grad)
d_FW = v-x
#If primal gap is small enough - terminate
if np.dot(-grad,d_FW) <= epsilon:
break
else:
#update convergence data
primal_gap.append(np.dot(-grad,d_FW))
#Compute away vertex and direction
a,alpha_a = away_step(grad, S)
d_A = x - a
#Pairwise step
d = d_FW + d_A
gamma_max = alpha_a
#Update next iterate by doing a feasible line-search
x, gamma = line_search(x, d, gamma_max,func)
#update active set
S = update_S_PW(S,gamma, v, a)
end = process_time()
time.append(time[t] + end - start)
f_improv = function_value[-1] - func(x)
function_value.append(func(x))
t+=1
return x, function_value, time,t,primal_gap
# # Decoposition Invaraint FW (DICG)
# In[6]:
#DICG algorithm
def DICG(x, lmo, feasibility_oracle, epsilon,func,grad_f, f_tol, time_tol):
#record primal gap, function value, and time every iteration
primal_gap = []
function_value=[func(x)]
time = [0]
f_improv = np.inf
#initialize starting point and active set
t = 0
while f_improv > f_tol and time[-1] < time_tol:
start = process_time()
#compute gradient
grad = grad_f(x)
#solve linear subproblem and compute FW direction
v = lmo(grad)
d_FW = v-x
#If primal gap is small enough - terminate
if np.dot(-grad,d_FW) <= epsilon:
break
else:
#update convergence data
primal_gap.append(np.dot(-grad,d_FW))
#create new gradient to find best away vertex
g = np.array([grad[i] if x[i] > 0 else -9e9 for i in range(len(x))])
a = lmo(-g)
d_A = x - a
#Pairwise step
d = d_FW + d_A
gamma_max = feasibility_oracle(x,d)
#Update next iterate by doing a feasible line-search
x, gamma = segment_search(func, grad_f, x, x+gamma_max*d)
end = process_time()
time.append(time[t] + end - start)
f_improv = function_value[-1] - func(x)
function_value.append(func(x))
t+=1
return x, function_value, time,t,primal_gap
# # Projected Gradient variants
# # Shadow Walk
# In[85]:
def trace_PW_curve_app(x,grad,shadow,feasibility_oracle,func):
'''
trace the piecewise linear projection curve approximately by only taking shadow steps
'''
count_in_face = 0
count_shadow = 0
t_all = 0
t_all_but_in_face = 0
t_shadow = 0
t_lam = 0
t_none = 0
gamma_total = 0
d_pi = shadow(x,-grad)
while np.dot(d_pi,d_pi)**0.5 > 0.00001:
t1 = process_time()
t2,t3,t4,t5 = 0,0,0,0
# only take shadow steps
count_shadow +=1
gamma_max = feasibility_oracle(x, d_pi)
x, gamma = segment_search(func, grad_f, x, x + gamma_max *d_pi)
#update total step-size accrued and shadow
gamma_total += gamma*gamma_max
#break if sufficient progress
if abs(gamma - 1) > 0.001:
t6,t7 = 0,0
break
else:
t6 = process_time()
d_pi = shadow(x,-grad)
t7 = process_time()
t8 = process_time()
t_all += t8 - t1 - (t3 - t2) - (t5 - t4) - (t7 - t6)
t_all_but_in_face += t8 - t1 - (t5 - t4) - (t7 - t6)
t_none += t8 - t1
t_shadow += t8 - t1 - (t5 - t4)
t_lam += t8 - t1 - (t7 - t6)
print(func(x))
return x,count_in_face,count_shadow,(t_none, t_lam, t_shadow, t_all_but_in_face, t_all),d_pi
def trace_PW_curve(x,grad,shadow,in_face_shadow,in_face_trace,feasibility_oracle,func,grad_f):
'''
trace the piecewise linear projection curve
'''
count_in_face = 0
count_shadow = 0
t_all = 0
t_all_but_in_face = 0
t_shadow = 0
t_lam = 0
t_none = 0
gamma_total = 0
d_pi = shadow(x,-grad)
x_0 = x.copy()
while np.dot(d_pi,d_pi)**0.5 > 1e-6:
t1 = process_time()
#print(np.dot(x_0 - gamma_total*grad - x,d_pi),func(x))
if abs(np.dot(x_0 - gamma_total*grad - x,d_pi)) > 1e-6:
#in-face step
t2 = process_time()
d_hat = in_face_shadow(x,-grad)
t3 = process_time()
count_in_face +=1
t4 = process_time()
gamma_max = in_face_trace(x_0,x,-grad, gamma_total,d_hat)
if np.round(gamma_max,4) > 0:
t5 = process_time()
if all(np.round(d_hat,6) == 0):
gamma = 1
else:
x, gamma = segment_search(func, grad_f, x, x + gamma_max *d_hat)
else:
t2,t3,t4,t5 = 0,0,0,0
#shadow step
count_shadow +=1
gamma_max = feasibility_oracle(x, d_pi)
x, gamma = segment_search(func, grad_f, x, x + gamma_max*d_pi)
else:
t2,t3,t4,t5 = 0,0,0,0
#shadow step
count_shadow +=1
gamma_max = feasibility_oracle(x, d_pi)
x, gamma = segment_search(func, grad_f, x, x + gamma_max*d_pi)
#update total step-size accrued and shadow
gamma_total += gamma*gamma_max
#break if sufficient progress
if abs(gamma - 1) > 0.001:
t6,t7 = 0,0
break
else:
t6 = process_time()
d_pi = shadow(x,-grad)
t7 = process_time()
t8 = process_time()
t_all += t8 - t1 - (t3 - t2) - (t5 - t4) - (t7 - t6)
t_all_but_in_face += t8 - t1 - (t5 - t4) - (t7 - t6)
t_none += t8 - t1
t_shadow += t8 - t1 - (t5 - t4)
t_lam += t8 - t1 - (t7 - t6)
return x,count_in_face,count_shadow,(t_none, t_lam, t_shadow, t_all_but_in_face, t_all),d_pi
#shadow descent algorithm:
def SD(x, lmo, shadow,in_face_shadow,in_face_trace, feasibility_oracle, epsilon,func,grad_f, f_tol, time_tol,tol,shadow_tol=1e-6):
#record primal gap, function value, and time every iteration
primal_gap = []
function_value=[func(x)]
time1 = [0]
time2 = [0]
f_improv = np.inf
counts_shadow = []
counts_in_face = []
#initialize starting point and active set
t = 0
while f_improv > f_tol and time1[-1] < time_tol:
start = process_time()
#compute gradient
grad = grad_f(x)
#solve linear subproblem and compute FW direction
s = lmo(grad)
d_FW = s-x
#If primal gap is small enough - terminate
if np.dot(-grad,d_FW) <= epsilon:
break
else:
#update convergence data
primal_gap.append(np.dot(-grad,d_FW))
end = process_time()
x, c1,c2, t_pw,d_pi = trace_PW_curve(x,grad,shadow,in_face_shadow,in_face_trace,feasibility_oracle,func,grad_f)
#x, c1,c2, t_pw,d_pi = trace_PW_curve_app(x,grad,shadow,feasibility_oracle,func)
if np.dot(d_pi,d_pi)**0.5 < shadow_tol:
break
else:
counts_in_face.append(c1)
counts_shadow.append(c2)
time1.append(time1[t] + end - start + t_pw[0])
time2.append( time2[t] + end - start + t_pw[-2])
f_improv = function_value[-1] - func(x)
function_value.append(func(x))
t+=1
#print(func(x))
return x, function_value, time1,time2,t,primal_gap,counts_shadow,counts_in_face
# # Shadow CG
# In[38]:
#shadow conditional gradients
def SCG(x, lmo, shadow,in_face_shadow,in_face_trace, feasibility_oracle, epsilon,func,grad_f, f_tol, time_tol,tol,shadow_tol=1e-6):
#record primal gap, function value, and time every iteration
primal_gap = []
function_value=[func(x)]
time1 = [0]
time2 = [0]
f_improv = np.inf
counts_shadow = []
counts_in_face = []
FW = []
#initialize starting point and active set
t = 0
while f_improv > f_tol and time1[-1] < time_tol:
t1 = process_time()
#compute gradient
grad = grad_f(x)
#solve linear subproblem and compute FW direction
v = lmo(grad)
d_FW = v-x
#If primal gap is small enough - terminate
if np.dot(-grad,d_FW) <= epsilon:
break
else:
#update convergence data
primal_gap.append(np.dot(-grad,d_FW))
#Compute directional derivative
t2 = process_time()
d_pi = shadow(x,-grad)
t3 = process_time()
#Check if FW gap direction is better than normalized shadow
if np.dot(-grad,d_FW) >= np.dot(-grad,d_pi/(np.dot(d_pi,d_pi)**0.5)):
t4 = process_time()
#choose FW direction
gamma_max = 1
x, gamma = segment_search(func, grad_f, x, x + gamma_max*d_FW)
FW.append(1)
counts_in_face.append(0)
counts_shadow.append(1)
t5,t_pw = process_time(),[0]*5
else:
#trace the projections curve
x, c1,c2, t_pw,d_pi = trace_PW_curve(x,grad,shadow,in_face_shadow,in_face_trace,feasibility_oracle,func,grad_f)
#x, c1,c2, t_pw,d_pi = trace_PW_curve_app(x,grad,shadow,feasibility_oracle,func)
FW.append(0)
counts_in_face.append(c1)
counts_shadow.append(c2)
t4,t5 = 0,0
if np.dot(d_pi,d_pi)**0.5 < shadow_tol:
break
else:
time1.append(time1[t] + (t3 - t1) + (t5-t4) + t_pw[0])
time2.append(time2[t] + (t2 - t1) + (t5-t4) + t_pw[-2])
f_improv = function_value[-1] - func(x)
function_value.append(func(x))
t+=1
#print(func(x))
return x, function_value, time1,time2,t,primal_gap,counts_shadow,counts_in_face,FW
# # PGD
# In[26]:
# PDG algorithm:
def PGD(x, lmo,proj,L, epsilon,func,grad_f, f_tol, time_tol):
#record primal gap, function value, and time every iteration
now=datetime.datetime.now()
primal_gap = []
function_value=[func(x)]
time = [0]
f_improv = np.inf
counts = []
#initialize starting point and active set
t = 0
while f_improv > f_tol and time[-1] < time_tol:
#compute gradient
grad = grad_f(x)