-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgradient_methods.py
More file actions
279 lines (229 loc) · 8 KB
/
Copy pathgradient_methods.py
File metadata and controls
279 lines (229 loc) · 8 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
# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def gradient_descent(x0, alphas, grad, proj=lambda x : x):
"""Project gradient descent.
This function is written for the purpose of the tutorial.
Input:
x0: initial point
alphas: list of step sizes
grad: gradient function
proj: projection function
Output:
a list of sequence of iterated points
"""
xt = [x0]
for step in alphas:
xt.append(proj(xt[-1] - step * grad(xt[-1])))
return xt
def least_square_sums(A, b, x):
"""
leaste square objective function that should be minimized
Input:
A: matrix, m by n
b: vector, m by 1
x: vector, n by 1
"""
m, n = A.shape
return (0.5/m) * np.linalg.norm(A @ x - b) ** 2
def leaste_square_gradient(A, b, x):
"""
leaste square gradient function (first order derivative)
Input:
A: matrix, m by n
b: vector, m by 1
x: vector, n by 1
"""
m, n = A.shape
return (1/m) * A.T @ (A @ x - b)
def simulate_data(m, n):
"""
simulate data for least square problem
Input:
m: number of samples
n: number of features
Output:
A: matrix, m by n
b: vector, m by 1
theta: coefficient vector, n by 1
"""
A = np.random.randn(m, n)
x = np.random.randn(n, 1)
noise = np.random.normal(0, 0.1, (m, 1))
b = A @ x + noise
return A, b, x
def case_study1():
# assume m > n
m = 100 # number of samples
n = 3 # number of features
# x is coefficient vector
A, b, x = simulate_data(m, n)
# calculate objective function and gradient
# least square sums that should be minimized
objective = lambda x: least_square_sums(A, b, x)
# gradient descent for least square
gradient = lambda x: leaste_square_gradient(A, b, x)
# initialize x0
x0 = np.random.normal(0, 1, (n, 1))
# 100 iterations
xt = gradient_descent(x0, [0.1]*100, gradient)
# plot the error term (the sums of squares error)
fig, ax = plt.subplots(1, 1, figsize=(7, 3.5))
ax.plot([objective(x) for x in xt], "k" ,label="error term")
ax.set_yscale("log")
ax.set_title("Gradient Descent for Least Square")
ax.plot([least_square_sums(A, b, x)]*len(xt), 'k--',
label="true error term")
ax.set_xlabel("Iteration")
ax.set_ylabel("Sum of Squares Error (log scale)")
ax.legend()
plt.savefig('../math/images/gradient-ols.png',
dpi=300, bbox_inches="tight")
df = pd.DataFrame.from_dict(
{
"Initial guess (x0)": x0.flatten(),
"True coefficient (x)": x.flatten(),
"Estimated coefficients (xt)": xt[-1].flatten()
}
)
print(df.to_markdown())
def case_study2():
m, n = 100, 1000
A = np.random.normal(0, 1, (m, n))
b = np.random.normal(0, 1, m)
# The least norm solution is given by the pseudo-inverse
x_opt = np.linalg.pinv(A.T @ A) @ A.T @ b
objective = lambda x: least_square_sums(A, b, x)
gradient = lambda x: leaste_square_gradient(A, b, x)
x0 = np.random.normal(0, 1, n)
xs = gradient_descent(x0, [0.1]*100, gradient)
fig, ax = plt.subplots(1, 1, figsize=(7, 3.5))
ax.plot([objective(x) for x in xs], "k", label="error term")
ax.set_yscale("log")
ax.plot([least_square_sums(A, b, x_opt)]*len(xs), 'k--',
label="true error term")
ax.set_title("Gradient Descent for Least Square")
ax.set_xlabel("Iteration")
ax.set_ylabel("Sum of Squares Error (log scale)")
ax.legend()
plt.savefig('../math/images/gradient-ols2.png',
dpi=300, bbox_inches="tight")
df = pd.DataFrame.from_dict(
{
"Initial guess (x0)": x0.flatten(),
"True coefficient (x)": x_opt.flatten(),
"Estimated coefficients (xt)": xs[-1].flatten()
}
)
print(df.head().to_markdown())
def least_square_sums_l2(A, b, x, lam):
"""
leaste square objective function that should be minimized
Input:
A: matrix, m by n
b: vector, m by 1
x: vector, n by 1
lam: regularization parameter
"""
m, n = A.shape
return least_square_sums(A, b, x) + lam/2 * np.linalg.norm(x) ** 2
def least_square_gradient_l2(A, b, x, lam):
"""
leaste square gradient function (first order derivative)
Input:
A: matrix, m by n
b: vector, m by 1
x: vector, n by 1
lam: regularization parameter
"""
m, n = A.shape
return leaste_square_gradient(A, b, x) + lam * x
def case_study3():
np.random.seed(1337)
m = 100
n = 1000
A = np.random.normal(0, 1, (m, n))
b = np.random.normal(0, 1, m)
lam = 0.1
# the optimal solution is given by the closed form solution
x_opt = np.linalg.pinv(A.T @ A + lam * np.eye(n)) @ A.T @ b
objective = lambda x: least_square_sums_l2(A, b, x, lam)
gradient = lambda x: least_square_gradient_l2(A, b, x, lam)
x0 = np.random.normal(0, 1, n)
xs = gradient_descent(x0, [0.1]*500, gradient)
fig, ax = plt.subplots(1, 1, figsize=(7, 3.5))
ax.plot([objective(x) for x in xs], "k", label="error term")
ax.set_yscale("log")
ax.plot([least_square_sums_l2(A, b, x_opt, lam)]*len(xs), 'k--',
label="true error term")
ax.set_title("Gradient Descent for Least Square")
ax.set_xlabel("Iteration")
ax.set_ylabel("Sum of Squares Error (log scale)")
ax.legend()
plt.savefig('../math/images/gradient-ols3.png',
dpi=300, bbox_inches="tight")
df = pd.DataFrame.from_dict(
{
"Initial guess (x0)": x0.flatten(),
"True coefficient (x)": x_opt.flatten(),
"Estimated coefficients (xt)": xs[-1].flatten()
}
)
print(df.head().to_markdown())
def frank_wolfe_descent(x0, alphas, grad):
n, _ = x0.shape
xt = [x0]
# construct the domain of x
foo = np.linspace(-2, 2, 1000).reshape(-1, 1)
foo2 = np.hstack([foo]*3)
x_domain = foo2.T
for step in alphas:
foo = grad(xt[-1]).T @ x_domain
x_tilde = np.amin(np.abs(foo))
xt.append(xt[-1] + step * (x_tilde - xt[-1]))
return xt
def case_study4():
np.random.seed(1337)
# assume m > n
m = 100 # number of samples
n = 3 # number of features
# x is coefficient vector
A, b, x = simulate_data(m, n)
# calculate objective function and gradient
# least square sums that should be minimized
objective = lambda x: least_square_sums(A, b, x)
# gradient descent for least square
gradient = lambda x: leaste_square_gradient(A, b, x)
# initialize x0
x0 = np.random.normal(0, 1, (n, 1))
# 100 iterations
xt = gradient_descent(x0, [0.1]*100, gradient)
xt_frank_wolfe = frank_wolfe_descent(x0, [0.1]*100, gradient)
# plot the error term (the sums of squares error)
fig, ax = plt.subplots(1, 1, figsize=(7, 3.5))
ax.plot([objective(x) for x in xt], "k" ,label="error term")
ax.plot([objective(x) for x in xt_frank_wolfe], "k:",
label="error term (frank wolfe)")
ax.set_yscale("log")
ax.set_title("Gradient Descent for Least Square")
ax.plot([least_square_sums(A, b, x)]*len(xt), 'k--',
label="true error term")
ax.set_xlabel("Iteration")
ax.set_ylabel("Sum of Squares Error (log scale)")
ax.legend()
# plt.savefig('../math/images/gradient-ols.png',
# dpi=300, bbox_inches="tight")
df = pd.DataFrame.from_dict(
{
"Initial guess (x0)": x0.flatten(),
"True coefficient (x)": x.flatten(),
"Estimated coefficients (xt)": xt[-1].flatten(),
"Estimated coefficients (xt_frank_wolfe)": xt_frank_wolfe[-1].flatten()
}
)
print(df.to_markdown())
if __name__ == "__main__":
print("Hello world!")
case_study4()
# %%