-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexamples.py
560 lines (454 loc) · 17.6 KB
/
examples.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
"""Some examples of using the functions im optimize.py"""
import numpy as np; np.seterr(all='raise')
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.linalg import solve
from optimize import steepest_descent, backtracking_line_search,\
AdaptiveLineSearch
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
def example_gradient_descent001():
"""Compute the analytic center of a randomly generated
polyhedra in dimension n, subject to the additional constraint
that x_i \in [-1, 1] for each i"""
# ---------------Generate some problem data-----------------
m, n = 1050, 450 # (number of hyperplanes), (dimension)
A = np.random.normal(size=(m, n))
b = np.random.gamma(shape=3.0, size=(m,)) # b > 0 ensures feasibility
x0 = np.zeros(n)
assert np.all(np.dot(A, x0) < b)
# ---------------Some helper functions----------------------
def _psi(x):
'''-log(1 + x) - log(1 - x)'''
if np.any(np.abs(x) > 1):
return np.inf
else:
return -(np.log1p(x) + np.log1p(-x))
def _phi(x):
'''-log(-x)'''
if np.any(x > 0):
return np.inf
else:
return -np.sum(np.log(-x))
def _grad_phi(x):
return -1. / x
# ------------- the actual functions we need to do gradient descent -------
def f(x): # The function to minimize
return np.sum(_psi(x)) + _phi(np.dot(A, x) - b)
# The gradient of f
def grad_f(x):
return (1 / (1 - x)) - (1 / (1 + x)) + np.dot(A.T, _grad_phi(
np.dot(A, x) - b))
# The descent direction for gradient descent
def f_dd(x):
return -grad_f(x)
def stopping_criteria_closure(eps=1e-5):
check_count, check_max = 0, 10
def stopping_criteria(x):
nonlocal check_count
check_count += 1
if check_count >= check_max:
check_count = 0
if np.linalg.norm(grad_f(x), ord=np.inf) < eps:
return True
return False
return stopping_criteria
def line_search_closure():
ASL = AdaptiveLineSearch(grad_f)
def line_search(x, x_dd):
# Pre compute Ax and Ax_dd
Ax = np.dot(A, x)
Ax_dd = np.dot(A, x_dd)
# Create a function to evaluate f(x + tx_dd) efficiently
def g(t):
return np.sum(_psi(x + t * x_dd)) + _phi(Ax + t * Ax_dd - b)
# Return the step size from the line search
return ASL.line_search(x, x_dd, g)
return line_search
# Store the execution history of the function for plotting
def callback_closure():
fx_list = []
grad_fx_list = []
def callback(x, n, x_dd, ss):
nonlocal grad_fx_list
nonlocal fx_list
grad_fx_list.append(np.linalg.norm(grad_f(x), ord=np.inf))
fx_list.append(f(x))
return
return callback, grad_fx_list, fx_list
fig, axes = plt.subplots(2, 1, sharex=True)
fig.suptitle('Gradient Descent for Polyhedron Analytic Centering')
ax_grad, ax_f = axes
ax_grad.set_ylabel(r'$||\nabla f(x^{(n)})||_\infty$')
ax_grad.set_title(r'$n = %d$ dimensions, $m = %d$ hyperplanes'
% (n, m))
ax_grad.set_yscale('log')
ax_grad.grid()
ax_f.set_ylabel(r'$f(x^{(n)}) - p^\star$')
ax_f.set_xlabel('iteration count $n$')
ax_f.set_yscale('log')
ax_f.grid()
for i, eps in enumerate([1e-7, 1e-6, 1e-3, 1e-1]):
line_search = line_search_closure()
callback, grad_fx_list, fx_list = callback_closure()
stopping_criteria = stopping_criteria_closure(eps)
# Call the optimizer
x_star, n_iter, success = steepest_descent(x0, f_dd,
stopping_criteria,
line_search,
maxiter=2000,
callback=callback)
if i == 0:
p_star = fx_list[-1]
# Plot the results
ax_grad.plot(grad_fx_list, linewidth=2,
label=r'$\epsilon = %.2E$' % eps)
ax_f.plot(np.array(fx_list[:-1]) - p_star,
linewidth=2, label=r'$\epsilon = %.2E$' % eps)
ax_grad.legend()
ax_f.legend()
fig.savefig('./images/analytic_center_gradient_descent.png')
plt.show()
return
def example_newton001():
"""Compute the analytic center of a randomly generated
polyhedra in dimension n, subject to the additional constraint
that x_i \in [-1, 1] for each i"""
# ---------------Generate some problem data-----------------
m, n = 1050, 550 # (number of hyperplanes), (dimension)
A = np.random.normal(size=(m, n))
b = np.random.gamma(shape=3.0, size=(m,)) # b > 0 ensures feasibility
x0 = np.zeros(n)
assert np.all(np.dot(A, x0) < b) # {x | Ax < b} is the polyhedron
# ---------------Some helper functions----------------------
def _psi(x):
'''-log(1 + x) - log(1 - x)'''
if np.any(np.abs(x) > 1):
return np.inf
else:
return -(np.log1p(x) + np.log1p(-x))
def _psi_pp(x):
'''2nd derivative of _psi'''
return (1 / (1 - x**2))**2 # This could be bad for numerical precision
def _phi(x):
'''-log(-x)'''
if np.any(x > 0):
return np.inf
else:
return -np.sum(np.log(-x))
def _grad_phi(x):
# The gradient is undefined when x = 0 and rightfully throws an error
return -1. / x
# ------------- the actual functions we need to do gradient descent -------
def f(x): # The function to minimize
return np.sum(_psi(x)) + _phi(np.dot(A, x) - b)
# The gradient of f
def grad_f(x):
return (1 / (1 - x)) - (1 / (1 + x)) + np.dot(A.T, _grad_phi(
np.dot(A, x) - b))
# The Hessian of f -- This is NOT Lipschitz near x = 1, and hence we
# should not necessarily expect quadratic convergence.
def hess_f(x):
H = _grad_phi(np.dot(A, x) - b)**2 # Hessian of Phi
HA = H[:, None] * A
ATHA = np.dot(A.T, HA)
dg = np.arange(ATHA.shape[0])
ATHA[dg, dg] += (1 / (1 - x**2))**2
return ATHA
def fdd_stopping_closure(eps=1e-5):
x_dd = x0
g = grad_f(x0)
# The descent direction for Newton's method
def f_dd(x):
nonlocal x_dd, g
g = grad_f(x)
H = hess_f(x)
x_dd = solve(H, -g, sym_pos=True, check_finite=False)
return x_dd
def stopping_criteria(x):
lmbda = 0.5 * np.dot(g, -x_dd)**0.5 # Newton decrement
if lmbda <= eps:
return True
return False
return f_dd, stopping_criteria
def line_search_closure():
ASL = AdaptiveLineSearch(grad_f, beta0=0.8)
undamped = False
def line_search(x, x_dd):
# Pre compute Ax and Ax_dd
nonlocal undamped
if not undamped:
Ax = np.dot(A, x)
Ax_dd = np.dot(A, x_dd)
# Create a function to evaluate f(x + tx_dd) efficiently
def g(t):
return np.sum(_psi(x + t * x_dd)) +\
_phi(Ax + t * Ax_dd - b)
# Return the step size from the line search
t = ASL.line_search(x, x_dd, g)
return t
return line_search
# Store the execution history of the function for plotting
def callback_closure():
fx_list = []
lmbda_list = []
def callback(x, n, x_dd, ss):
nonlocal lmbda_list
nonlocal fx_list
lmbda_list.append(0.5 * np.dot(grad_f(x), -x_dd)**0.5)
fx_list.append(f(x))
return
return callback, lmbda_list, fx_list
fig, axes = plt.subplots(2, 1, sharex=True)
fig.suptitle("Newton's method for Polyhedron Analytic Centering")
ax_lmbda, ax_f = axes
ax_lmbda.set_title(r'$n = %d$ dimensions, $m = %d$ hyperplanes'
% (n, m))
ax_lmbda.set_ylabel(r'$\lambda(x) / 2$')
ax_lmbda.set_yscale('log')
ax_lmbda.grid()
ax_f.set_ylabel(r'$f(x^{(n)}) - p^\star$')
ax_f.set_xlabel('iteration count $n$')
ax_f.set_yscale('log')
ax_f.grid()
for i, eps in enumerate([1e-12, 1e-9, 1e-6, 1e-3, 1e-1]):
line_search = line_search_closure()
callback, lmbda_list, fx_list = callback_closure()
f_dd, stopping_criteria = fdd_stopping_closure(eps)
# Call the optimizer
x_star, n_iter, success = steepest_descent(x0, f_dd,
stopping_criteria,
line_search,
maxiter=50,
callback=callback)
if i == 0:
p_star = fx_list[-1]
# Plot the results
ax_lmbda.plot(lmbda_list[:-1], linewidth=2,
label=r'$\epsilon = %.2E$' % eps)
ax_f.plot(np.array(fx_list[:-1]) - p_star,
linewidth=2, label=r'$\epsilon = %.2E$' % eps)
ax_lmbda.legend()
ax_f.legend()
fig.savefig('./images/analytic_center_newton.png')
plt.show()
return
def example_newton002():
"""
Minimize f(x) = <c, x> + sum_j log(b_j - <a_j, x>) + sum_i(x_i),
Which is a log barrier with a linear objective.
"""
# ---------------Generate some problem data-----------------
m, n = 750, 800 # (number of hyperplanes), (dimension)
A = np.random.normal(size=(m, n))
b = np.random.gamma(shape=3.0, size=(m,)) # b > 0 ensures feasibility
c = np.random.gamma(shape=3.0, size=(n,)) # c > 0 ensures boundedness
x0 = np.zeros(n)
assert np.all(np.dot(A, x0) < b) # {x | Ax < b} is the polyhedron
# ---------------Some helper functions----------------------
def _phi(x):
'''-log(1 + x)'''
if any(x < -1):
return np.inf
else:
return -np.sum(np.log1p(x))
def _psi(x):
'''-log(-x)'''
if np.any(x > 0):
return np.inf
else:
return -np.sum(np.log(-x))
def _grad_psi(x):
# The gradient is undefined when x = 0 and rightfully throws an error
return -1. / x
def _grad_phi(x):
return -1. / (1 + x)
# ------------- the actual functions we need to do gradient descent -------
def f(x): # The function to minimize
return np.dot(c, x) + _phi(x) + _psi(np.dot(A, x) - b)
# The gradient of f
def grad_f(x):
return c + _grad_phi(x) + np.dot(A.T, _grad_psi(np.dot(A, x) - b))
def hess_f(x):
# H is diagonal and is returned as a vector only
D = _grad_psi(np.dot(A, x) - b)**2
HA = D[:, None] * A
ATHA = np.dot(A.T, HA)
dg = np.arange(ATHA.shape[0])
ATHA[dg, dg] = ATHA[dg, dg] + _grad_phi(x)**2
return ATHA
def fdd_stopping_closure(eps=1e-5):
x_dd = x0
g = grad_f(x0)
# The descent direction for Newton's method
def f_dd(x):
nonlocal x_dd, g
g = grad_f(x)
H = hess_f(x)
x_dd = solve(H, -g, sym_pos=True, check_finite=False)
return x_dd
def stopping_criteria(x):
lmbda = 0.5 * np.dot(g, -x_dd)**0.5 # Newton decrement
if lmbda <= eps:
return True
return False
return f_dd, stopping_criteria
def line_search_closure():
ASL = AdaptiveLineSearch(grad_f, beta0=0.8)
undamped = False
def line_search(x, x_dd):
# Pre compute Ax and Ax_dd
nonlocal undamped
if not undamped:
Ax = np.dot(A, x)
Ax_dd = np.dot(A, x_dd)
cx = np.dot(c, x)
cx_dd = np.dot(c, x_dd)
# Create a function to evaluate f(x + tx_dd) efficiently
def g(t):
return (cx + t * cx_dd) +\
_phi(x + t * x_dd) +\
_psi(Ax + t * Ax_dd - b)
# Return the step size from the line search
t = ASL.line_search(x, x_dd, g)
return t
return line_search
# Store the execution history of the function for plotting
def callback_closure():
fx_list = []
lmbda_list = []
def callback(x, n, x_dd, ss):
nonlocal lmbda_list
nonlocal fx_list
lmbda_list.append(0.5 * np.dot(grad_f(x), -x_dd)**0.5)
fx_list.append(f(x))
return
return callback, lmbda_list, fx_list
fig, axes = plt.subplots(2, 1, sharex=True)
fig.suptitle("Newton's method for barrier LP")
ax_lmbda, ax_f = axes
ax_lmbda.set_title(r'$n = %d$ dimensions, $m = %d$ hyperplanes'
% (n, m))
ax_lmbda.set_ylabel(r'$\lambda(x) / 2$')
ax_lmbda.set_yscale('log')
ax_lmbda.grid()
ax_f.set_ylabel(r'$f(x^{(n)}) - p^\star$')
ax_f.set_xlabel('iteration count $n$')
ax_f.set_yscale('log')
ax_f.grid()
for i, eps in enumerate([1e-12, 1e-7, 1e-6, 1e-3, 1e-1]):
line_search = line_search_closure()
callback, lmbda_list, fx_list = callback_closure()
f_dd, stopping_criteria = fdd_stopping_closure(eps)
# Call the optimizer
x_star, n_iter, success = steepest_descent(x0, f_dd,
stopping_criteria,
line_search,
maxiter=50,
callback=callback)
if i == 0:
p_star = fx_list[-1]
# Plot the results
ax_lmbda.plot(lmbda_list[:-1], linewidth=2,
label=r'$\epsilon = %.2E$' % eps)
ax_f.plot(np.array(fx_list[:-1]) - p_star,
linewidth=2, label=r'$\epsilon = %.2E$' % eps)
ax_lmbda.legend()
ax_f.legend()
fig.savefig('./images/LP_barrier.png')
plt.show()
return
def example_smooth_huber():
'''
Robust regression with a smoothed approximation to the Huber
loss function:
h_d(a) = d**2 * [sqrt(1 + (a / d)**2) - 1]
We can do robust regression with just an unconstrained minimization
algorithm.
The data generating model is y = <X, beta> + n + ot
where n ~ Normal, ot ~ Pareto.
'''
N = 100 # Number of data samples
m = 3 # number of regression coefficients (polynomial degree)
# Smooth function y = f(x)
def y_curve(beta, X):
y = np.dot(X, beta)
return y
# Noisy data generator
def y_data(beta):
# Data generator y = Xb + n + ot
# x ~ U; X = [x, x**2, ..., x**m]
# n ~ N # Well behaved noise
# ot ~ pareto # Fat tailed noise
# x = np.random.normal(size=N)
x = np.random.uniform(-3, 3, size=N)
X = np.hstack((x[:, None]**k for k in range(1, m + 1)))
y = (y_curve(beta, X) +
np.random.normal(loc=0.0, scale=np.sqrt(15), size=N) +
3 * np.random.pareto(a=1.1, size=N))
return X, y
# Generate some data
beta_true = [1.3, -2.4, 2.1]
X, y = y_data(beta_true)
def huber(u, d):
return d**2 * (np.sqrt(1 + (u / d)**2) - 1)
def grad_huber(u, d):
return u / np.sqrt(1 + (u / d)**2)
def psi(w, d):
return np.sum(huber(w, d))
def grad_psi(w, d):
return grad_huber(w, d)
def f(beta, d):
return (1. / N) * psi(y - np.dot(X, beta), d)
def grad_f(beta, d):
return -(1. / N) * np.dot(X.T, grad_psi(y - np.dot(X, beta), d))
def f_dd_closure(d):
def f_dd(beta):
return -grad_f(beta, d)
return f_dd
def stopping_criteria_closure(d, eps=1e-5):
def stopping_criteria(beta):
if np.linalg.norm(grad_f(beta, d), ord=np.inf) < eps:
return True
else:
return False
return stopping_criteria
def line_search_closure(d):
ASL = AdaptiveLineSearch(lambda x: grad_f(x, d))
def line_search(x, x_dd):
return ASL.line_search(x, x_dd, lambda t: f(x + t * x_dd, d))
return line_search
beta0 = np.ones(m)
beta_lstsq = np.linalg.solve(np.dot(X.T, X), np.dot(X.T, y))
x = X[:, 0] # Input data without extra features
plt.scatter(x, y, alpha=0.5, marker='o', label='Data')
x_plt = np.linspace(np.min(x), np.max(x), 1000)
X_plt = np.hstack((x_plt[:, None]**k for k in range(1, m + 1)))
y_true = y_curve(beta_true, X_plt)
y_lstsq = y_curve(beta_lstsq, X_plt)
plt.plot(x_plt, y_true, linewidth=2, linestyle='--', color='k',
label='True Curve')
plt.plot(x_plt, y_lstsq, linewidth=2, color='g', label='LstSq Estimate')
d = 1.0
stopping_criteria = stopping_criteria_closure(d)
line_search = line_search_closure(d)
f_dd = f_dd_closure(d)
beta_star, n_iter, success = steepest_descent(beta0, f_dd,
stopping_criteria,
line_search,
maxiter=2000)
y_hat = y_curve(beta_star, X_plt)
plt.plot(x_plt, y_hat, linewidth=2, color='r',
label='Robust Estimate $(\delta = %0.1f)$' % d)
plt.legend()
plt.xlabel(r'$x$')
plt.ylabel(r'$f(x)$')
plt.title('Huber Robust Regression')
plt.savefig('./images/huber_robust.png')
plt.show()
return
if __name__ == '__main__':
example_gradient_descent001()
example_newton001()
example_newton002()
example_smooth_huber()