Build a Simple CNN with PyTorch
2026A basic Convolutional Neural Network (CNN) architecture for image classification (e.g., FashionMNIST) typically involves:
- Convolutional Layers:
nn.Conv2dto extract features. - Activation Functions:
nn.ReLUto introduce non-linearity. - Pooling Layers:
nn.MaxPool2dto reduce spatial dimensions. - Flattening:
nn.Flattento transition from 2D feature maps to 1D vectors. - Fully Connected Layers:
nn.Linearfor final classification.
import torch
import torch.nn as nn
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1)
self.relu1 = nn.ReLU()
self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
self.relu2 = nn.ReLU()
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.flatten = nn.Flatten()
self.fc1 = nn.Linear(64 * 7 * 7, 128)
self.relu3 = nn.ReLU()
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.pool1(self.relu1(self.conv1(x)))
x = self.pool2(self.relu2(self.conv2(x)))
x = self.flatten(x)
x = self.relu3(self.fc1(x))
x = self.fc2(x)
return x