mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
749 KiB
749 KiB
In [1]:
from sklearn.datasets import make_circles
# Make 1000 samples
n_samples = 1000
# Create circles
X, y = make_circles(n_samples,
noise=0.03, # a little bit of noise to the dots
random_state=42) # keep random state so we get the same valuesIn [2]:
print(f"First 5 X features:\n{X[:5]}")
print(f"\nFirst 5 y labels:\n{y[:5]}")First 5 X features: [[ 0.75424625 0.23148074] [-0.75615888 0.15325888] [-0.81539193 0.17328203] [-0.39373073 0.69288277] [ 0.44220765 -0.89672343]] First 5 y labels: [1 1 1 1 0]
In [3]:
# Make DataFrame of circle data
import pandas as pd
circles = pd.DataFrame({"X1": X[:, 0],
"X2": X[:, 1],
"label": y
})
circles.head(10)Out [3]:
| X1 | X2 | label | |
|---|---|---|---|
| 0 | 0.754246 | 0.231481 | 1 |
| 1 | -0.756159 | 0.153259 | 1 |
| 2 | -0.815392 | 0.173282 | 1 |
| 3 | -0.393731 | 0.692883 | 1 |
| 4 | 0.442208 | -0.896723 | 0 |
| 5 | -0.479646 | 0.676435 | 1 |
| 6 | -0.013648 | 0.803349 | 1 |
| 7 | 0.771513 | 0.147760 | 1 |
| 8 | -0.169322 | -0.793456 | 1 |
| 9 | -0.121486 | 1.021509 | 0 |
In [4]:
# Check different labels
circles.label.value_counts()Out [4]:
1 500 0 500 Name: label, dtype: int64
In [5]:
# Visualize with a plot
import matplotlib.pyplot as plt
plt.scatter(x=X[:, 0],
y=X[:, 1],
c=y,
cmap=plt.cm.RdYlBu);In [6]:
# Check the shapes of our features and labels
X.shape, y.shapeOut [6]:
((1000, 2), (1000,))
In [7]:
# View the first example of features and labels
X_sample = X[0]
y_sample = y[0]
print(f"Values for one sample of X: {X_sample} and the same for y: {y_sample}")
print(f"Shapes for one sample of X: {X_sample.shape} and the same for y: {y_sample.shape}")Values for one sample of X: [0.75424625 0.23148074] and the same for y: 1 Shapes for one sample of X: (2,) and the same for y: ()
In [8]:
# Turn data into tensors
# Otherwise this causes issues with computations later on
import torch
X = torch.from_numpy(X).type(torch.float)
y = torch.from_numpy(y).type(torch.float)
# View the first five samples
X[:5], y[:5]Out [8]:
(tensor([[ 0.7542, 0.2315],
[-0.7562, 0.1533],
[-0.8154, 0.1733],
[-0.3937, 0.6929],
[ 0.4422, -0.8967]]), tensor([1., 1., 1., 1., 0.]))In [9]:
# Split data into train and test sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,
y,
test_size=0.2, # 20% test, 80% train
random_state=42) # make the random split reproducible
len(X_train), len(X_test), len(y_train), len(y_test)Out [9]:
(800, 200, 800, 200)
In [10]:
# Standard PyTorch imports
import torch
from torch import nn
# Make device agnostic code
device = "cuda" if torch.cuda.is_available() else "cpu"
deviceOut [10]:
'cuda'
In [11]:
# 1. Construct a model class that subclasses nn.Module
class CircleModelV0(nn.Module):
def __init__(self):
super().__init__()
# 2. Create 2 nn.Linear layers capable of handling X and y input and output shapes
self.layer_1 = nn.Linear(in_features=2, out_features=5) # takes in 2 features (X), produces 5 features
self.layer_2 = nn.Linear(in_features=5, out_features=1) # takes in 5 features, produces 1 feature (y)
# 3. Define a forward method containing the forward pass computation
def forward(self, x):
# Return the output of layer_2, a single feature, the same shape as y
return self.layer_2(self.layer_1(x)) # computation goes through layer_1 first then the output of layer_1 goes through layer_2
# 4. Create an instance of the model and send it to target device
model_0 = CircleModelV0().to(device)
model_0Out [11]:
CircleModelV0( (layer_1): Linear(in_features=2, out_features=5, bias=True) (layer_2): Linear(in_features=5, out_features=1, bias=True) )
In [12]:
# Replicate CircleModelV0 with nn.Sequential
model_0 = nn.Sequential(
nn.Linear(in_features=2, out_features=5),
nn.Linear(in_features=5, out_features=1)
).to(device)
model_0Out [12]:
Sequential( (0): Linear(in_features=2, out_features=5, bias=True) (1): Linear(in_features=5, out_features=1, bias=True) )
In [13]:
# Make predictions with the model
untrained_preds = model_0(X_test.to(device))
print(f"Length of predictions: {len(untrained_preds)}, Shape: {untrained_preds.shape}")
print(f"Length of test samples: {len(y_test)}, Shape: {y_test.shape}")
print(f"\nFirst 10 predictions:\n{untrained_preds[:10]}")
print(f"\nFirst 10 test labels:\n{y_test[:10]}")Length of predictions: 200, Shape: torch.Size([200, 1])
Length of test samples: 200, Shape: torch.Size([200])
First 10 predictions:
tensor([[0.2632],
[0.2296],
[0.2759],
[0.2599],
[0.1564],
[0.1369],
[0.1371],
[0.1151],
[0.2809],
[0.2261]], device='cuda:0', grad_fn=<SliceBackward0>)
First 10 test labels:
tensor([1., 0., 1., 0., 1., 1., 0., 0., 1., 0.])
In [14]:
# Create a loss function
# loss_fn = nn.BCELoss() # BCELoss = no sigmoid built-in
loss_fn = nn.BCEWithLogitsLoss() # BCEWithLogitsLoss = sigmoid built-in
# Create an optimizer
optimizer = torch.optim.SGD(params=model_0.parameters(),
lr=0.1)In [15]:
# Calculate accuracy (a classification metric)
def accuracy_fn(y_true, y_pred):
correct = torch.eq(y_true, y_pred).sum().item() # torch.eq() calculates where two tensors are equal
acc = (correct / len(y_pred)) * 100
return accIn [21]:
# View the frist 5 outputs of the forward pass on the test data
y_logits = model_0(X_test.to(device))[:5]
y_logitsOut [21]:
tensor([[0.2632],
[0.2296],
[0.2759],
[0.2599],
[0.1564]], device='cuda:0', grad_fn=<SliceBackward0>)In [22]:
# Use sigmoid on model logits
y_pred_probs = torch.sigmoid(y_logits)
y_pred_probsOut [22]:
tensor([[0.5654],
[0.5572],
[0.5685],
[0.5646],
[0.5390]], device='cuda:0', grad_fn=<SigmoidBackward0>)In [36]:
# Find the predicted labels (round the prediction probabilities)
y_preds = torch.round(y_pred_probs)
# In full
y_pred_labels = torch.round(torch.sigmoid(model_0(X_test.to(device))[:5]))
# Check for equality
print(torch.eq(y_preds.squeeze(), y_pred_labels.squeeze()))
# Get rid of extra dimension
y_preds.squeeze()Out [36]:
tensor([True, True, True, True, True], device='cuda:0')
tensor([1., 1., 1., 1., 1.], device='cuda:0', grad_fn=<SqueezeBackward0>)
In [37]:
y_test[:5]Out [37]:
tensor([1., 0., 1., 0., 1.])
In [38]:
torch.manual_seed(42)
# Set the number of epochs
epochs = 100
# Put data to target device
X_train, y_train = X_train.to(device), y_train.to(device)
X_test, y_test = X_test.to(device), y_test.to(device)
# Build training and evaluation loop
for epoch in range(epochs):
### Training
model_0.train()
# 1. Forward pass (model outputs raw logits)
y_logits = model_0(X_train).squeeze() # squeeze to remove extra `1` dimensions, this won't work unless model and data are on same device
y_pred = torch.round(torch.sigmoid(y_logits)) # turn logits -> pred probs -> pred labls
# 2. Calculate loss/accuracy
# loss = loss_fn(torch.sigmoid(y_logits), # Using nn.BCELoss you need torch.sigmoid()
# y_train)
loss = loss_fn(y_logits, # Using nn.BCEWithLogitsLoss works with raw logits
y_train)
acc = accuracy_fn(y_true=y_train,
y_pred=y_pred)
# 3. Optimizer zero grad
optimizer.zero_grad()
# 4. Loss backwards
loss.backward()
# 5. Optimizer step
optimizer.step()
### Testing
model_0.eval()
with torch.inference_mode():
# 1. Forward pass
test_logits = model_0(X_test).squeeze()
test_pred = torch.round(torch.sigmoid(test_logits))
# 2. Caculate loss/accuracy
test_loss = loss_fn(test_logits,
y_test)
test_acc = accuracy_fn(y_true=y_test,
y_pred=test_pred)
# Print out what's happening every 10 epochs
if epoch % 10 == 0:
print(f"Epoch: {epoch} | Loss: {loss:.5f}, Accuracy: {acc:.2f}% | Test loss: {test_loss:.5f}, Test acc: {test_acc:.2f}%")Epoch: 0 | Loss: 0.69939, Accuracy: 50.00% | Test loss: 0.69805, Test acc: 50.00% Epoch: 10 | Loss: 0.69562, Accuracy: 50.00% | Test loss: 0.69461, Test acc: 50.00% Epoch: 20 | Loss: 0.69434, Accuracy: 58.50% | Test loss: 0.69353, Test acc: 56.50% Epoch: 30 | Loss: 0.69387, Accuracy: 51.62% | Test loss: 0.69321, Test acc: 54.50% Epoch: 40 | Loss: 0.69367, Accuracy: 50.25% | Test loss: 0.69317, Test acc: 56.50% Epoch: 50 | Loss: 0.69356, Accuracy: 50.12% | Test loss: 0.69321, Test acc: 55.00% Epoch: 60 | Loss: 0.69349, Accuracy: 50.00% | Test loss: 0.69328, Test acc: 51.50% Epoch: 70 | Loss: 0.69344, Accuracy: 49.50% | Test loss: 0.69336, Test acc: 53.00% Epoch: 80 | Loss: 0.69340, Accuracy: 49.50% | Test loss: 0.69344, Test acc: 54.50% Epoch: 90 | Loss: 0.69336, Accuracy: 49.50% | Test loss: 0.69352, Test acc: 54.50%
In [45]:
import numpy as np
# TK - this could go in the helper_functions.py and be explained there
def plot_decision_boundary(model, X, y):
# Put everything to CPU (works better with NumPy + Matplotlib)
model.to("cpu")
X, y = X.to("cpu"), y.to("cpu")
# Source - https://madewithml.com/courses/foundations/neural-networks/
# (with modifications)
x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1
y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 101),
np.linspace(y_min, y_max, 101))
# Make features
X_to_pred_on = torch.from_numpy(np.column_stack((xx.ravel(), yy.ravel()))).float()
# Make predictions
model.eval()
with torch.inference_mode():
y_logits = model(X_to_pred_on)
# Test for multi-class or binary and adjust logits to prediction labels
if len(torch.unique(y)) > 2:
y_pred = torch.softmax(y_logits, dim=1).argmax(dim=1) # mutli-class
else:
y_pred = torch.round(torch.sigmoid(y_logits)) # binary
# Reshape preds and plot
y_pred = y_pred.reshape(xx.shape).detach().numpy()
plt.contourf(xx, yy, y_pred, cmap=plt.cm.RdYlBu, alpha=0.7)
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.RdYlBu)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())In [54]:
# Plot decision boundaries for training and test sets
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.title("Train")
plot_decision_boundary(model_0, X_train, y_train)
plt.subplot(1, 2, 2)
plt.title("Test")
plot_decision_boundary(model_0, X_test, y_test)In [55]:
class CircleModelV1(nn.Module):
def __init__(self):
super().__init__()
self.layer_1 = nn.Linear(in_features=2, out_features=10)
self.layer_2 = nn.Linear(in_features=10, out_features=10) # extra layer
self.layer_3 = nn.Linear(in_features=10, out_features=1)
def forward(self, x): # note: always make sure forward is spelt correctly!
# Creating a model like this is the same as below, though below
# generally benefits from speedups where possible.
# z = self.layer_1(x)
# z = self.layer_2(z)
# z = self.layer_3(z)
# return z
return self.layer_3(self.layer_2(self.layer_1(x)))
model_1 = CircleModelV1().to(device)
model_1Out [55]:
CircleModelV1( (layer_1): Linear(in_features=2, out_features=10, bias=True) (layer_2): Linear(in_features=10, out_features=10, bias=True) (layer_3): Linear(in_features=10, out_features=1, bias=True) )
In [56]:
# loss_fn = nn.BCELoss() # Requires sigmoid on input
loss_fn = nn.BCEWithLogitsLoss() # Does not require sigmoid on input
optimizer = torch.optim.SGD(model_1.parameters(), lr=0.1)In [57]:
torch.manual_seed(42)
epochs = 1000 # Train for longer
# Put data to target device
X_train, y_train = X_train.to(device), y_train.to(device)
X_test, y_test = X_test.to(device), y_test.to(device)
for epoch in range(epochs):
### Training
# 1. Forward pass
y_logits = model_1(X_train).squeeze()
y_pred = torch.round(torch.sigmoid(y_logits)) # logits -> predicition probabilities -> prediction labels
# 2. Calculate loss/accuracy
loss = loss_fn(y_pred, y_train)
acc = accuracy_fn(y_true=y_train,
y_pred=y_pred)
# 3. Optimizer zero grad
optimizer.zero_grad()
# 4. Loss backwards
loss.backward()
# 5. Optimizer step
optimizer.step()
### Testing
model_1.eval()
with torch.inference_mode():
# 1. Forward pass
test_logits = model_1(X_test).squeeze()
test_pred = torch.round(torch.sigmoid(test_logits))
# 2. Caculate loss/accuracy
test_loss = loss_fn(test_logits,
y_test)
test_acc = accuracy_fn(y_true=y_test,
y_pred=test_pred)
# Print out what's happening every 10 epochs
if epoch % 100 == 0:
print(f"Epoch: {epoch} | Loss: {loss:.5f}, Accuracy: {acc:.2f}% | Test loss: {test_loss:.5f}, Test acc: {test_acc:.2f}%")
Epoch: 0 | Loss: 0.75769, Accuracy: 50.88% | Test loss: 0.69261, Test acc: 51.00% Epoch: 100 | Loss: 0.75769, Accuracy: 50.88% | Test loss: 0.69261, Test acc: 51.00% Epoch: 200 | Loss: 0.75769, Accuracy: 50.88% | Test loss: 0.69261, Test acc: 51.00% Epoch: 300 | Loss: 0.75769, Accuracy: 50.88% | Test loss: 0.69261, Test acc: 51.00% Epoch: 400 | Loss: 0.75769, Accuracy: 50.88% | Test loss: 0.69261, Test acc: 51.00% Epoch: 500 | Loss: 0.75769, Accuracy: 50.88% | Test loss: 0.69261, Test acc: 51.00% Epoch: 600 | Loss: 0.75769, Accuracy: 50.88% | Test loss: 0.69261, Test acc: 51.00% Epoch: 700 | Loss: 0.75769, Accuracy: 50.88% | Test loss: 0.69261, Test acc: 51.00% Epoch: 800 | Loss: 0.75769, Accuracy: 50.88% | Test loss: 0.69261, Test acc: 51.00% Epoch: 900 | Loss: 0.75769, Accuracy: 50.88% | Test loss: 0.69261, Test acc: 51.00%
In [58]:
# Plot decision boundaries for training and test sets
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.title("Train")
plot_decision_boundary(model_1, X_train, y_train)
plt.subplot(1, 2, 2)
plt.title("Test")
plot_decision_boundary(model_1, X_test, y_test)In [59]:
# Create some data (same as notebook 01)
weight = 0.7
bias = 0.3
start = 0
end = 1
step = 0.02
# TK - change these variable names so they don't interfere with the original circles data
# Create data
X_regression = torch.arange(start, end, step).unsqueeze(dim=1)
y_regression = weight * X_regression + bias
X_regression[:5], y_regression[:5]Out [59]:
(tensor([[0.0000],
[0.0200],
[0.0400],
[0.0600],
[0.0800]]), tensor([[0.3000],
[0.3140],
[0.3280],
[0.3420],
[0.3560]]))In [60]:
# Create train/test split
train_split = int(0.8 * len(X_regression)) # 80% of data used for training set
X_train_regression, y_train_regression = X_regression[:train_split], \
y_regression[:train_split]
X_test_regression, y_test_regression = X_regression[train_split:], \
y_regression[train_split:]
print(len(X_train_regression),
len(y_train_regression),
len(X_test_regression),
len(y_test_regression))40 40 10 10
In [61]:
# TK - put this in helper function file...
def plot_predictions(train_data=X_train,
train_labels=y_train,
test_data=X_test,
test_labels=y_test,
predictions=None):
"""
Plots training data, test data and compares predictions.
"""
plt.figure(figsize=(10, 7))
# Plot training data in blue
plt.scatter(train_data, train_labels, c="b", s=4, label="Training data")
# Plot test data in green
plt.scatter(test_data, test_labels, c="g", s=4, label="Testing data")
if predictions is not None:
# Plot the predictions in red (predictions were made on the test data)
plt.scatter(test_data, predictions, c="r", s=4, label="Predictions")
# Show the legend
plt.legend(prop={"size": 14});In [62]:
plot_predictions(train_data=X_train_regression,
train_labels=y_train_regression,
test_data=X_test_regression,
test_labels=y_test_regression
);In [63]:
# Same architecture as model_1 (but using nn.Sequential)
model_2 = nn.Sequential(
nn.Linear(in_features=1, out_features=10),
nn.Linear(in_features=10, out_features=10),
nn.Linear(in_features=10, out_features=1)
)
model_2Out [63]:
Sequential( (0): Linear(in_features=1, out_features=10, bias=True) (1): Linear(in_features=10, out_features=10, bias=True) (2): Linear(in_features=10, out_features=1, bias=True) )
In [64]:
# Loss and optimizer
loss_fn = nn.L1Loss()
optimizer = torch.optim.SGD(model_2.parameters(), lr=0.1)In [65]:
# Train the model
torch.manual_seed(42)
epochs = 1000
for epoch in range(epochs):
# 1. Forward pass
y_pred = model_2(X_train_regression)
# 2. Calculate loss
loss = loss_fn(y_pred, y_train_regression)
# 3. Optimizer zero grad
optimizer.zero_grad()
# 4. Loss backwards
loss.backward()
# 5. Optimizer step
optimizer.step()
# Testing
model_2.eval()
with torch.inference_mode():
test_pred = model_2(X_test_regression)
test_loss = loss_fn(test_pred, y_test_regression)
# Print out what's happening
if epoch % 100 == 0:
print(f"Epoch: {epoch} | Train loss: {loss:.5f}, Test loss: {test_loss:.5f}")
Epoch: 0 | Train loss: 0.75792, Test loss: 0.54143 Epoch: 100 | Train loss: 0.07424, Test loss: 0.00881 Epoch: 200 | Train loss: 0.07601, Test loss: 0.01785 Epoch: 300 | Train loss: 0.06932, Test loss: 0.03021 Epoch: 400 | Train loss: 0.06326, Test loss: 0.01104 Epoch: 500 | Train loss: 0.05926, Test loss: 0.01172 Epoch: 600 | Train loss: 0.05980, Test loss: 0.02428 Epoch: 700 | Train loss: 0.04829, Test loss: 0.02345 Epoch: 800 | Train loss: 0.04891, Test loss: 0.00572 Epoch: 900 | Train loss: 0.06723, Test loss: 0.00978
In [66]:
model_2.eval()
with torch.inference_mode():
y_preds = model_2(X_test_regression)
plot_predictions(train_data=X_train_regression,
train_labels=y_train_regression,
test_data=X_test_regression,
test_labels=y_test_regression,
predictions=y_preds.detach().numpy());In [67]:
# Make data
from sklearn.datasets import make_circles
n_samples = 1000
X, y = make_circles(n_samples=1000,
noise=0.03,
random_state=42,
)In [68]:
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.RdBu)Out [68]:
<matplotlib.collections.PathCollection at 0x7f1fdad212d0>
In [69]:
# Convert to tensors and split into train and test sets
import torch
from sklearn.model_selection import train_test_split
X = torch.from_numpy(X).type(torch.float)
y = torch.from_numpy(y).type(torch.float)
# Split into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42
)
X_train[:5], y_train[:5]Out [69]:
(tensor([[ 0.6579, -0.4651],
[ 0.6319, -0.7347],
[-1.0086, -0.1240],
[-0.9666, -0.2256],
[-0.1666, 0.7994]]), tensor([1., 0., 0., 0., 1.]))In [70]:
# Build model
from torch import nn
class CircleModelV2(nn.Module):
def __init__(self):
super().__init__()
self.layer_1 = nn.Linear(in_features=2, out_features=10)
self.layer_2 = nn.Linear(in_features=10, out_features=10)
self.layer_3 = nn.Linear(in_features=10, out_features=1)
self.relu = nn.ReLU()
# Can also put sigmoid in the model
# This would mean you don't need to use it on the predictions
# self.sigmoid = nn.Sigmoid()
def forward(self, x):
return self.layer_3(self.relu(self.layer_2(self.relu(self.layer_1(x)))))
model_3 = CircleModelV2().to(device)
print(model_3)CircleModelV2( (layer_1): Linear(in_features=2, out_features=10, bias=True) (layer_2): Linear(in_features=10, out_features=10, bias=True) (layer_3): Linear(in_features=10, out_features=1, bias=True) (relu): ReLU() )
In [71]:
# Setup loss and optimizer
loss_fn = nn.BCEWithLogitsLoss()
optimizer = torch.optim.SGD(model_3.parameters(), lr=0.1)In [72]:
# Fit the model
torch.manual_seed(42)
epochs = 1000
for epoch in range(epochs):
# 1. Forward pass
y_pred = model_3(X_train).squeeze()
# 2. Calculate loss
loss = loss_fn(y_pred, y_train)
acc = accuracy_fn(y_true=y_train,
y_pred=torch.round(torch.sigmoid(y_pred)))
# 3. Optimizer zero grad
optimizer.zero_grad()
# 4. Loss backward
loss.backward()
# 5. Optimizer step
optimizer.step()
# Print out what's happening
if epoch % 100 == 0:
print(f"Epoch: {epoch} | Loss: {loss:.5f}, Accuracy: {acc:.2f}%")[0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) [0;32m<ipython-input-72-dd8d212c8183>[0m in [0;36m<module>[0;34m()[0m [1;32m 4[0m [0;32mfor[0m [0mepoch[0m [0;32min[0m [0mrange[0m[0;34m([0m[0mepochs[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [1;32m 5[0m [0;31m# 1. Forward pass[0m[0;34m[0m[0;34m[0m[0;34m[0m[0m [0;32m----> 6[0;31m [0my_pred[0m [0;34m=[0m [0mmodel_3[0m[0;34m([0m[0mX_train[0m[0;34m)[0m[0;34m.[0m[0msqueeze[0m[0;34m([0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 7[0m [0;34m[0m[0m [1;32m 8[0m [0;31m# 2. Calculate loss[0m[0;34m[0m[0;34m[0m[0;34m[0m[0m [0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py[0m in [0;36m_call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1100[0m if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks [1;32m 1101[0m or _global_forward_hooks or _global_forward_pre_hooks): [0;32m-> 1102[0;31m [0;32mreturn[0m [0mforward_call[0m[0;34m([0m[0;34m*[0m[0minput[0m[0;34m,[0m [0;34m**[0m[0mkwargs[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 1103[0m [0;31m# Do not call functions when jit is used[0m[0;34m[0m[0;34m[0m[0;34m[0m[0m [1;32m 1104[0m [0mfull_backward_hooks[0m[0;34m,[0m [0mnon_full_backward_hooks[0m [0;34m=[0m [0;34m[[0m[0;34m][0m[0;34m,[0m [0;34m[[0m[0;34m][0m[0;34m[0m[0;34m[0m[0m [0;32m<ipython-input-70-fccb548ea524>[0m in [0;36mforward[0;34m(self, x)[0m [1;32m 13[0m [0;34m[0m[0m [1;32m 14[0m [0;32mdef[0m [0mforward[0m[0;34m([0m[0mself[0m[0;34m,[0m [0mx[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m---> 15[0;31m [0;32mreturn[0m [0mself[0m[0;34m.[0m[0mlayer_3[0m[0;34m([0m[0mself[0m[0;34m.[0m[0mrelu[0m[0;34m([0m[0mself[0m[0;34m.[0m[0mlayer_2[0m[0;34m([0m[0mself[0m[0;34m.[0m[0mrelu[0m[0;34m([0m[0mself[0m[0;34m.[0m[0mlayer_1[0m[0;34m([0m[0mx[0m[0;34m)[0m[0;34m)[0m[0;34m)[0m[0;34m)[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 16[0m [0;34m[0m[0m [1;32m 17[0m [0mmodel_3[0m [0;34m=[0m [0mCircleModelV2[0m[0;34m([0m[0;34m)[0m[0;34m.[0m[0mto[0m[0;34m([0m[0mdevice[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py[0m in [0;36m_call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1100[0m if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks [1;32m 1101[0m or _global_forward_hooks or _global_forward_pre_hooks): [0;32m-> 1102[0;31m [0;32mreturn[0m [0mforward_call[0m[0;34m([0m[0;34m*[0m[0minput[0m[0;34m,[0m [0;34m**[0m[0mkwargs[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 1103[0m [0;31m# Do not call functions when jit is used[0m[0;34m[0m[0;34m[0m[0;34m[0m[0m [1;32m 1104[0m [0mfull_backward_hooks[0m[0;34m,[0m [0mnon_full_backward_hooks[0m [0;34m=[0m [0;34m[[0m[0;34m][0m[0;34m,[0m [0;34m[[0m[0;34m][0m[0;34m[0m[0;34m[0m[0m [0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/linear.py[0m in [0;36mforward[0;34m(self, input)[0m [1;32m 101[0m [0;34m[0m[0m [1;32m 102[0m [0;32mdef[0m [0mforward[0m[0;34m([0m[0mself[0m[0;34m,[0m [0minput[0m[0;34m:[0m [0mTensor[0m[0;34m)[0m [0;34m->[0m [0mTensor[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m--> 103[0;31m [0;32mreturn[0m [0mF[0m[0;34m.[0m[0mlinear[0m[0;34m([0m[0minput[0m[0;34m,[0m [0mself[0m[0;34m.[0m[0mweight[0m[0;34m,[0m [0mself[0m[0;34m.[0m[0mbias[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 104[0m [0;34m[0m[0m [1;32m 105[0m [0;32mdef[0m [0mextra_repr[0m[0;34m([0m[0mself[0m[0;34m)[0m [0;34m->[0m [0mstr[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py[0m in [0;36mlinear[0;34m(input, weight, bias)[0m [1;32m 1846[0m [0;32mif[0m [0mhas_torch_function_variadic[0m[0;34m([0m[0minput[0m[0;34m,[0m [0mweight[0m[0;34m,[0m [0mbias[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [1;32m 1847[0m [0;32mreturn[0m [0mhandle_torch_function[0m[0;34m([0m[0mlinear[0m[0;34m,[0m [0;34m([0m[0minput[0m[0;34m,[0m [0mweight[0m[0;34m,[0m [0mbias[0m[0;34m)[0m[0;34m,[0m [0minput[0m[0;34m,[0m [0mweight[0m[0;34m,[0m [0mbias[0m[0;34m=[0m[0mbias[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0;32m-> 1848[0;31m [0;32mreturn[0m [0mtorch[0m[0;34m.[0m[0m_C[0m[0;34m.[0m[0m_nn[0m[0;34m.[0m[0mlinear[0m[0;34m([0m[0minput[0m[0;34m,[0m [0mweight[0m[0;34m,[0m [0mbias[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 1849[0m [0;34m[0m[0m [1;32m 1850[0m [0;34m[0m[0m [0;31mRuntimeError[0m: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_addmm)
In [73]:
# Make predictions
model_3.eval()
with torch.inference_mode():
y_preds = torch.round(torch.sigmoid(model_3(X_test))).squeeze()
y_preds[:10], y[:10] # want preds in same format as truth labels[0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) [0;32m<ipython-input-73-ff6f65993e5e>[0m in [0;36m<module>[0;34m()[0m [1;32m 2[0m [0mmodel_3[0m[0;34m.[0m[0meval[0m[0;34m([0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [1;32m 3[0m [0;32mwith[0m [0mtorch[0m[0;34m.[0m[0minference_mode[0m[0;34m([0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m----> 4[0;31m [0my_preds[0m [0;34m=[0m [0mtorch[0m[0;34m.[0m[0mround[0m[0;34m([0m[0mtorch[0m[0;34m.[0m[0msigmoid[0m[0;34m([0m[0mmodel_3[0m[0;34m([0m[0mX_test[0m[0;34m)[0m[0;34m)[0m[0;34m)[0m[0;34m.[0m[0msqueeze[0m[0;34m([0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 5[0m [0my_preds[0m[0;34m[[0m[0;34m:[0m[0;36m10[0m[0;34m][0m[0;34m,[0m [0my[0m[0;34m[[0m[0;34m:[0m[0;36m10[0m[0;34m][0m [0;31m# want preds in same format as truth labels[0m[0;34m[0m[0;34m[0m[0m [0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py[0m in [0;36m_call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1100[0m if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks [1;32m 1101[0m or _global_forward_hooks or _global_forward_pre_hooks): [0;32m-> 1102[0;31m [0;32mreturn[0m [0mforward_call[0m[0;34m([0m[0;34m*[0m[0minput[0m[0;34m,[0m [0;34m**[0m[0mkwargs[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 1103[0m [0;31m# Do not call functions when jit is used[0m[0;34m[0m[0;34m[0m[0;34m[0m[0m [1;32m 1104[0m [0mfull_backward_hooks[0m[0;34m,[0m [0mnon_full_backward_hooks[0m [0;34m=[0m [0;34m[[0m[0;34m][0m[0;34m,[0m [0;34m[[0m[0;34m][0m[0;34m[0m[0;34m[0m[0m [0;32m<ipython-input-70-fccb548ea524>[0m in [0;36mforward[0;34m(self, x)[0m [1;32m 13[0m [0;34m[0m[0m [1;32m 14[0m [0;32mdef[0m [0mforward[0m[0;34m([0m[0mself[0m[0;34m,[0m [0mx[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m---> 15[0;31m [0;32mreturn[0m [0mself[0m[0;34m.[0m[0mlayer_3[0m[0;34m([0m[0mself[0m[0;34m.[0m[0mrelu[0m[0;34m([0m[0mself[0m[0;34m.[0m[0mlayer_2[0m[0;34m([0m[0mself[0m[0;34m.[0m[0mrelu[0m[0;34m([0m[0mself[0m[0;34m.[0m[0mlayer_1[0m[0;34m([0m[0mx[0m[0;34m)[0m[0;34m)[0m[0;34m)[0m[0;34m)[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 16[0m [0;34m[0m[0m [1;32m 17[0m [0mmodel_3[0m [0;34m=[0m [0mCircleModelV2[0m[0;34m([0m[0;34m)[0m[0;34m.[0m[0mto[0m[0;34m([0m[0mdevice[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py[0m in [0;36m_call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1100[0m if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks [1;32m 1101[0m or _global_forward_hooks or _global_forward_pre_hooks): [0;32m-> 1102[0;31m [0;32mreturn[0m [0mforward_call[0m[0;34m([0m[0;34m*[0m[0minput[0m[0;34m,[0m [0;34m**[0m[0mkwargs[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 1103[0m [0;31m# Do not call functions when jit is used[0m[0;34m[0m[0;34m[0m[0;34m[0m[0m [1;32m 1104[0m [0mfull_backward_hooks[0m[0;34m,[0m [0mnon_full_backward_hooks[0m [0;34m=[0m [0;34m[[0m[0;34m][0m[0;34m,[0m [0;34m[[0m[0;34m][0m[0;34m[0m[0;34m[0m[0m [0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/linear.py[0m in [0;36mforward[0;34m(self, input)[0m [1;32m 101[0m [0;34m[0m[0m [1;32m 102[0m [0;32mdef[0m [0mforward[0m[0;34m([0m[0mself[0m[0;34m,[0m [0minput[0m[0;34m:[0m [0mTensor[0m[0;34m)[0m [0;34m->[0m [0mTensor[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m--> 103[0;31m [0;32mreturn[0m [0mF[0m[0;34m.[0m[0mlinear[0m[0;34m([0m[0minput[0m[0;34m,[0m [0mself[0m[0;34m.[0m[0mweight[0m[0;34m,[0m [0mself[0m[0;34m.[0m[0mbias[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 104[0m [0;34m[0m[0m [1;32m 105[0m [0;32mdef[0m [0mextra_repr[0m[0;34m([0m[0mself[0m[0;34m)[0m [0;34m->[0m [0mstr[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py[0m in [0;36mlinear[0;34m(input, weight, bias)[0m [1;32m 1846[0m [0;32mif[0m [0mhas_torch_function_variadic[0m[0;34m([0m[0minput[0m[0;34m,[0m [0mweight[0m[0;34m,[0m [0mbias[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [1;32m 1847[0m [0;32mreturn[0m [0mhandle_torch_function[0m[0;34m([0m[0mlinear[0m[0;34m,[0m [0;34m([0m[0minput[0m[0;34m,[0m [0mweight[0m[0;34m,[0m [0mbias[0m[0;34m)[0m[0;34m,[0m [0minput[0m[0;34m,[0m [0mweight[0m[0;34m,[0m [0mbias[0m[0;34m=[0m[0mbias[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0;32m-> 1848[0;31m [0;32mreturn[0m [0mtorch[0m[0;34m.[0m[0m_C[0m[0;34m.[0m[0m_nn[0m[0;34m.[0m[0mlinear[0m[0;34m([0m[0minput[0m[0;34m,[0m [0mweight[0m[0;34m,[0m [0mbias[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 1849[0m [0;34m[0m[0m [1;32m 1850[0m [0;34m[0m[0m [0;31mRuntimeError[0m: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_addmm)
In [ ]:
# Plot decision boundaries for training and test sets
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.title("Train")
plot_decision_boundary(model_1, X_train, y_train) # model_1 = no non-linearity
plt.subplot(1, 2, 2)
plt.title("Test")
plot_decision_boundary(model_3, X_test, y_test) # model_3 = has non-linearityIn [ ]:
import torch
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
NUM_CLASSES = 4
NUM_FEATURES = 2
RANDOM_SEED = 42
# Create data
X_blob, y_blob = make_blobs(n_samples=1000,
n_features=NUM_FEATURES,
centers=NUM_CLASSES,
cluster_std=1.5,
random_state=RANDOM_SEED
)
# Turn into tensors
X_blob = torch.from_numpy(X_blob).type(torch.float)
y_blob = torch.from_numpy(y_blob).type(torch.LongTensor)
print(X_blob[:5], y_blob[:5])
# Split into train and test
X_blob_train, X_blob_test, y_blob_train, y_blob_test = train_test_split(X_blob,
y_blob,
test_size=0.2,
random_state=RANDOM_SEED
)
# Plot data
plt.figure(figsize=(10, 7))
plt.scatter(X_blob[:, 0], X_blob[:, 1], c=y_blob, cmap=plt.cm.RdYlBu);tensor([[-8.4134, 6.9352],
[-5.7665, -6.4312],
[-6.0421, -6.7661],
[ 3.9508, 0.6984],
[ 4.2505, -0.2815]]) tensor([3, 2, 2, 1, 1])
In [ ]:
from torch import nn
# Build model
class BlobModel(nn.Module):
def __init__(self, input_features, output_features, hidden_units):
super().__init__()
self.linear_layer_stack = nn.Sequential(
nn.Linear(in_features=input_features, out_features=hidden_units),
# nn.ReLU(),
nn.Linear(in_features=hidden_units, out_features=hidden_units),
# nn.ReLU(),
nn.Linear(in_features=hidden_units, out_features=output_features), # how many classes are there?
)
def forward(self, x):
return self.linear_layer_stack(x)
model_4 = BlobModel(input_features=NUM_FEATURES,
output_features=NUM_CLASSES,
hidden_units=8) # doesn't work with 1, try a different value
model_4BlobModel(
(linear_layer_stack): Sequential(
(0): Linear(in_features=2, out_features=8, bias=True)
(1): Linear(in_features=8, out_features=8, bias=True)
(2): Linear(in_features=8, out_features=4, bias=True)
)
)In [ ]:
# Loss and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model_4.parameters(), lr=0.1)In [ ]:
# Fit the model
torch.manual_seed(42)
epochs = 100
for epoch in range(epochs):
# 1. Forward pass
y_pred = model_4(X_blob_train)
# 2. Calculate loss and accuracy
loss = loss_fn(y_pred, y_blob_train)
acc = accuracy_fn(y_true=y_blob_train,
y_pred=y_pred.argmax(dim=1))
# 3. Optimizer zero grad
optimizer.zero_grad()
# 4. Loss backwards
loss.backward()
# 5. Optimizer step
optimizer.step()
# Print out what's happening
if epoch % 10 == 0:
print(f"Epoch: {epoch} | Loss: {loss:.5f}, Accuracy: {acc:.2f}%")Epoch: 0 | Loss: 1.04324, Accuracy: 65.50% Epoch: 10 | Loss: 0.14398, Accuracy: 99.12% Epoch: 20 | Loss: 0.08062, Accuracy: 99.12% Epoch: 30 | Loss: 0.05924, Accuracy: 99.12% Epoch: 40 | Loss: 0.04892, Accuracy: 99.00% Epoch: 50 | Loss: 0.04295, Accuracy: 99.00% Epoch: 60 | Loss: 0.03910, Accuracy: 99.00% Epoch: 70 | Loss: 0.03643, Accuracy: 99.00% Epoch: 80 | Loss: 0.03448, Accuracy: 99.00% Epoch: 90 | Loss: 0.03300, Accuracy: 99.12%
In [ ]:
# Make predictions
model_4.eval()
with torch.inference_mode():
y_preds = model_4(X_blob_test)In [ ]:
# TODO: Show the outputs of the model - what do these mean?
y_preds[:10]tensor([[ 4.3377, 10.3539, -14.8948, -9.7642],
[ 5.0142, -12.0371, 3.3860, 10.6699],
[ -5.5885, -13.3448, 20.9894, 12.7711],
[ 1.8400, 7.5599, -8.6016, -6.9942],
[ 8.0727, 3.2906, -14.5998, -3.6186],
[ 5.5844, -14.9521, 5.0168, 13.2891],
[ -5.9739, -10.1913, 18.8655, 9.9179],
[ 7.0755, -0.7601, -9.5531, 0.1736],
[ -5.5918, -18.5990, 25.5310, 17.5799],
[ 7.3142, 0.7197, -11.2017, -1.2011]])In [ ]:
# TODO: Softmax = obtain probabilities, no softmax = logits from model
print(torch.softmax(y_preds, dim=1).argmax(dim=1)[:10], y_preds.argmax(dim=1)[:10])
print(f"Test accuracy: {accuracy_fn(y_true=y_blob_test, y_pred=y_preds.argmax(dim=1))}%")tensor([1, 3, 2, 1, 0, 3, 2, 0, 2, 0]) tensor([1, 3, 2, 1, 0, 3, 2, 0, 2, 0]) Test accuracy: 99.5%
In [ ]:
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.title("Train")
plot_decision_boundary(model_4, X_blob_train, y_blob_train)
plt.subplot(1, 2, 2)
plt.title("Test")
plot_decision_boundary(model_4, X_blob_test, y_blob_test)