dudl / code_challenge_manipulate_regression_slopes.py
BytePhantom
up
ec69f9c
# %%
# 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()
# %%