Intro To PyTorch and Neural Networks - Intro To PyTorch and Neural Networks Cheatsheet - Codecademy
Intro To PyTorch and Neural Networks - Intro To PyTorch and Neural Networks Cheatsheet - Codecademy
PyTorch Library
y = mx + b
Here,
y is the target output
x is the input feature
m is the weight for x
b is the bias
The ReLU activation function returns 0 for negative # by hand definition of ReLU
input values, otherwise it returns nonnegative values
def ReLU(x):
unchanged.
For example, return max(0,x)
ReLU(-1) returns 0 since -1 is negative
ReLU(3) returns 3 since 3 is nonnegative
# ReLU in PyTorch
ReLU can be implemented in PyTorch with nn.ReLU
from torch import nn
from the torch.nn module.
ReLU = nn.ReLU()
Loss Functions
The most common loss function for regression tasks is # Implement MSE in PyTorch
the Mean Squared Error (MSE) which is computed by
import torch.nn as nn
computing the difference from each prediction to
the actual value loss = nn.MSELoss()
squaring each difference MSE = loss(predictions, y)
computing the mean of the squared differences
Notably, MSE emphasizes the largest differences which
can be helpful but may lead to overfitting.
The Optimizer
When training a neural network, optimizers are from torch import optim
algorithms used to adjust the weights and biases of the
neural network. The goal of an optimizer is to decrease
the loss of the network.
PyTorch implements many common optimizer algorithms
in its optim module.
Learning Rate
Training a neural network is an iterative process of: # Training loop with 400 iterations
performing the forward pass to generate target
num_epochs = 400
predictions
computing the loss between the predictions and for epoch in range(num_epochs):
the actual target values predictions = model(X) # forward pass
running a backward pass to compute gradients
MSE = loss(predictions,y) # compute
applying the optimizer to adjust the weights and
biases loss
resetting the gradients for the next iteration MSE.backward() # compute gradients
Each iteration in this loop is called an epoch.
optimizer.step() # update weights and
biases
optimizer.zero_grad() # reset the
gradients
Saving and Loading PyTorch Models
Neural network classes can be constructed using object- # Creating a Neural Network Class Using
oriented programming (OOP) with the PyTorch subclass
OOP
nn.Module . This requires explicitly defining the
init method to initialize the network components and class NN_Regression(nn.Module):
the forward method to design the forward pass. def __init__(self):
Constructing networks as classes gives developers
super(NN_Regression, self).__init__()
increased flexibility and control over pre-built sequential
models using nn.Sequential while still inheriting
# Initialize layers and activation
PyTorch’s built-in training and optimization libraries. functions
..
Print Share