Training of CNN - ( Convolutional Neural Network in PyTorch )
Heading h2
Syntax
import torch.nn as nn
import torch.optim as optim
model = MyCNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
Example
import torch
import torch.nn as nn
import torch.optim as optim
# Define the CNN model
class MyCNN(nn.Module):
def __init__(self):
super(MyCNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, stride=1, padding=1)
self.conv2 = nn.Conv2d(32, 64, 3, stride=1, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(64 * 7 * 7, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.pool(torch.relu(self.conv1(x)))
x = self.pool(torch.relu(self.conv2(x)))
x = x.view(-1, 64 * 7 * 7)
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# Instantiate the model
model = MyCNN()
# Define the loss criterion and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
Output
MyCNN(
(conv1): Conv2d(1, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(fc1): Linear(in_features=3136, out_features=128, bias=True)
(fc2): Linear(in_features=128, out_features=10, bias=True)
)
Explanation
Training a Convolutional Neural Network (CNN) in PyTorch involves defining the model architecture, specifying the loss criterion and optimizer, and iterating over the training data.
In the example above, we defined a simple CNN architecture called MyCNN
that consists of two convolutional layers, two max pooling layers, and two fully connected layers. We then instantiated the model, defined a cross entropy loss criterion, and used the Adam optimizer to optimize the model parameters during training.
Use
Training a CNN in PyTorch is useful for a wide range of computer vision tasks, such as image classification, object detection, and segmentation. The process of training a CNN involves feeding input images through the model, computing the loss between the predicted and actual labels, and updating the model parameters to minimize the loss.
Important Points
- Training a CNN in PyTorch involves defining the model architecture, loss criterion, and optimizer
- PyTorch provides various built-in loss functions and optimizers for training neural networks
- The goal of training a CNN is to minimize the loss between predicted and actual labels by updating the model parameters during training
Summary
In conclusion, training a Convolutional Neural Network in PyTorch involves defining the CNN architecture, loss criterion, and optimizer, and iterating over the training data to update the model parameters. PyTorch provides a variety of built-in loss functions and optimizers that can be used for training neural networks on a range of computer vision tasks.