Safe lab preview
Conv Nets Py Torch
This is a sanitized, read-only preview. Nothing executes in this page.
Read-only
Notebook preview
Conv Nets Py Torch
> **Integrated runtime note:** This preview uses a small deterministic, rights-safe offline fixture for reproducible learning. Full-scale results require the lesson's documented dataset or model in an approved external environment.
# Convolutional neural networks
In the previous unit we have learned how to define a multi-layered neural network using class definition, but those networks were generic, and not specialized for computer vision tasks. In this unit we will learn about **Convolutional Neural Networks (CNNs)**, which are specifically designed for computer vision.
Computer vision is different from generic classification, because when we are trying to find a certain object in the picture, we are scanning the image looking for some specific **patterns** and their combinations. For example, when looking for a cat, we first may look for horizontal lines, which can form whiskers, and then certain combination of whiskers can tell us that it is actually a picture of a cat. Relative position and presence of certain patterns is important, and not their exact position on the image.
To extract patterns, we will use the notion of **convolutional filters**. But first, let us load all dependencies and functions that we have defined in the previous units.
import torch
import torch.nn as nn
import torchvision
import matplotlib.pyplot as plt
from torchinfo import summary
import numpy as np
# Self-contained course PyTorch computer-vision helpers.
from torchvision.transforms import ToTensor
from sklearn.datasets import load_digits
from PIL import Image
import glob
default_device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def load_mnist(batch_size=64):
global data_train, data_test, train_loader, test_loader
course_digits = load_digits()
images = torch.as_tensor(course_digits.images, dtype=torch.float32).unsqueeze(1) / 16.0
images = torch.nn.functional.interpolate(images, size=(28, 28), mode="bilinear", align_corners=False)
labels = torch.as_tensor(course_digits.target, dtype=torch.long)
split = int(0.8 * len(images))
data_train = torch.utils.data.TensorDataset(images[:split], labels[:split])
data_test = torch.utils.data.TensorDataset(images[split:], labels[split:])
train_loader = torch.utils.data.DataLoader(data_train, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(data_test, batch_size=batch_size)
return data_train, data_test
def _validate(net, dataloader, loss_fn):
net.eval()
total_loss, correct, count = 0.0, 0, 0
with torch.no_grad():
for features, labels in dataloader:
features, labels = features.to(default_device), labels.to(default_device)
output = net(features)
total_loss += loss_fn(output, labels).item() * len(labels)
correct += (output.argmax(1) == labels).sum().item()
count += len(labels)
return total_loss / max(count, 1), correct / max(count, 1)
def train(net, train_loader, test_loader, optimizer=None, lr=0.01, epochs=10, loss_fn=None):
net.to(default_device)
loss_fn = loss_fn or nn.CrossEntropyLoss()
optimizer = optimizer or torch.optim.Adam(net.parameters(), lr=lr)
history = {"train_loss": [], "train_acc": [], "val_loss": [], "val_acc": []}
for epoch in range(epochs):
net.train()
total_loss, correct, count = 0.0, 0, 0
for features, labels in train_loader:
features, labels = features.to(default_device), labels.to(default_device)
optimizer.zero_grad()
output = net(features)
loss = loss_fn(output, labels)
loss.backward()
optimizer.step()
total_loss += loss.item() * len(labels)
correct += (output.argmax(1) == labels).sum().item()
count += len(labels)
validation_loss, validation_accuracy = _validate(net, test_loader, loss_fn)
history["train_loss"].append(total_loss / max(count, 1))
history["train_acc"].append(correct / max(count, 1))
history["val_loss"].append(validation_loss)
history["val_acc"].append(validation_accuracy)
print(f"Epoch {epoch + 1}: train_acc={history['train_acc'][-1]:.3f}, val_acc={validation_accuracy:.3f}")
return history
def train_long(net, train_loader, test_loader, **kwargs):
return train(net, train_loader, test_loader, **kwargs)
def plot_results(history):
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
axes[0].plot(history["train_acc"], label="train")
axes[0].plot(history["val_acc"], label="validation")
axes[1].plot(history["train_loss"], label="train")
axes[1].plot(history["val_loss"], label="validation")
axes[0].set_title("Accuracy")
axes[1].set_title("Loss")
axes[0].legend()
axes[1].legend()
plt.show()
def plot_convolution(kernel, title=""):
convolution = nn.Conv2d(1, 1, kernel_size=3, bias=False)
with torch.no_grad():
convolution.weight.copy_(kernel.reshape(1, 1, 3, 3))
fig, axes = plt.subplots(2, 6, figsize=(10, 4))
fig.suptitle(title)
for index in range(5):
image = data_train[index][0]
axes[0, index].imshow(image[0], cmap="gray")
axes[1, index].imshow(convolution(image.unsqueeze(0))[0, 0], cmap="gray")
axes[0, index].axis("off")
axes[1, index].axis("off")
axes[0, 5].imshow(kernel, cmap="gray")
axes[0, 5].axis("off")
axes[1, 5].axis("off")
plt.show()
def display_dataset(dataset, n=10, classes=None):
count = min(n, len(dataset))
fig, axes = plt.subplots(1, count, figsize=(1.8 * count, 3))
axes = np.atleast_1d(axes)
for index in range(count):
image, label = dataset[index]
image = image.detach().cpu()
low, high = image.min(), image.max()
image = (image - low) / (high - low + 1e-7)
axes[index].imshow(np.transpose(image.numpy(), (1, 2, 0)))
axes[index].axis("off")
if classes is not None:
axes[index].set_title(classes[int(label)])
plt.show()
def check_image_dir(pattern):
invalid = []
for filename in glob.glob(pattern):
try:
with Image.open(filename) as image:
image.verify()
except (OSError, SyntaxError):
invalid.append(filename)
if invalid:
raise ValueError(f"Invalid images detected: {invalid[:5]}")
return 0
load_mnist(batch_size=128)## Convolutional filters
Convolutional filters are small windows that run over each pixel of the image and compute weighted average of the neighboring pixels.
They are defined by matrices of weight coefficients. Let's see the examples of applying two different convolutional filters over our MNIST handwritten digits:
plot_convolution(torch.tensor([[-1.,0.,1.],[-1.,0.,1.],[-1.,0.,1.]]),'Vertical edge filter')
plot_convolution(torch.tensor([[-1.,-1.,-1.],[0.,0.,0.],[1.,1.,1.]]),'Horizontal edge filter')First filter is called a **vertical edge filter**, and it is defined by the following matrix:
$$
\left(
\begin{matrix}
-1 & 0 & 1 \cr
-1 & 0 & 1 \cr
-1 & 0 & 1 \cr
\end{matrix}
\right)
$$
When this filter goes over relatively uniform pixel field, all values add up to 0. However, when it encounters a vertical edge in the image, high spike value is generated. That's why in the images above you can see vertical edges represented by high and low values, while horizontal edges are averaged out.
An opposite thing happens when we apply horizontal edge filter - horizontal lines are amplified, and vertical are averaged out.
In classical computer vision, multiple filters were applied to the image to generate features, which then were used by machine learning algorithm to build a classifier. However, in deep learning we construct networks that **learn** best convolutional filters to solve classification problem.
To do that, we introduce **convolutional layers**.
## Covolutional layers
Convolutional layers are defined using `nn.Conv2d` construction. We need to specify the following:
* `in_channels` - number of input channels. In our case we are dealing with a grayscale image, thus number of input channels is 1.
* `out_channels` - number of filters to use. We will use 9 different filters, which will give the network plenty of opportunities to explore which filters work best for our scenario.
* `kernel_size` is the size of the sliding window. Usually 3x3 or 5x5 filters are used.
Simplest CNN will contain one convolutional layer. Given the input size 28x28, after applying nine 5x5 filters we will end up with a tensor of 9x24x24 (the spatial size is smaller, because there are only 24 positions where a sliding interval of length 5 can fit into 28 pixels).
After convolution, we flatten 9x24x24 tensor into one vector of size 5184, and then add linear layer, to produce 10 classes. We also use `relu` activation function in between layers.
class OneConv(nn.Module):
def __init__(self):
super(OneConv, self).__init__()
self.conv = nn.Conv2d(in_channels=1,out_channels=9,kernel_size=(5,5))
self.flatten = nn.Flatten()
self.fc = nn.Linear(5184,10)
def forward(self, x):
x = nn.functional.relu(self.conv(x))
x = self.flatten(x)
x = nn.functional.log_softmax(self.fc(x),dim=1)
return x
net = OneConv()
summary(net,input_size=(1,1,28,28))You can see that this network contains around 50k trainable parameters, compared to around 80k in fully-connected multi-layered networks. This allows us to achieve good results even on smaller datasets, because convolutional networks generalize much better.
hist = train(net,train_loader,test_loader,epochs=5)
plot_results(hist)As you can see, we are able to achieve higher accuracy, and much faster, compared to the fully-connected networks from previous unit.
We can also visualize the weights of our trained convolutional layers, to try and make some more sense of what is going on:
fig,ax = plt.subplots(1,9)
with torch.no_grad():
p = next(net.conv.parameters())
for i,x in enumerate(p):
ax[i].imshow(x.detach().cpu()[0,...])
ax[i].axis('off')You can see that some of those filters look like they can recognize some oblique strokes, while others look pretty random.
## Multi-layered CNNs and pooling layers
First convolutional layers looks for primitive patterns, such as horizontal or vertical lines, but we can apply further convolutional layers on top of them to look for higher-level patterns, such as primitive shapes. Then more convolutional layers can combine those shapes into some parts of the picture, up to the final object that we are trying to classify.
When doing so, we may also apply one trick: reducing the spatial size of the image. Once we have detected there is a horizontal stoke within sliding 3x3 window, it is not so important at which exact pixel it occurred. Thus we can "scale down" the size of the image, which is done using one of the **pooling layers**:
* **Average Pooling** takes a sliding window (for example, 2x2 pixels) and computes an average of values within the window
* **Max Pooling** replaces the window with the maximum value. The idea behind max pooling is to detect a presence of a certain pattern within the sliding window.
Thus, in a typical CNN there would be several convolutional layers, with pooling layers in between them to decrease dimensions of the image. We would also increase the number of filters, because as patterns become more advanced - there are more possible interesting combinations that we need to be looking for.
> **Figure description:** An image showing several convolutional layers with pooling layers.
Because of decreasing spatial dimensions and increasing feature/filters dimensions, this architecture is also called **pyramid architecture**.
class MultiLayerCNN(nn.Module):
def __init__(self):
super(MultiLayerCNN, self).__init__()
self.conv1 = nn.Conv2d(1, 10, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(10, 20, 5)
self.fc = nn.Linear(320,10)
def forward(self, x):
x = self.pool(nn.functional.relu(self.conv1(x)))
x = self.pool(nn.functional.relu(self.conv2(x)))
x = x.view(-1, 320)
x = nn.functional.log_softmax(self.fc(x),dim=1)
return x
net = MultiLayerCNN()
summary(net,input_size=(1,1,28,28))Note a few things about this definition:
* Instead of using `Flatten` layer, we are flattening the tensor inside `forward` function using `view` function. Since flattening layer does not have trainable weights, it is not essential that we create a separate layer instance within our class
* We use just one instance of pooling layer in our model, also because it does not contain any trainable parameters, and this one instance can be effectively reused
* The number of trainable parameters (~8.5K) is dramatically smaller than in previous cases. This happens because convolutional layers in general have few parameters, and dimensionality of the image before applying final dense layer is significantly reduced. Small number of parameters have positive impact on our models, because it helps to prevent overfitting even on smaller dataset sizes.
hist = train(net,train_loader,test_loader,epochs=5)What you should probably observe is that we are able to achieve higher accuracy than with just one layer, and much faster - just with 1 or 2 epochs. It means that sophisticated network architecture needs much fewer data to figure out what is going on, and to extract generic patterns from our images.
## Playing with real images from the CIFAR-10 dataset
While our handwritten digit recognition problem may seem like a toy problem, we are now ready to do something more serious. Let's explore more advanced dataset of pictures of different objects, called [CIFAR-10](https://www.cs.toronto.edu/~kriz/cifar.html). It contains 60k 32x32 images, divided into 10 classes.
# course-edition deterministic RGB pattern fixture v1
_course_generator = torch.Generator().manual_seed(2026)
_course_axis = torch.linspace(-1.0, 1.0, 32)
_course_y, _course_x = torch.meshgrid(_course_axis, _course_axis, indexing="ij")
def _course_rgb_pattern(label):
frequency = 1 + label % 3
phase = label * 0.37
horizontal = 0.5 + 0.5 * torch.sin(frequency * torch.pi * _course_x + phase)
vertical = 0.5 + 0.5 * torch.cos((1 + label // 3) * torch.pi * _course_y - phase)
radius = torch.sqrt((_course_x - 0.12 * (label % 3 - 1)) ** 2 + (_course_y - 0.12 * (label // 3 - 1)) ** 2)
ring = torch.exp(-((radius - (0.25 + 0.035 * label)) ** 2) / 0.012)
channels = torch.stack((horizontal, vertical, ring))
return torch.roll(channels, shifts=label % 3, dims=0).clamp(0.0, 1.0)
_course_templates = torch.stack([_course_rgb_pattern(label) for label in range(10)])
_course_labels = torch.arange(500, dtype=torch.long) % 10
_course_images = _course_templates[_course_labels].clone()
_course_noise = 0.04 * torch.rand(_course_images.shape, generator=_course_generator)
_course_images = ((_course_images + _course_noise).clamp(0.0, 1.0) - 0.5) / 0.5
_course_split = 400
trainset = torch.utils.data.TensorDataset(_course_images[:_course_split], _course_labels[:_course_split])
testset = torch.utils.data.TensorDataset(_course_images[_course_split:], _course_labels[_course_split:])
trainloader = torch.utils.data.DataLoader(trainset, batch_size=14, shuffle=True, generator=_course_generator)
testloader = torch.utils.data.DataLoader(testset, batch_size=14, shuffle=False)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')display_dataset(trainset,classes=classes)A well-known architecture for CIFAR-10 is called [LeNet](https://en.wikipedia.org/wiki/LeNet), and has been proposed by *Yann LeCun*. It follows the same principles as we have outlined above, the main difference being 3 input color channels instead of 1.
We also do one more simplification to this model - we do not use `log_softmax` as output activation function, and just return the output of last fully-connected layer. In this case we can just use `CrossEntropyLoss` loss function to optimize the model.
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.conv3 = nn.Conv2d(16,120,5)
self.flat = nn.Flatten()
self.fc1 = nn.Linear(120,64)
self.fc2 = nn.Linear(64,10)
def forward(self, x):
x = self.pool(nn.functional.relu(self.conv1(x)))
x = self.pool(nn.functional.relu(self.conv2(x)))
x = nn.functional.relu(self.conv3(x))
x = self.flat(x)
x = nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return x
net = LeNet()
summary(net,input_size=(1,3,32,32))Training this network properly will take significant amount of time, and should preferably be done on GPU-enabled compute.
opt = torch.optim.SGD(net.parameters(),lr=0.001,momentum=0.9)
hist = train(net, trainloader, testloader, epochs=3, optimizer=opt, loss_fn=nn.CrossEntropyLoss())The accuracy that we have been able to achieve with 3 epochs of training does not seem great. However, remember that blind guessing would only give us 10% accuracy, and that our problem is actually significantly more difficult than MNIST digit classification. Getting above 50% accuracy in such a short training time seems like a good accomplishment.
## Takeaways
In this unit, we have learned the main concept behind computer vision neural networks - convolutional networks. Real-life architectures that power image classification, object detection, and even image generation networks are all based on CNNs, just with more layers and some additional training tricks.
Outputs, execution counts, widgets, and active content were removed during import. Run notebooks only in an external environment you trust.
Record your practice
Optional self-reporting helps you remember what you practiced and never gates course completion.