-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathautotuning-ridge_new.jl
More file actions
223 lines (187 loc) · 6 KB
/
Copy pathautotuning-ridge_new.jl
File metadata and controls
223 lines (187 loc) · 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
# # Auto-tuning Hyperparameters (JuMP API)
#md # [](@__REPO_ROOT_URL__/docs/src/examples/autotuning-ridge.jl)
# This example shows how to learn a hyperparameter in Ridge Regression using a gradient descent routine.
# Let the regularized regression problem be formulated as:
# ```math
# \begin{equation}
# \min_{w} \quad \frac{1}{2nd} \sum_{i=1}^{n} (w^T x_{i} - y_i)^2 + \frac{\alpha}{2d} \| w \|_2^2
# \end{equation}
# ```
# where
# - `x`, `y` are the data points
# - `w` are the learned weights
# - `α` is the hyperparameter acting on regularization.
# The main optimization model will be formulated with JuMP.
# Using the gradient of the optimal weights with respect to the regularization parameters
# computed with DiffOpt, we can perform a gradient descent on top of the inner model
# to minimize the test loss.
# This tutorial uses the following packages
using JuMP # The mathematical programming modelling language
import DiffOpt # JuMP extension for differentiable optimization
import Ipopt # Optimization solver that handles quadratic programs
import LinearAlgebra
import Plots
import Random
# ## Generating a noisy regression dataset
Random.seed!(42)
N = 100
D = 20
noise = 5
w_real = 10 * randn(D)
X = 10 * randn(N, D)
y = X * w_real + noise * randn(N)
l = N ÷ 2 # test train split
X_train = X[1:l, :]
X_test = X[(l+1):N, :]
y_train = y[1:l]
y_test = y[(l+1):N];
# ## Defining the regression problem
# We implement the regularized regression problem as a function taking the problem data,
# building a JuMP model and solving it.
# Note the cubic term in the objective function (`α * dot(w, w)`),
# currently this is not handled by ParametricOptInterface smoothly,
# so we use Ipopt as the solver that support parameters as part of
# nonlinear (here only cubic) objective functions.
function build_fit_ridge(X, y, α_val = 1.0)
model = DiffOpt.nonlinear_diff_model(Ipopt.Optimizer)
set_silent(model)
N, D = size(X)
@variable(model, w[1:D])
@variable(model, α in Parameter(α_val))
@expression(model, err_term, X * w - y)
@objective(
model,
Min,
LinearAlgebra.dot(err_term, err_term) / (2 * N * D) +
α * LinearAlgebra.dot(w, w) / (2 * D),
)
return model
end
function optimize_fit_ridge!(model, α_val)
set_parameter_value(model[:α], α_val)
optimize!(model)
return value.(model[:w])
end
# We can solve the problem for several values of α
# to visualize the effect of regularization on the testing and training loss.
αs = 0.00:0.01:0.50
mse_test = Float64[]
mse_train = Float64[]
model = build_fit_ridge(X, y)
(Ntest, D) = size(X_test)
(Ntrain, D) = size(X_train)
for α in αs
ŵ = optimize_fit_ridge!(model, α)
ŷ_test = X_test * ŵ
ŷ_train = X_train * ŵ
push!(mse_test, LinearAlgebra.norm(ŷ_test - y_test)^2 / (2 * Ntest * D))
push!(mse_train, LinearAlgebra.norm(ŷ_train - y_train)^2 / (2 * Ntrain * D))
end
# Visualize the Mean Score Error metric
Plots.plot(
αs,
mse_test ./ sum(mse_test);
label = "MSE test",
xaxis = "α",
yaxis = "MSE",
legend = (0.8, 0.2),
width = 3,
)
Plots.plot!(
αs,
mse_train ./ sum(mse_train);
label = "MSE train",
linestyle = :dash,
width = 3,
)
Plots.title!("Normalized MSE on training and testing sets")
# ## Leveraging differentiable optimization: computing the derivative of the solution
# Using DiffOpt, we can compute `∂w_i/∂α`, the derivative of the learned solution `̂w`
# w.r.t. the regularization parameter.
function compute_dw_dα(model, w)
D = length(w)
dw_dα = zeros(D)
DiffOpt.set_forward_parameter(model, model[:α], 1.0)
DiffOpt.forward_differentiate!(model)
for i in 1:D
dw_dα[i] = DiffOpt.get_forward_variable(model, w[i])
end
return dw_dα
end
# Using `∂w_i/∂α` computed with `compute_dw_dα`,
# we can compute the derivative of the test loss w.r.t. the parameter α
# by composing derivatives.
function d_testloss_dα(model, X_test, y_test, ŵ)
N, D = size(X_test)
dw_dα = compute_dw_dα(model, model[:w])
err_term = X_test * ŵ - y_test
return sum(eachindex(err_term)) do i
return LinearAlgebra.dot(X_test[i, :], dw_dα) * err_term[i]
end / (N * D)
end
# We can define a meta-optimizer function performing gradient descent
# on the test loss w.r.t. the regularization parameter.
function descent(α0, max_iters = 100; fixed_step = 0.01, grad_tol = 1e-3)
α_s = Float64[]
∂α_s = Float64[]
test_loss = Float64[]
α = α0
N, D = size(X_test)
model = build_fit_ridge(X_train, y_train)
for iter in 1:max_iters
ŵ = optimize_fit_ridge!(model, α)
err_term = X_test * ŵ - y_test
∂α = d_testloss_dα(model, X_test, y_test, ŵ)
push!(α_s, α)
push!(∂α_s, ∂α)
push!(test_loss, LinearAlgebra.norm(err_term)^2 / (2 * N * D))
α -= fixed_step * ∂α
if abs(∂α) ≤ grad_tol
break
end
end
return α_s, ∂α_s, test_loss
end
ᾱ, ∂ᾱ, msē = descent(0.10, 500)
iters = 1:length(ᾱ);
# Visualize gradient descent and convergence
Plots.plot(
αs,
mse_test;
label = "MSE test",
xaxis = ("α"),
legend = :topleft,
width = 2,
)
Plots.plot!(ᾱ, msē; label = "learned α", width = 5, style = :dot)
Plots.title!("Regularizer learning")
# Visualize the convergence of α to its optimal value
Plots.plot(
iters,
ᾱ;
label = nothing,
color = :blue,
xaxis = ("Iterations"),
legend = :bottom,
title = "Convergence of α",
)
# Visualize the convergence of the objective function
Plots.plot(
iters,
msē;
label = nothing,
color = :red,
xaxis = ("Iterations"),
legend = :bottom,
title = "Convergence of MSE",
)
# Visualize the convergence of the derivative to zero
Plots.plot(
iters,
∂ᾱ;
label = nothing,
color = :green,
xaxis = ("Iterations"),
legend = :bottom,
title = "Convergence of ∂α",
)