-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo_linear.py
252 lines (187 loc) · 5.6 KB
/
demo_linear.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
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.8
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# %%
# %load_ext autoreload
# %autoreload 2
# %autosave 0
# %matplotlib notebook
# %%
from jupyterthemes import jtplot
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
from IPython.display import HTML
# %%
import match
# %%
jtplot.style(context="talk")
def plot_linear(x, *, yt=None, yp=None, ypl=None, ax=None):
"""Plot a simple linear model.
Args:
x (Matrix): x-axis data (independent)
yt (Matrix): y-axis data for true/target values (dependent)
yp (Matrix): y-axis data for predicted values (dependent)
ypl (str): label for prediction line
ax (axes): matplotlib axes for plotting
"""
# Use 3D projection if x has two dimensions
three_d = x.shape[1] == 2
plot_args = {"projection": "3d"} if three_d else {}
# Create tha axis if one is not provided
if not ax:
_, ax = plt.subplots(figsize=(8,4), subplot_kw=plot_args)
# Grab the underlying matrix data (bit of a peek beneath / hack)
xT = x.T.data.vals
# Plot the "true" data if it exists
if yt:
ytT = yt.T.data.vals
if three_d:
ax.scatter(xT[0], xT[1], ytT[0], label="Target")
else:
ax.scatter(xT[0], ytT[0], label="Target")
# Plot the predicted data
if yp:
# Use "Prediction" as the default label if not is not provided
ypl = "Prediction" if not ypl else ypl
ypT = yp.T.data.vals
if three_d:
ax.scatter(xT[0], xT[1], ypT[0], label=ypl)
else:
plt.plot(xT[0], ypT[0], linestyle="--", label=ypl)
plt.legend()
return ax
# %% [markdown]
# # Create dummy data with some noise
# %%
num_points = 50
num_features = 1
x = match.randn(num_points, num_features)
y_target = x * 5 + 10
nx = x.shape[1]
ny = y_target.shape[1]
# %%
_ = plot_linear(x, yt=y_target)
# %% [markdown]
# # Train a single-feature linear model
# %%
num_epochs = 10
learning_rate = 0.1
loss_fcn = match.nn.MSELoss()
# A single-neuron model
model = match.nn.Linear(nx, ny)
"""
# An alternative method for constructing the model
class Neuron(match.nn.Module):
def __init__(self):
super().__init__()
self.linear = match.nn.Linear(nx, ny)
def forward(self, x):
return self.linear(x)
model = Neuron()
"""
# Save model predictions for each epoch so that we can
# plot progress
predictions = []
for epoch in range(num_epochs):
# Compute model output
y_prediction = model(x)
# Save prediction and a corresponding label
loss = loss_fcn(y_prediction, y_target)
predictions.append((y_prediction, epoch + 1, loss.data.vals[0][0]))
# Backpropagation
model.zero_grad()
loss.backward()
# Update parameters
for param in model.parameters():
param.data = param.data - learning_rate * param.grad
# %%
_, (ax_loss, ax_lines) = plt.subplots(1, 2, figsize=(8, 4))
losses = list(zip(*predictions))[2]
ax_loss.plot(range(1, num_epochs + 1), losses)
ax_loss.set_title("Loss vs. Epoch")
plot_linear(x, yt=y_target, ax=ax_lines)
for y_prediction, epoch, loss in predictions:
label = f"{epoch:>3}/{num_epochs}: {loss:5.2f}"
plot_linear(x, yp=y_prediction, ypl=label, ax=ax_lines)
_ = ax_lines.set_title("Model Improvement")
# %%
fig, ax = plt.subplots(figsize=(8, 4))
ax.set_xlim([-2.5, 2.5])
ax.set_ylim([-5, 20])
line, = ax.plot([], [], color="r", lw=2, label="Prediction")
xT = x.T.data.vals
ytT = y_target.T.data.vals
ax.scatter(xT, ytT, lw=2, label="Target")
ax.legend()
def animate(frame):
ypT = frame[0].T.data.vals
line.set_data(xT, ypT)
return line,
animation = FuncAnimation(fig, animate, predictions)
# %%
HTML(animation.to_jshtml())
# %%
# animation.save("demo_linear_1d.mp4")
# %% [markdown]
# # Train a two-feature linear model¶
# %%
num_points = 100
num_features = 2
x = match.randn(num_points, num_features)
true_weights = match.mat([[2.0, -1.0]])
y_target = x @ true_weights.T + 0.5
nx = x.shape[1]
ny = y_target.shape[1]
# %%
plot_linear(x, yt=y_target)
_ = plt.title("Interactive Plot (Click and Drag Me)")
# %%
num_epochs = 10
learning_rate = 0.1
loss_fcn = match.nn.MSELoss()
# A single-neuron model
model = match.nn.Linear(nx, ny)
# Save model predictions for each epoch so that we can
# plot progress
predictions = []
for epoch in range(num_epochs):
# Compute model output
y_prediction = model(x)
# Save prediction and a corresponding label
loss = loss_fcn(y_prediction, y_target)
predictions.append((y_prediction, epoch + 1, loss.data.vals[0][0]))
# Backpropagation
model.zero_grad()
loss.backward()
# Update parameters
for param in model.parameters():
param.data = param.data - learning_rate * param.grad
# %%
fig = plt.figure(figsize=(8, 4))
ax_loss = fig.add_subplot(121)
losses = list(zip(*predictions))[2]
ax_loss.plot(range(1, num_epochs + 1), losses)
ax_loss.set_title("Loss vs. Epoch")
# Plot just the first and final models
ax_lines = fig.add_subplot(122, projection="3d")
plot_linear(x, yt=y_target, ax=ax_lines)
ax_lines.set_title("Model Predictions (Click and Drag)")
# First model
yp, e, l = predictions[0]
plot_linear(x, yp=yp, ypl=f"{e:>3}/{num_epochs}: {l:5.2f}", ax=ax_lines)
# Final model
yp, e, l = predictions[-1]
_ = plot_linear(x, yp=yp, ypl=f"{e:>3}/{num_epochs}: {l:5.2f}", ax=ax_lines)
# %%