File size: 5,156 Bytes
ec69f9c | 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 | # %%
# import libraries
import numpy as np
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from IPython import display
display.set_matplotlib_formats('svg')
# %%
# create data
N = 30
x = torch.randn(N, 1)
y = x + torch.randn(N, 1)/2
# and plot
plt.plot(x,y,'s')
plt.show()
# %%
# build model
ANNreg = nn.Sequential(
nn.Linear(1, 1), # input layer
nn.ReLU(), # activation function
nn.Linear(1, 1) # output layer
)
ANNreg
# %%
# learning rate
learning_rate = .05
# loss function
loss_fn = nn.MSELoss()
# optimizer (the flavor of gradient descent to implement)
optimizer = torch.optim.SGD(ANNreg.parameters(), lr=learning_rate)
# %%
# train the model
num_epochs = 500
losses = torch.zeros(num_epochs)
# Train the model
for epochi in range(num_epochs):
# forward pass
yhat = ANNreg(x)
# compute loss
loss = loss_fn(yhat, y)
losses[epochi] = loss
# backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
# %%
# show the losses
# manually compute losses
# final forward pass
predictions = ANNreg(x)
# final loss (MSE)
test_loss = loss_fn(predictions, y).pow(2).mean()
plt.plot(losses.detach(), 'o', markerfacecolor='w', linewidth=.1)
plt.plot(num_epochs, test_loss.detach(), 'ro')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Final loss: %.3f' % test_loss.item())
plt.show()
# %%
test_loss.item()
# %%
# plot the data
plt.plot(x,y,'bo', label='Real data')
plt.plot(x, predictions.detach(), 'rs', label='Predictions')
plt.title(f'preiction-data r = {np.corrcoef(y.T, predictions.detach().T)[0,1]:.2f}')
plt.legend()
plt.show()
# %%
def Model(x,y, num_epochs, learning_rate):
# build model
ANNreg =nn.Sequential(
nn.Linear(1,1),
nn.ReLU(),
nn.Linear(1,1)
)
# loss function
loss_fn = nn.MSELoss()
# optimizer
optimizer = torch.optim.SGD(ANNreg.parameters(), lr=learning_rate)
# train the model
losses = torch.zeros(num_epochs)
for epoch in range(num_epochs):
# forward pass
yHat = ANNreg(x)
# compute loss
loss = loss_fn(yHat,y)
losses[epoch] = loss
# backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
final_predictions = ANNreg(x)
return final_predictions, losses
N = 30
x = torch.randn(N, 1)
y = x + torch.randn(N, 1)/2
final_predictions, losses = Model(x,y, num_epochs=500, learning_rate=.05)
final_predictions
# %%
# A function that creates and trains the model
def buildAndTrainTheModel(x,y):
# build the model
ANNreg = nn.Sequential(
nn.Linear(1,1), # input layer
nn.ReLU(), # activation function
nn.Linear(1,1) # output layer
)
# loss and optimizer functions
loss_fn = nn.MSELoss()
optimizer = torch.optim.SGD(ANNreg.parameters(), lr=.05)
# train the model
num_epochs = 500
losses = torch.zeros(num_epochs)
for epochi in range(num_epochs):
# forward pass
yHat = ANNreg(x)
# compute loss
loss = loss_fn(yHat, y)
losses[epochi] = loss
# backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
# end traing loop
# compute model predictions
predictions = ANNreg(x)
return predictions, losses
# %%
# A function that creates the data
def createTheData(m):
N = 30
x = torch.randn(N,1)
y = m*x + torch.randn(N,1)/2
return x, y
# %%
# Test it once
# create a dataset
x, y = createTheData(.8)
# run the model
yhat, losses = buildAndTrainTheModel(x,y)
fig, ax = plt.subplots(1,2, figsize=(12,4))
ax[0].plot(losses.detach(),'o',markerfacecolor='w',linewidth=.1)
ax[0].set_xlabel('Epoch')
ax[0].set_title('loss')
ax[1].plot(x,y,'bo',label='Real data')
ax[1].plot(x,yhat.detach(),'rs',label='Predictions')
ax[1].set_xlabel('x')
ax[1].set_ylabel('y')
ax[1].set_title(f'prediction-data corr = {np.corrcoef(y.T, yhat.detach().T)[0,1]:.2f}')
ax[1].legend()
plt.show()
# %%
# Now for the expriment!
# (takes 3 mns with 21 slopes and 50 exps)
# the slopes to simulate
slopes = np.linspace(-2,2,21)
numExps = 50
# intialize output matrix
results = np.zeros((len(slopes), numExps,2))
for slopi in range(len(slopes)):
for expi in range(numExps):
# create data
x, y = createTheData(slopes[slopi])
# run the model
yhat, losses = buildAndTrainTheModel(x,y)
# store the results
results[slopi, expi, 0] = losses[-1]
results[slopi, expi, 1] = np.corrcoef(y.T, yhat.detach().T)[0,1]
# correlation can be 0 if the model didn't do well. Set nan's -> 0
results[np.isnan(results)] = 0
# %%
# plot the results!
fig, ax = plt.subplots(1,2, figsize=(12,4))
ax[0].plot(slopes, np.mean(results[:,:,0], axis=1), 'ko-', markerfacecolor='w', markersize=10)
ax[0].set_xlabel('Slope')
ax[0].set_title('Loss')
ax[1].plot(slopes, np.mean(results[:,:,1], axis=1), 'ms-', markerfacecolor='w', markersize=10)
ax[1].set_xlabel('Slope')
ax[1].set_ylabel('Real-predicted Correlation')
ax[1].set_title('Model performance')
plt.show()
# %%
|