mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
797 KiB
797 KiB
In [ ]:
import sklearnIn [ ]:
from sklearn.datasets import make_circles
# Make 1000 samples
n_samples = 1000
# Create circles
X, y = make_circles(n_samples,
noise=0.03,
random_state=42)In [ ]:
len(X), len(y)(1000, 1000)
In [ ]:
print(f"First 5 samples of X:\n {X[:5]}")
print(f"First 5 samples of y:\n {y[:5]}")First 5 samples of X: [[ 0.75424625 0.23148074] [-0.75615888 0.15325888] [-0.81539193 0.17328203] [-0.39373073 0.69288277] [ 0.44220765 -0.89672343]] First 5 samples of y: [1 1 1 1 0]
In [ ]:
# Make DataFrame of circle data
import pandas as pd
circles = pd.DataFrame({"X1": X[:, 0],
"X2": X[:, 1],
"label": y})
circles.head(10)| 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 [ ]:
circles.label.value_counts() 1 500 0 500 Name: label, dtype: int64
In [ ]:
# Visualize, visualize, visualize
import matplotlib.pyplot as plt
plt.scatter(x=X[:, 0],
y=X[:, 1],
c=y,
cmap=plt.cm.RdYlBu);In [ ]:
X.shape, y.shape((1000, 2), (1000,))
In [ ]:
Xarray([[ 0.75424625, 0.23148074],
[-0.75615888, 0.15325888],
[-0.81539193, 0.17328203],
...,
[-0.13690036, -0.81001183],
[ 0.67036156, -0.76750154],
[ 0.28105665, 0.96382443]])In [ ]:
# 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 [ ]:
import torch
torch.__version__'1.10.0+cu111'
In [ ]:
type(X), X.dtype(numpy.ndarray, dtype('float64'))In [ ]:
# Turn data into tensors
X = torch.from_numpy(X).type(torch.float)
y = torch.from_numpy(y).type(torch.float)
X[:5], y[:5](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 [ ]:
type(X), X.dtype, y.dtype(torch.Tensor, torch.float32, torch.float32)
In [ ]:
# Split data into training 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, # 0.2 = 20% of data will be test & 80% will be train
random_state=42) In [ ]:
len(X_train), len(X_test), len(y_train), len(y_test)(800, 200, 800, 200)
In [ ]:
n_samples1000
In [ ]:
# Import PyTorch and nn
import torch
from torch import nn
# Make device agnostic code
device = "cuda" if torch.cuda.is_available() else "cpu"
device'cuda'
In [ ]:
X_traintensor([[ 0.6579, -0.4651],
[ 0.6319, -0.7347],
[-1.0086, -0.1240],
...,
[ 0.0157, -1.0300],
[ 1.0110, 0.1680],
[ 0.5578, -0.5709]])In [ ]:
X_train.shapetorch.Size([800, 2])
In [ ]:
y_train[:5]tensor([1., 0., 0., 0., 1.])
In [ ]:
from sklearn import datasets
# 1. Construct a model that subclasses nn.Module
class CircleModelV0(nn.Module):
def __init__(self):
super().__init__()
# 2. Create 2 nn.Linear layers capable of handling the shapes of our data
self.layer_1 = nn.Linear(in_features=2, out_features=5) # takes in 2 features and upscales to 5 features
self.layer_2 = nn.Linear(in_features=5, out_features=1) # takes in 5 features from previous layer and outputs a single feature (same shape as y)
# 3. Define a forward() method that outlines the forward pass
def forward(self, x):
return self.layer_2(self.layer_1(x)) # x -> layer_1 -> layer_2 -> output
# 4. Instantiate an instance of our model class and send it to the target device
model_0 = CircleModelV0().to(device)
model_0CircleModelV0( (layer_1): Linear(in_features=2, out_features=5, bias=True) (layer_2): Linear(in_features=5, out_features=1, bias=True) )
In [ ]:
device'cuda'
In [ ]:
next(model_0.parameters()).devicedevice(type='cuda', index=0)
In [ ]:
# Let's replicate the model above using 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_0Sequential( (0): Linear(in_features=2, out_features=5, bias=True) (1): Linear(in_features=5, out_features=1, bias=True) )
In [ ]:
model_0.state_dict()OrderedDict([('0.weight', tensor([[-0.1962, 0.3652],
[ 0.2764, 0.2147],
[ 0.5723, -0.5955],
[-0.2329, 0.0170],
[ 0.6259, 0.6916]], device='cuda:0')),
('0.bias',
tensor([ 0.4193, 0.6624, 0.2594, -0.1640, -0.0477], device='cuda:0')),
('1.weight',
tensor([[ 0.4129, 0.2358, 0.4115, 0.4045, -0.0853]], device='cuda:0')),
('1.bias', tensor([-0.4294], device='cuda:0'))])In [ ]:
# Make predictions
with torch.inference_mode():
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(X_test)}, Shape: {X_test.shape}")
print(f"\nFirst 10 predictions:\n{torch.round(untrained_preds[:10])}")
print(f"\nFirst 10 labels:\n{y_test[:10]}")Length of predictions: 200, Shape: torch.Size([200, 1])
Length of test samples: 200, Shape: torch.Size([200, 2])
First 10 predictions:
tensor([[-0.],
[-0.],
[-0.],
[-0.],
[0.],
[0.],
[-0.],
[-0.],
[-0.],
[-0.]], device='cuda:0')
First 10 labels:
tensor([1., 0., 1., 0., 1., 1., 0., 0., 1., 0.])
In [ ]:
X_test[:10], y_test[:10](tensor([[-0.3752, 0.6827],
[ 0.0154, 0.9600],
[-0.7028, -0.3147],
[-0.2853, 0.9664],
[ 0.4024, -0.7438],
[ 0.6323, -0.5711],
[ 0.8561, 0.5499],
[ 1.0034, 0.1903],
[-0.7489, -0.2951],
[ 0.0538, 0.9739]]),
tensor([1., 0., 1., 0., 1., 1., 0., 0., 1., 0.]))In [ ]:
# Setup the loss function
# loss_fn = nn.BCELoss() # BCELoss = requires inputs to have gone through the sigmoid activation function prior to input to BCELoss
loss_fn = nn.BCEWithLogitsLoss() # BCEWithLogitsLoss = sigmoid activation function built-in
optimizer = torch.optim.SGD(params=model_0.parameters(),
lr=0.1)In [ ]:
# Calculate accuracy - out of 100 examples, what percentage does our model get right?
def accuracy_fn(y_true, y_pred):
correct = torch.eq(y_true, y_pred).sum().item()
acc = (correct/len(y_pred)) * 100
return accIn [ ]:
# View the first 5 outputs of the forward pass on the test data
model_0.eval()
with torch.inference_mode():
y_logits = model_0(X_test.to(device))[:5]
y_logits tensor([[-0.1481],
[-0.1465],
[-0.0762],
[-0.1688],
[ 0.0445]], device='cuda:0')In [ ]:
y_test[:5]tensor([1., 0., 1., 0., 1.])
In [ ]:
# Use the sigmoid activation function on our model logits to turn them into prediction probabilities
y_pred_probs = torch.sigmoid(y_logits)
y_pred_probstensor([[0.4630],
[0.4634],
[0.4810],
[0.4579],
[0.5111]], device='cuda:0')In [ ]:
# Find the predicted labels
y_preds = torch.round(y_pred_probs)
# In full (logits -> pred probs -> pred labels)
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()tensor([True, True, True, True, True], device='cuda:0')
tensor([0., 0., 0., 0., 1.], device='cuda:0')
In [ ]:
y_test[:5]tensor([1., 0., 1., 0., 1.])
In [ ]:
torch.manual_seed(42)
torch.cuda.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
y_logits = model_0(X_train).squeeze()
y_pred = torch.round(torch.sigmoid(y_logits)) # turn logits -> pred probs -> pred labels
# 2. Calculate loss/accuracy
# loss = loss_fn(torch.sigmoid(y_logits), # nn.BCELoss expects prediction probabilities as input
# y_train)
loss = loss_fn(y_logits, # nn.BCEWithLogitsLoss expects raw logits as input
y_train)
acc = accuracy_fn(y_true=y_train,
y_pred=y_pred)
# 3. Optimizer zero grad
optimizer.zero_grad()
# 4. Loss backward (backpropagation)
loss.backward()
# 5. Optimizer step (gradient descent)
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. Calculate test loss/acc
test_loss = loss_fn(test_logits,
y_test)
test_acc = accuracy_fn(y_true=y_test,
y_pred=test_pred)
# Print out what's happenin'
if epoch % 10 == 0:
print(f"Epoch: {epoch} | Loss: {loss:.5f}, Acc: {acc:.2f}% | Test loss: {test_loss:.5f}, Test acc: {test_acc:.2f}%")Epoch: 0 | Loss: 0.69461, Acc: 47.88% | Test loss: 0.69301, Test acc: 48.50% Epoch: 10 | Loss: 0.69402, Acc: 48.75% | Test loss: 0.69296, Test acc: 48.00% Epoch: 20 | Loss: 0.69369, Acc: 49.50% | Test loss: 0.69308, Test acc: 46.50% Epoch: 30 | Loss: 0.69348, Acc: 50.62% | Test loss: 0.69325, Test acc: 45.50% Epoch: 40 | Loss: 0.69334, Acc: 50.12% | Test loss: 0.69341, Test acc: 48.50% Epoch: 50 | Loss: 0.69324, Acc: 49.25% | Test loss: 0.69357, Test acc: 51.00% Epoch: 60 | Loss: 0.69317, Acc: 49.50% | Test loss: 0.69372, Test acc: 50.50% Epoch: 70 | Loss: 0.69312, Acc: 50.38% | Test loss: 0.69385, Test acc: 49.00% Epoch: 80 | Loss: 0.69308, Acc: 50.12% | Test loss: 0.69396, Test acc: 49.50% Epoch: 90 | Loss: 0.69305, Acc: 50.50% | Test loss: 0.69406, Test acc: 48.00%
In [ ]:
import requests
from pathlib import Path
# Download helper functions from Learn PyTorch repo (if it's not already downloaded)
if Path("helper_functions.py").is_file():
print("helper_functions.py already exists, skipping download")
else:
print("Downloading helper_functions.py")
request = requests.get("https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/helper_functions.py")
with open("helper_functions.py", "wb") as f:
f.write(request.content)
from helper_functions import plot_predictions, plot_decision_boundaryDownloading helper_functions.py
In [ ]:
# Plot decision boundary of the model
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 [ ]:
X_train[:5], y_train[:5](tensor([[ 0.6579, -0.4651],
[ 0.6319, -0.7347],
[-1.0086, -0.1240],
[-0.9666, -0.2256],
[-0.1666, 0.7994]], device='cuda:0'),
tensor([1., 0., 0., 0., 1.], device='cuda:0'))In [ ]:
# Create a model
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)
self.layer_3 = nn.Linear(in_features=10, out_features=1)
def forward(self, x):
# z = self.layer_1(x)
# z = self.layer_2(z)
# z = self.layer_3(z)
return self.layer_3(self.layer_2(self.layer_1(x))) # this way of writing operations leverages speed ups where possible behind the scenes
model_1 = CircleModelV1().to(device)
model_1CircleModelV1( (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 [ ]:
# Create a loss function
loss_fn = nn.BCEWithLogitsLoss()
# Create an optimizer
optimizer = torch.optim.SGD(params=model_1.parameters(),
lr=0.1)In [ ]:
# Write a training and evaluation loop for model_1
torch.manual_seed(42)
torch.cuda.manual_seed(42)
# Train for longer
epochs = 1000
# Put data on the 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
model_1.train()
# 1. Forward pass
y_logits = model_1(X_train).squeeze()
y_pred = torch.round(torch.sigmoid(y_logits)) # logits -> pred probabilities -> prediction labels
# 2. Calculate the loss/acc
loss = loss_fn(y_logits, y_train)
acc = accuracy_fn(y_true=y_train,
y_pred=y_pred)
# 3. Optimizer zero grad
optimizer.zero_grad()
# 4. Loss backward (backpropagation)
loss.backward()
# 5. Optimizer step (gradient descent)
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. Calculate loss
test_loss = loss_fn(test_logits,
y_test)
test_acc = accuracy_fn(y_true=y_test,
y_pred=test_pred)
# Print out what's happenin'
if epoch % 100 == 0:
print(f"Epoch: {epoch} | Loss: {loss:.5f}, Acc: {acc:.2f}% | Test loss: {test_loss:.5f}, Test acc: {test_acc:.2f}%")Epoch: 0 | Loss: 0.69396, Acc: 50.88% | Test loss: 0.69261, Test acc: 51.00% Epoch: 100 | Loss: 0.69305, Acc: 50.38% | Test loss: 0.69379, Test acc: 48.00% Epoch: 200 | Loss: 0.69299, Acc: 51.12% | Test loss: 0.69437, Test acc: 46.00% Epoch: 300 | Loss: 0.69298, Acc: 51.62% | Test loss: 0.69458, Test acc: 45.00% Epoch: 400 | Loss: 0.69298, Acc: 51.12% | Test loss: 0.69465, Test acc: 46.00% Epoch: 500 | Loss: 0.69298, Acc: 51.00% | Test loss: 0.69467, Test acc: 46.00% Epoch: 600 | Loss: 0.69298, Acc: 51.00% | Test loss: 0.69468, Test acc: 46.00% Epoch: 700 | Loss: 0.69298, Acc: 51.00% | Test loss: 0.69468, Test acc: 46.00% Epoch: 800 | Loss: 0.69298, Acc: 51.00% | Test loss: 0.69468, Test acc: 46.00% Epoch: 900 | Loss: 0.69298, Acc: 51.00% | Test loss: 0.69468, Test acc: 46.00%
In [ ]:
# Plot decision boundary of the model
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 [ ]:
# Create some data (same as notebook 01)
weight = 0.7
bias = 0.3
start = 0
end = 1
step = 0.01
# Create data
X_regression = torch.arange(start, end, step).unsqueeze(dim=1)
y_regression = weight * X_regression + bias # Linear regression formula (without epsilon)
# Check the data
print(len(X_regression))
X_regression[:5], y_regression[:5]100
(tensor([[0.0000],
[0.0100],
[0.0200],
[0.0300],
[0.0400]]), tensor([[0.3000],
[0.3070],
[0.3140],
[0.3210],
[0.3280]]))In [ ]:
# Create train and test splits
train_split = int(0.8 * len(X_regression))
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:]
# Check the lengths of each
len(X_train_regression), len(X_test_regression), len(y_train_regression), len(y_test_regression)(80, 20, 80, 20)
In [ ]:
plot_predictions(train_data=X_train_regression,
train_labels=y_train_regression,
test_data=X_test_regression,
test_labels=y_test_regression);In [ ]:
# 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)
).to(device)
model_2Sequential( (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 [ ]:
# Loss and optimizer
loss_fn = nn.L1Loss() # MAE loss with regression data
optimizer = torch.optim.SGD(params=model_2.parameters(),
lr=0.01)In [ ]:
# Train the model
torch.manual_seed(42)
torch.cuda.manual_seed(42)
# Set the number of epochs
epochs = 1000
# Put the data on the target device
X_train_regression, y_train_regression = X_train_regression.to(device), y_train_regression.to(device)
X_test_regression, y_test_regression = X_test_regression.to(device), y_test_regression.to(device)
# Training
for epoch in range(epochs):
y_pred = model_2(X_train_regression)
loss = loss_fn(y_pred, y_train_regression)
optimizer.zero_grad()
loss.backward()
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 happenin'
if epoch % 100 == 0:
print(f"Epoch: {epoch} | Loss: {loss:.5f} | Test loss: {test_loss:.5f}")Epoch: 0 | Loss: 0.75986 | Test loss: 0.91103 Epoch: 100 | Loss: 0.02858 | Test loss: 0.00081 Epoch: 200 | Loss: 0.02533 | Test loss: 0.00209 Epoch: 300 | Loss: 0.02137 | Test loss: 0.00305 Epoch: 400 | Loss: 0.01964 | Test loss: 0.00341 Epoch: 500 | Loss: 0.01940 | Test loss: 0.00387 Epoch: 600 | Loss: 0.01903 | Test loss: 0.00379 Epoch: 700 | Loss: 0.01878 | Test loss: 0.00381 Epoch: 800 | Loss: 0.01840 | Test loss: 0.00329 Epoch: 900 | Loss: 0.01798 | Test loss: 0.00360
In [ ]:
# Turn on evaluation mode
model_2.eval()
# Make predictions (inference)
with torch.inference_mode():
y_preds = model_2(X_test_regression)
# Plot data and predictions
plot_predictions(train_data=X_train_regression.cpu(),
train_labels=y_train_regression.cpu(),
test_data=X_test_regression.cpu(),
test_labels=y_test_regression.cpu(),
predictions=y_preds.cpu()); In [ ]:
# Make and plot data
import matplotlib.pyplot as plt
from sklearn.datasets import make_circles
n_samples = 1000
X, y = make_circles(n_samples,
noise=0.03,
random_state=42)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.RdYlBu);In [ ]:
# Convert data to tensors and then to train and test splits
import torch
from sklearn.model_selection import train_test_split
# Turn data into tensors
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](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 [ ]:
# Build a model with non-linear activation functions
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() # relu is a non-linear activation function
def forward(self, x):
# Where should we put our non-linear activation functions?
return self.layer_3(self.relu(self.layer_2(self.relu(self.layer_1(x)))))
model_3 = CircleModelV2().to(device)
model_3CircleModelV2( (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 [ ]:
# Setup loss and optimizer
loss_fn = nn.BCEWithLogitsLoss()
optimizer = torch.optim.SGD(model_3.parameters(),
lr=0.1)In [ ]:
len(X_test), len(y_test)(200, 200)
In [ ]:
# Random seeds
torch.manual_seed(42)
torch.cuda.manual_seed(42)
# Put all data on 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)
# Loop through data
epochs = 1000
for epoch in range(epochs):
### Training
model_3.train()
# 1. Forward pass
y_logits = model_3(X_train).squeeze()
y_pred = torch.round(torch.sigmoid(y_logits)) # logits -> prediction probabilities -> prediction labels
# 2. Calculate the loss
loss = loss_fn(y_logits, y_train) # BCEWithLogitsLoss (takes in logits as first input)
acc = accuracy_fn(y_true=y_train,
y_pred=y_pred)
# 3. Optimizer zero grad
optimizer.zero_grad()
# 4. Loss backward
loss.backward()
# 5. Step the optimizer
optimizer.step()
### Testing
model_3.eval()
with torch.inference_mode():
test_logits = model_3(X_test).squeeze()
test_pred = torch.round(torch.sigmoid(test_logits))
test_loss = loss_fn(test_logits, y_test)
test_acc = accuracy_fn(y_true=y_test,
y_pred=test_pred)
# Print out what's this happenin'
if epoch % 100 == 0:
print(f"Epoch: {epoch} | Loss: {loss:.4f}, Acc: {acc:.2f}% | Test Loss: {test_loss:.4f}, Test Acc: {test_acc:.2f}%")Epoch: 0 | Loss: 0.6928, Acc: 50.00% | Test Loss: 0.6931, Test Acc: 50.00% Epoch: 100 | Loss: 0.6911, Acc: 53.12% | Test Loss: 0.6910, Test Acc: 53.00% Epoch: 200 | Loss: 0.6897, Acc: 53.50% | Test Loss: 0.6894, Test Acc: 55.50% Epoch: 300 | Loss: 0.6879, Acc: 53.00% | Test Loss: 0.6872, Test Acc: 56.00% Epoch: 400 | Loss: 0.6851, Acc: 52.75% | Test Loss: 0.6840, Test Acc: 56.50% Epoch: 500 | Loss: 0.6809, Acc: 52.75% | Test Loss: 0.6793, Test Acc: 56.50% Epoch: 600 | Loss: 0.6750, Acc: 54.62% | Test Loss: 0.6727, Test Acc: 56.50% Epoch: 700 | Loss: 0.6664, Acc: 58.38% | Test Loss: 0.6630, Test Acc: 59.50% Epoch: 800 | Loss: 0.6512, Acc: 64.25% | Test Loss: 0.6472, Test Acc: 68.00% Epoch: 900 | Loss: 0.6228, Acc: 74.00% | Test Loss: 0.6208, Test Acc: 79.00%
In [ ]:
# Makes predictions
model_3.eval()
with torch.inference_mode():
y_preds = torch.round(torch.sigmoid(model_3(X_test))).squeeze()
y_preds[:10], y_test[:10](tensor([1., 0., 1., 0., 0., 1., 0., 0., 1., 0.], device='cuda:0'), tensor([1., 0., 1., 0., 1., 1., 0., 0., 1., 0.], device='cuda:0'))
In [ ]:
# Plot decision boundaries
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 [ ]:
# Create a tensor
A = torch.arange(-10, 10, 1, dtype=torch.float32)
A.dtypetorch.float32
In [ ]:
Atensor([-10., -9., -8., -7., -6., -5., -4., -3., -2., -1., 0., 1.,
2., 3., 4., 5., 6., 7., 8., 9.])In [ ]:
# Visualize the tensor
plt.plot(A); In [ ]:
plt.plot(torch.relu(A));In [ ]:
Atensor([-10., -9., -8., -7., -6., -5., -4., -3., -2., -1., 0., 1.,
2., 3., 4., 5., 6., 7., 8., 9.])In [ ]:
def relu(x: torch.Tensor) -> torch.Tensor:
return torch.maximum(torch.tensor(0), x) # inputs must be tensors
relu(A)tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 2., 3., 4., 5., 6., 7.,
8., 9.])In [ ]:
# Plot ReLU activation function
plt.plot(relu(A)); In [ ]:
# Now let's do the same for Sigmoid = https://pytorch.org/docs/stable/generated/torch.nn.Sigmoid.html#torch.nn.Sigmoid
def sigmoid(x):
return 1 / (1 + torch.exp(-x))In [ ]:
plt.plot(torch.sigmoid(A)); In [ ]:
plt.plot(sigmoid(A));In [ ]:
# Import dependencies
import torch
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs # https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_blobs.html#sklearn.datasets.make_blobs
from sklearn.model_selection import train_test_split
# Set the hyperparameters for data creation
NUM_CLASSES = 4
NUM_FEATURES = 2
RANDOM_SEED = 42
# 1. Create multi-class data
X_blob, y_blob = make_blobs(n_samples=1000,
n_features=NUM_FEATURES,
centers=NUM_CLASSES,
cluster_std=1.5, # give the clusters a little shake up
random_state=RANDOM_SEED)
# 2. Turn data into tensors
X_blob = torch.from_numpy(X_blob).type(torch.float)
y_blob = torch.from_numpy(y_blob).type(torch.LongTensor)
# 3. 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)
# 4. Plot data (visualize, visualize, visualize)
plt.figure(figsize=(10, 7))
plt.scatter(X_blob[:, 0], X_blob[:, 1], c=y_blob, cmap=plt.cm.RdYlBu);In [ ]:
# Create device agnostic code
device = "cuda" if torch.cuda.is_available() else "cpu"
device'cuda'
In [ ]:
# Build a multi-class classification model
class BlobModel(nn.Module):
def __init__(self, input_features, output_features, hidden_units=8):
"""Initializes multi-class classification model.
Args:
input_features (int): Number of input features to the model
output_features (int): Number of outputs features (number of output classes)
hidden_units (int): Number of hidden units between layers, default 8
Returns:
Example:
"""
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)
)
def forward(self, x):
return self.linear_layer_stack(x)
# Create an instance of BlobModel and send it to the target device
model_4 = BlobModel(input_features=2,
output_features=4,
hidden_units=8).to(device)
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 [ ]:
X_blob_train.shape, y_blob_train[:5](torch.Size([800, 2]), tensor([1, 0, 2, 2, 0], device='cuda:0'))
In [ ]:
torch.unique(y_blob_train)tensor([0, 1, 2, 3], device='cuda:0')
Warning:
Output truncated. This notebook contains too many cells to display efficiently.