Reading for this lecture:¶
The reading for this lecture:
Reading: Convolutional Neural Networks
- Chapter 9.1 (The Convolution Operation)
- Chapter 9.2 (Motivation)
- Chapter 9.3 (Pooling)
- Chapter 9.4 (Convolution and Pooling as an Infinitely Strong Prior)
- Chapter 9.5 (Variants of the Basic Convolution Function)
- Chapter 9.6 (Structured Output)
Image Classification with MLPs¶
Vector inputs are useful for a variety of tasks, but in some tasks the data structure contains information
- Since MLPs (Feedforward networks) are universal function approximators, they can be used for image classification tasks.
- Task input: The input is a $n \times m \times C$ tensor ${\bf X}$: $C$ matrices, each $n \times m$, representing images in $C$ colors.
- MLP input: vectorize $\text{vec}({\bf X})$
- We will each "color" as a "channel"
- Sometimes a channel will encode light intensity rather than a "color"
- MLP output: softmax output predicting $P(Y=y | {\bf X})$
Convolutional Neural Networks¶
Convolutional neural networks will take advantage of pixel locality to more easily learn local pixel structure.
- This is an inductive bias (we are adding some world knowledge to our neural network)
Local pixel structural information will be extracted as a filter.
- Based on the concept of local convolutions
Example:
CNNs: The revolution in image processing¶
Imagenet TOP 1 accuracy results (source https://paperswithcode.com/sota/image-classification-on-imagenet)
Connection between Good Vision models and Bayesian Deep Learning¶
- ModelSoup is a state-of-the-art vision model that does something similar to posterior sampling (via hyperparmeters, different intitializations, and SGD MLE optimization)
- Work argues it produces more robust and accurate models.
- Work argues it produces more robust and accurate models.
https://paperswithcode.com/paper/model-soups-averaging-weights-of-multiple
%matplotlib inline
import matplotlib.pyplot as plt
def show(img, title=None, cmap_='Greys'):
## converting to a CPU memory numpy array
npimg = img.cpu().numpy()
if title != None:
print(title)
plt.imshow(npimg, cmap=cmap_, vmin=0, interpolation='nearest')
Loading the MNIST data using Pytorch¶
Now we will:
- Define image size
- Define batch size
- Check if CUDA GPUs are available
import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import numpy as np
#from class_cnn import *
IMAGE_SIZE = 784
IMAGE_WIDTH = IMAGE_HEIGHT = 28
batch_size = 64
# Do we have GPUs available?
use_cuda = torch.cuda.is_available()
/Users/ribeirob/anaconda3/lib/python3.10/site-packages/tqdm/auto.py:22: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from .autonotebook import tqdm as notebook_tqdm
Next:
- Define device we will use for matrix computations (CPU or GPU)
- We will use the variable
deviceto define if the matrix computations will be on CPU or GPU
- We will use the variable
- Define how many threads will be used to load data from disk into the memory
- Multiple threads are useful if we use multiple GPUs
# Handy way to use GPUs if there are any
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
# Data loader parameters
kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
# Load data
train_data = datasets.MNIST('../data/MNIST/', train=True, download=True , transform=transforms.ToTensor())
test_data = datasets.MNIST('../data/MNIST/', train=False, download=True, transform=transforms.ToTensor())
train_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size, drop_last=True, **kwargs)
test_loader = DataLoader(test_data, shuffle=False, batch_size=batch_size, drop_last=True, **kwargs)
Example of training image¶
We now show a random training image
- Since MNIST images are B/W (Black & White), the tensor ${\bf X}$ is actually just a $28\times 28$ matrix
import random
# Look at random example from training data
train_image, train_label = random.choice(train_data)
# Let's see which digit we got
train_image = train_image[0].view([1, 1, IMAGE_WIDTH, IMAGE_HEIGHT])
#train_label = train_image[1]
show(train_image.data[0][0],title="Original Image")
Original Image
Step 1: Apply Convolutional Filter¶
Step 1.1: Break the original image into image patches¶
- Divide image into overlapping image patches based on stride (pad image corners with zeros if needed)
- Patch (filter) size $k$ = patch is of size $k\times k$, $k \geq 2$
- The filter is applied over $k \times k$ image patches (over each channel)
- Stride = number of pixels we will skip after making the previous patch
- These patches overlap accodring to stride, which is by how much each block must be separated horizontally and vertically.
- Padding = number of extra padding "0" values we add to the corners of the image
- If $k$ is not a multiple of the image height of width, we will need padding (increase image height (width) by adding a row (column) of zeros).
- Patch (filter) size $k$ = patch is of size $k\times k$, $k \geq 2$
- We will not save the image patches
Patch Example¶
- To define a patch, we first need to define $k$
- i.e., we must define the size of the $k \times k$ filter
torch.FloatTensorcreates a tensor in Pytorch- The parameter
,device=deviceindicates which memory (CPU or GPU) will hold the tensor - The filter is a $1 \times k \times k$ tensor (since we only have a single B/W channel)
- The parameter
# Filter has only a single channel as our image is black and white
W1 = torch.zeros((1,3,3), device=device)
# An arbitrary initial value for our filter (this is a special toy filter)
W1[0, :, :] = torch.tensor([[[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1]]],dtype=torch.float,device=device)
- We now define a patch
- Patches must have a stride parameter
- There is no padding for now (to simplify)
# Defines patches
def conv_patch(img, filter_size, stride=1, willshow=False):
if willshow:
fig=plt.figure(figsize=(8, 8))
cnt = 0
# Iterate to segment the image for the convolution operation.
i_vec = np.uint32(np.arange(filter_size/2, img.shape[0]-filter_size/2+1, step=stride))
j_vec = np.uint32(np.arange(filter_size/2, img.shape[1]-filter_size/2+1, step=stride))
for i in i_vec:
for j in j_vec:
img_region = img[(i-np.uint32(np.floor(filter_size/2))):(i+np.uint32(np.ceil(filter_size/2))),
(j-np.uint32(np.floor(filter_size/2))):(j+np.uint32(np.ceil(filter_size/2)))]
if willshow:
cnt += 1
no_i = i_vec.shape[0]
no_j = j_vec.shape[0]
ax = fig.add_subplot(no_i,no_j,cnt) #img.shape[0]//stride -stride, img.shape[1]//stride + stride, cnt)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
show(img_region)
if willshow:
plt.show()
Showing all image patches of my_filter (1x3x3 filter)
conv_patch(train_image.data[0][0], filter_size=W1.shape[1], stride=2, willshow=True)
Step 1.2: Understanding Convolution Operations¶
Mathematical Foundation¶
A convolution is a mathematical operation of two functions that produces a third function expressing how the shape of one is modified by the other: $$(f * g)(t) = \int_{-\infty}^{\infty} f(\tau)g(t-\tau)d\tau.$$
In discrete domains, which are more relevant for our computational purposes, this becomes: $$(f * g)(n) = \sum_{m=-\infty}^{\infty} f(m)g(n-m)$$
Intuitive Understanding Through Probability¶
Let's build intuition through a practical example involving discrete probability distributions:
Consider a system with two independent random variables X₁ and X₂ (say, two biased die):
- X₁ follows distribution p₁ over support {1,...,6}
- X₂ follows distribution p₂ over support {1,...,6}
The probability distribution of their sum S = X₁ + X₂ is given by their convolution: $$(p_1 * p_2)(s) = \sum_{j=1}^6 p_1(j)p_2(s-j).$$
This can be understood as summing the probabilities of all possible ways to obtain s through addition of values from X₁ and X₂.
Computational Implementation¶
In neural networks, convolutions operate on discrete arrays (tensors). For a 2D input $M$ and $k\times k$ kernel $W$:
$$(W * M)(i,j) = \sum_{m=1}^k\sum_{n=1}^k W(m,n)M(i-m,j-n)$$
This operation forms the basis for convolutional layers in neural networks, where kernels learn to detect important features in the input data.
Applying the convolution filter:
- For each $C \times k \times k$ image patch ${\bf M}_{ij}$ with lower right corner pixel $(i,j)$
- Apply the filter (our filter defined above does not have a bias):
$$
\text{out} = \sigma(\text{sum}({\bf M}_{i,j} \odot {\bf W}_1) + b_1)
$$
- The operator $\odot$ is the Hadamard product (element-wise multiplication)
- The filter takes two $C \times k \times k$ tensors (${\bf M}_{ij}$ and ${\bf W}_1$) and a scalar $b_1$.
- The operator $\text{sum}(\cdot)$ sums over all the values of a $C \times k \times k$ tensor.
- The filter is really just a single-layer MLP with a single output neuron applied over a vectorized image patch of each channel
Visual representation of the convolution for the $i$-th channel:
Let $\text{vec}({\bf M})$ and $\text{vec}({\bf W}_i)$ be the patch and the parameters of the $i$-th filter, respectivelly:
| |
|
Step 1.2: Feature Map¶
Then, we apply this convolution in layers, multiple times. Note that each pixel in the previous layer has a convolution representation in the next layer, which we will call a Feature Map.
Code for the convolution operation
# Convolution with the filter
def convolve_with_filter(img, c_filter, stride=1, device=None, willshow=False):
if willshow:
fig=plt.figure(figsize=(8, 8))
cnt = 0
filter_size = c_filter.shape[1]
c_filter = c_filter.view((filter_size*filter_size,1))
result = torch.zeros(img.shape,device=device)
img = img.to(device)
#Looping through the image to apply the convolution operation.
for i in np.uint32(np.arange(filter_size/2, img.shape[0]-filter_size/2+1, step=stride)):
for j in np.uint32(np.arange(filter_size/2, img.shape[1]-filter_size/2+1, step=stride)):
img_region = img[(i-np.uint32(np.floor(filter_size/2))):(i+np.uint32(np.ceil(filter_size/2))),
(j-np.uint32(np.floor(filter_size/2))):(j+np.uint32(np.ceil(filter_size/2)))]
# Linearizes both filter and region, and perform inner product of vectors. Result is a real number.
# .contiguous() is need to place the segmentation of the image into a contigous region of the memory
result[i, j] = img_region.contiguous().view((-1,filter_size*filter_size)) @ c_filter
# Neuron output.
output = torch.relu(result[np.uint32(filter_size/2):result.shape[0]-np.uint32(filter_size/2),
np.uint32(filter_size/2):result.shape[1]-np.uint32(filter_size/2)])
if willshow:
cnt += 1
# Shows the absolute values returned by the filter
show(output.cpu())
if willshow:
plt.show()
return output
Applying the filter over the input image:
- The result is the next layer (called Feature Map)
- Note that our filter example ${\bf W}_1$ is a vertical edge detector
## Remember our initial toy filter (a real CNN filter matrix is a parameter of the algorithm):
# W1[0, :, :] = torch.tensor([[[-1, 0, 1],
# [-1, 0, 1],
# [-1, 0, 1]]],dtype=torch.float,device=device)
conv_img = convolve_with_filter(train_image.data[0][0], c_filter=W1[0,:,:], stride=3, device=device, willshow=True)
Equivariant Transformations¶
A function $f$ is said to be equivariant to a transformation $T$ if $$ T(f(x)) = f(T(x)).$$
CNN Convolutions are Approximately Shift-Equivariant¶
If $T$ is a shift operation over the image, then $$T(\text{convolve\_with\_filter}(x, \text{stride}=1)) \approx \text{convolve\_with\_filter}(T(x), \text{stride}=1),$$ the difference being at the image boundaries.
print("Original image")
show(train_image.data[0][0])
print("Original image after applying all convolutions")
conv_img = convolve_with_filter(train_image.data[0][0], c_filter=W1[0,:,:], stride=1, device=device, willshow=True)
print("--------------------")
print("Shifted image")
translated_image = transforms.functional.affine(train_image.data[0], angle=0, translate=(5,-5), scale=1, shear=[0])[0]
show(translated_image)
print("Shifted image after applying all convolutions")
conv_img = convolve_with_filter(translated_image, c_filter=W1[0,:,:], stride=1, device=device, willshow=True)
Original image Original image after applying all convolutions
-------------------- Shifted image Shifted image after applying all convolutions
CNNs Convolutions are not Rotation Equivariant¶
If $T$ is a rotation operation over the image, then, for arbitrary convolution weights $$T(\text{convolve\_with\_filter}(x, \text{stride}=1)) \neq \text{convolve\_with\_filter}(T(x), \text{stride}=1),\quad \forall x.$$
As we have seen in our lecture on G-invariant neurons, the weights of the neural network must lie in an invariant subspace in order to make the neuron invariant to group transformations.
print("Original image")
show(train_image.data[0][0])
print("Original image after applying all convolutions")
conv_img = convolve_with_filter(train_image.data[0][0], c_filter=W1[0,:,:], stride=1, device=device, willshow=True)
print("Rotated image")
rotated_image = transforms.functional.affine(train_image.data[0], angle=-90, translate=(0,0), scale=1, shear=[0])[0]
show(rotated_image)
print("Rotated image after applying all convolutions")
conv_img_rot = convolve_with_filter(rotated_image, c_filter=W1[0,:,:], stride=1, device=device, willshow=True)
Original image Original image after applying all convolutions
Rotated image Rotated image after applying all convolutions
Step 1.3: Downsampling via Pooling Layer¶
Pooling Layer¶
def max_pooling(img, filter_size=3, stride=1, device=None, willshow=False):
if willshow:
fig=plt.figure(figsize=(8, 8))
cnt = 0
result = torch.zeros(img.shape,device=device)
img = img.to(device)
#Looping through the image to apply the convolution operation.
for i in np.uint32(np.arange(filter_size/2, img.shape[0]-filter_size/2+1, step=stride)):
for j in np.uint32(np.arange(filter_size/2, img.shape[1]-filter_size/2+1, step=stride)):
img_region = img[(i-np.uint32(np.floor(filter_size/2))):(i+np.uint32(np.ceil(filter_size/2))),
(j-np.uint32(np.floor(filter_size/2))):(j+np.uint32(np.ceil(filter_size/2)))]
# Max over window
result[i, j] = torch.max(img_region.contiguous().view((-1,filter_size*filter_size)))
if willshow:
cnt += 1
# Shows the absolute values returbed by the filter
show(torch.abs(result.cpu()))
if willshow:
plt.show()
return result
Max pooling over $3\times 3$ patches of the previous feature map (stride = 2)
## Remember our initial toy filter (a real CNN filter matrix is a parameter of the algorithm):
# W1[0, :, :] = torch.tensor([[[-1, 0, 1],
# [-1, 0, 1],
# [-1, 0, 1]]],dtype=torch.float,device=device)
max_pooled_img = max_pooling(conv_img, filter_size = 3, stride = 2, willshow=True)
End of Convolutional Filter¶
Dealing with Color Images¶
- There are multiple ways to deal with RGB color images
- The simplest way is to apply 3 different filters to form a single pixel in the feature map
- The simplest way is to apply 3 different filters to form a single pixel in the feature map
Colored CNN Filter Example¶
- This example show the filters, the padding and the various filters
Step 2: Stack Multiple Convolutional Filters¶
- Use multiple filters per image channel (channel = "color")
- Filters specialize, will learn to detect "ears", "fur", "feet", etc.
- Last feature map becomes the image of the next set of filters
- After a few convolution layers, we will add a few MLP layers
- Transition from convolution to MLP requires changing a feature map tensor (or matrix) into a vector
Pytorch Example¶
- In what follows we will present a CNN with 2 convolutional layers followed by a 2-hidden layer MLP.
- Convolution kernels take 8x8 patches and have stride = 2
- ReLU activations (except for last softmax output)
- The task: Classify animals in images as ants or bees
- Input images have different sizes, must be cropped by torchvision's transforms.Compose() transforms.RandomResizedCrop
- It is always a good idea to normalize the images, in order to make the input less sensitive to different exposures
- Image folders must be organized as
data_dir --+ |-train |---ants |---bees |-val |---ants |---bees
<center><img src="CNN.svg" width=1200px/></center>
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, models, transforms
import matplotlib.pyplot as plt
import os
import numpy as np
import copy
import time
# Show images
def imshow(inp, title=None):
"""Imshow for Tensor."""
inp = inp.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406]) # mean of ImageNet
std = np.array([0.229, 0.224, 0.225]) # std of ImageNet
inp = std * inp + mean
inp = np.clip(inp, 0, 1)
plt.imshow(inp)
if title is not None:
plt.title(title)
plt.pause(0.001) # pause a bit so that plots are updated
plt.ion() # interactive mode
<matplotlib.pyplot._IonContext at 0x7fad712559b0>
# Load data with data augmentation transformations
def load_data(data_dir, batch_size = 32):
global b_size
b_size = batch_size
# Data augmentation and normalization for training
# Just normalization for validation
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(size=(224,224), scale=(0.6, 1.0), ratio=(0.75, 1.3333333333333333), interpolation=2), #interpolation=PIL.Image.BILINEAR
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) # mean and std of ImageNet
]),
'val': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop((224,224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) # mean and std of ImageNet
]),
}
# Read dataset from real jpeg images inside folder data_dir
# Folder must be organized as
# data_dir --+
# |-train
# |---ants
# |---bees
# |-val
# |---ants
# |---bees
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) for x in ['train', 'val']}
data_loaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size,shuffle=True, pin_memory=True, drop_last=True, num_workers=4) for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_names = image_datasets['train'].classes
return data_loaders, dataset_sizes, class_names
data_loaders, dataset_sizes, class_names = load_data(data_dir='./data/antsbees', batch_size=32)
# Get a batch of training data
inputs, classes = next(iter(data_loaders['train']))
# Make a grid from batch
out = torchvision.utils.make_grid(inputs)
imshow(out, title="Mini-batch")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
/Users/ribeirob/anaconda3/lib/python3.7/site-packages/torchvision/transforms/transforms.py:835: UserWarning: Argument interpolation should be of type InterpolationMode instead of int. Please, use InterpolationMode enum. "Argument interpolation should be of type InterpolationMode instead of int. "
# CNN takes 3-channel images as input
#
class CNNNet(nn.Module):
def __init__(self):
super(CNNNet, self).__init__()
# out_channels defines how many filters we will have
self.conv1 = nn.Conv2d(in_channels=3, out_channels=100, kernel_size=8, stride=2)
self.pool = nn.MaxPool2d(kernel_size=5, stride=2)
self.conv2 = nn.Conv2d(in_channels=100, out_channels=32, kernel_size=8, stride=2)
# Next is the feedforward neural network part
self.fc1 = nn.Linear(32 * 10 * 10, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 2)
def forward(self, x):
# First CNN convolution + activation + pooling
x = torch.relu(self.conv1(x))
# print(f'conv1 {x.shape}')
x = self.pool(x)
# print(f'pool1 {x.shape}')
# Second CNN convolution + activation + pooling
x = torch.relu(self.conv2(x))
# print(f'conv2 {x.shape}')
x = self.pool(x)
# print(f'pool2 {x.shape}')
# Make the feature maps into vectors
x = x.view(-1, 32 * 10 * 10)
# Feed vectors to feedforward networks
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
# Model does not need to output the softmax because the CrossEntropyLoss already computes the softmax for us
return x
model = CNNNet().to(device)
print(model)
CNNNet( (conv1): Conv2d(3, 100, kernel_size=(8, 8), stride=(2, 2)) (pool): MaxPool2d(kernel_size=5, stride=2, padding=0, dilation=1, ceil_mode=False) (conv2): Conv2d(100, 32, kernel_size=(8, 8), stride=(2, 2)) (fc1): Linear(in_features=3200, out_features=120, bias=True) (fc2): Linear(in_features=120, out_features=84, bias=True) (fc3): Linear(in_features=84, out_features=2, bias=True) )
module = model.conv1
print(f'Number of weight parameters in first conv layer: {len(list(module.weight))}')
print(list(module.named_parameters()))
Number of weight parameters in first conv layer: 100
[('weight', Parameter containing:
tensor([[[[-8.7199e-03, -5.2857e-02, 6.9117e-02, ..., -4.9588e-02,
-5.4959e-02, -2.9211e-02],
[-2.0656e-02, 1.5452e-02, -3.6041e-02, ..., 4.4886e-02,
6.9026e-02, -3.0882e-03],
[-2.8698e-02, -2.5230e-02, 1.1584e-03, ..., -3.8607e-02,
2.3159e-02, -4.1991e-02],
...,
[-1.6568e-02, 4.6236e-02, -3.3802e-02, ..., 4.9187e-02,
-1.5492e-02, 1.3342e-02],
[-6.8413e-02, -6.9441e-02, -2.1421e-02, ..., -2.5604e-02,
-4.4789e-02, 6.7149e-02],
[-3.0952e-02, -8.0341e-03, 3.2298e-02, ..., -3.3293e-02,
-2.4068e-02, 3.0491e-02]],
[[ 3.5019e-02, 2.2325e-02, 4.4138e-02, ..., 6.2999e-02,
2.0834e-02, -6.4607e-02],
[ 4.3797e-02, -5.9679e-02, 6.0381e-03, ..., 3.9931e-02,
3.2812e-02, -1.4391e-02],
[-1.4491e-02, -4.7937e-03, -6.2388e-02, ..., -4.9574e-03,
2.2404e-02, 6.4779e-02],
...,
[ 5.3781e-02, -1.5658e-03, -6.8408e-02, ..., 8.4258e-03,
8.9419e-03, -5.6679e-02],
[ 6.3030e-02, -7.0807e-02, -2.9990e-02, ..., -3.3887e-02,
3.9443e-04, 4.7560e-02],
[ 6.2674e-02, -6.8894e-02, -4.6214e-02, ..., -1.8077e-02,
-2.6137e-02, 4.9260e-02]],
[[-2.3307e-02, -5.2173e-02, -1.8364e-02, ..., 6.0928e-03,
3.2064e-02, 2.4385e-02],
[ 2.9405e-02, 4.8276e-03, -3.5933e-02, ..., -1.7818e-02,
-4.9033e-02, -3.0924e-02],
[-4.6393e-02, 4.0180e-02, 2.8955e-02, ..., 6.0159e-02,
-2.4527e-02, 1.1484e-02],
...,
[ 2.1535e-02, -3.2134e-02, 4.5911e-02, ..., -6.0689e-02,
-4.8589e-02, 3.5056e-02],
[-4.5093e-02, -1.1753e-03, -7.2140e-02, ..., 4.3195e-02,
1.0105e-02, -8.8694e-03],
[ 2.0332e-02, 3.1006e-02, -2.5717e-02, ..., 5.7096e-02,
-1.7773e-02, 2.9748e-02]]],
[[[ 5.8076e-02, 5.4659e-02, -2.2765e-02, ..., 5.6196e-02,
5.1361e-02, 5.2430e-02],
[-1.8222e-02, -5.8213e-02, -4.9020e-02, ..., 2.5070e-02,
-4.4464e-02, 5.7538e-02],
[-3.9858e-02, 2.7806e-02, -5.3690e-02, ..., -4.6459e-02,
2.4335e-02, -6.1292e-02],
...,
[-4.1611e-05, 3.7705e-02, -1.9726e-03, ..., 4.9748e-02,
6.7846e-02, 5.7255e-03],
[ 1.9944e-02, 1.2382e-02, -4.1670e-02, ..., -4.3290e-02,
-3.7903e-02, 1.2739e-02],
[ 6.2188e-02, 7.1709e-02, 5.4559e-02, ..., -7.0103e-02,
-6.3246e-03, -4.4487e-02]],
[[-4.6894e-02, 3.7276e-02, -6.3357e-02, ..., 3.8209e-02,
-1.7839e-02, -4.3134e-02],
[ 1.1268e-02, -1.9386e-02, 6.8126e-02, ..., -1.5707e-02,
-3.8045e-02, -2.9552e-02],
[-3.8326e-02, 7.3725e-03, -1.4597e-02, ..., 4.9313e-03,
1.8478e-02, -6.2749e-02],
...,
[ 4.7246e-02, -1.9710e-02, 4.8895e-02, ..., 9.1512e-03,
6.5606e-02, -1.9612e-02],
[ 6.7086e-03, -4.8956e-02, 4.9682e-02, ..., 7.0179e-02,
-4.2279e-02, 5.3183e-02],
[ 5.5250e-02, -1.4898e-02, -8.6535e-03, ..., 3.4871e-03,
-6.1705e-02, -5.9189e-03]],
[[ 6.7148e-02, -4.4031e-02, -5.0811e-02, ..., -3.8505e-02,
3.6153e-02, -3.8020e-02],
[-5.0297e-02, 6.6009e-02, -5.2794e-02, ..., 4.4966e-03,
-4.3542e-02, -5.7337e-02],
[-4.8375e-02, -3.0418e-02, -6.2435e-02, ..., 4.2361e-02,
3.3232e-02, -5.1671e-02],
...,
[ 3.5142e-02, 1.2547e-02, -2.5914e-02, ..., -4.2936e-02,
3.2852e-02, -2.5114e-02],
[-6.9205e-02, -2.4796e-02, 3.8374e-02, ..., 9.0753e-03,
-5.6634e-03, -1.2487e-02],
[-3.0229e-02, 1.0373e-02, 6.9595e-02, ..., -2.5565e-02,
-3.8111e-02, 3.3409e-02]]],
[[[-4.5868e-02, -4.7554e-02, -5.3361e-02, ..., 1.8966e-02,
4.4413e-02, 4.1859e-02],
[ 4.6228e-02, -9.4999e-03, 9.8560e-03, ..., 7.1209e-02,
3.5019e-02, -4.5170e-02],
[ 4.5544e-02, 5.9369e-02, -1.0094e-02, ..., -2.2823e-02,
-1.0744e-02, -2.3177e-02],
...,
[-6.8118e-02, -2.0028e-02, -3.7279e-02, ..., 5.7391e-02,
5.5585e-02, 3.0534e-02],
[-5.9913e-02, 4.7986e-02, -4.1333e-02, ..., 8.6147e-03,
-4.9267e-02, -1.1845e-02],
[-6.9948e-02, 4.7166e-02, -2.6169e-02, ..., 4.5017e-02,
-1.9778e-02, -1.3000e-02]],
[[ 6.6694e-03, -5.8022e-02, -8.8753e-03, ..., -4.7719e-02,
-2.6264e-02, -3.1768e-02],
[ 6.0061e-02, 1.4308e-02, -4.1889e-02, ..., -5.5980e-02,
2.2908e-02, -6.5842e-02],
[-2.7685e-02, -7.0530e-02, 7.1858e-02, ..., 1.6462e-02,
-6.3128e-02, 6.6843e-02],
...,
[ 3.1042e-02, 6.0729e-02, 7.0882e-02, ..., 1.2458e-02,
2.9704e-02, 7.7495e-03],
[ 3.9764e-02, 4.7801e-02, -4.5668e-02, ..., -2.8378e-02,
-6.0852e-02, -2.9069e-02],
[-1.5565e-02, 3.9782e-03, -6.7429e-03, ..., 5.1018e-02,
-4.0536e-03, 5.0457e-03]],
[[-2.7379e-02, 6.6250e-02, -6.5553e-02, ..., -5.0223e-02,
-1.0571e-02, -7.0137e-02],
[-5.3766e-02, -3.9598e-02, 6.4299e-03, ..., 1.5761e-02,
-5.1655e-02, 2.6104e-02],
[ 4.2302e-02, 4.7440e-02, -1.9807e-02, ..., -5.0513e-02,
6.7663e-02, -1.1828e-02],
...,
[ 5.4695e-02, -3.9801e-03, 3.9362e-02, ..., 5.0229e-02,
3.2456e-04, -4.9946e-02],
[-2.1222e-02, -7.3458e-03, -6.4434e-02, ..., -2.9666e-02,
-3.0206e-02, -7.0923e-02],
[ 2.4494e-02, -4.2833e-02, -1.7165e-03, ..., 2.4241e-02,
-5.0472e-02, 3.0421e-03]]],
...,
[[[ 4.4846e-02, 5.1295e-02, 4.3526e-03, ..., 2.0647e-02,
4.1074e-02, -4.0982e-02],
[ 2.0011e-02, 1.2054e-02, -6.0920e-02, ..., 3.3443e-02,
1.3016e-02, -5.1524e-02],
[ 5.0686e-02, -4.4777e-03, 4.9609e-02, ..., -3.6912e-02,
-6.2490e-02, -1.3685e-02],
...,
[-5.5527e-02, 3.5703e-02, 6.6360e-02, ..., 3.0310e-02,
7.5028e-03, -6.5103e-02],
[-2.8043e-02, 4.5851e-02, 4.4002e-02, ..., -3.5427e-02,
9.9245e-03, -1.1460e-02],
[-5.2040e-02, -2.5125e-02, 5.7287e-02, ..., -6.1192e-02,
1.2053e-02, -2.0203e-02]],
[[ 4.2167e-02, -1.9715e-02, 3.1294e-02, ..., -2.0041e-02,
9.9045e-03, 1.1413e-02],
[-6.3304e-02, -3.0920e-02, -4.2802e-02, ..., 2.2706e-02,
6.1599e-02, 2.4468e-02],
[-2.7088e-02, 7.1816e-02, 1.6866e-02, ..., 2.8810e-02,
4.3562e-02, 3.7779e-02],
...,
[-4.2678e-02, -1.8773e-02, 3.6324e-02, ..., -5.0086e-02,
-1.5353e-02, 1.3024e-02],
[ 1.5909e-02, 4.4825e-02, 6.6536e-02, ..., -1.4050e-03,
1.4085e-02, -8.2482e-03],
[-3.4451e-02, -4.7969e-02, 1.5691e-02, ..., 1.8697e-02,
8.9950e-03, -5.3118e-02]],
[[-1.8198e-02, 1.6849e-03, -2.4110e-02, ..., -6.2111e-02,
4.3076e-02, -6.4502e-02],
[-5.5533e-02, -1.6269e-02, -1.8928e-02, ..., -4.9680e-02,
-2.6120e-02, 3.0268e-02],
[ 4.1695e-02, -5.2764e-02, 6.4207e-02, ..., -6.3287e-02,
-6.4123e-02, -2.5298e-03],
...,
[ 4.4772e-02, -3.5123e-02, 1.6839e-02, ..., 2.1624e-02,
-4.9376e-02, -6.5261e-04],
[ 4.7753e-02, -3.7257e-02, 5.9191e-02, ..., 2.4821e-02,
2.6853e-02, -6.0470e-02],
[ 3.5252e-02, 4.5988e-02, 3.1974e-02, ..., 1.7425e-02,
-1.2798e-02, -9.1002e-03]]],
[[[-9.9888e-03, 3.1287e-02, -8.1365e-03, ..., 3.8939e-02,
-6.6773e-02, -3.9271e-02],
[-3.8151e-02, -6.4581e-02, 3.1370e-02, ..., 6.0117e-02,
-3.0909e-02, -2.9013e-02],
[-3.7079e-02, 3.7167e-02, 5.1752e-02, ..., 2.1358e-02,
7.6609e-03, 4.0576e-02],
...,
[-6.3824e-02, -6.1524e-02, -5.8401e-02, ..., 3.3128e-02,
-8.3552e-03, -4.6941e-02],
[ 2.9762e-02, 6.4347e-02, -2.9686e-02, ..., 1.4191e-02,
5.4310e-02, 5.0533e-03],
[-4.5941e-02, -6.8322e-02, 4.8202e-02, ..., 6.5569e-02,
2.1906e-02, 5.7927e-02]],
[[-2.4088e-02, 1.9637e-02, 5.4194e-02, ..., -4.5372e-02,
-2.0012e-02, 6.1297e-02],
[ 4.3395e-03, -6.6239e-02, -3.9162e-02, ..., 1.9606e-02,
-2.6738e-02, 6.3490e-03],
[ 4.0048e-02, 4.1326e-02, 1.5821e-02, ..., 7.1970e-02,
-1.5674e-02, 4.7955e-02],
...,
[ 4.8167e-02, -6.9082e-02, -5.8759e-02, ..., -5.5066e-02,
3.9992e-02, -5.4166e-04],
[-1.9117e-02, -4.8324e-02, -5.7475e-02, ..., -5.0273e-02,
-3.4603e-02, 5.8026e-02],
[-8.6559e-03, -2.9322e-03, -1.2760e-02, ..., -7.8623e-03,
-3.7213e-02, 6.3762e-02]],
[[-1.9626e-02, -4.3937e-02, 2.4311e-02, ..., 6.7549e-02,
-2.4408e-02, -1.5093e-02],
[ 6.1298e-02, 4.2446e-02, 4.9233e-02, ..., -4.5020e-02,
3.5417e-02, -6.1639e-02],
[-5.6427e-02, -4.0531e-02, -3.8104e-02, ..., -7.0156e-02,
-5.1033e-03, -1.3354e-02],
...,
[ 5.9682e-02, -3.1272e-03, 3.7639e-02, ..., -4.1504e-02,
2.3340e-03, 2.6803e-02],
[-3.1044e-02, -6.9593e-02, 3.2570e-02, ..., -7.2941e-03,
-3.1415e-02, -1.2619e-02],
[-1.0573e-02, 5.9732e-02, 6.1493e-02, ..., 2.8432e-02,
-2.8078e-02, -4.7883e-02]]],
[[[-1.2805e-02, 7.1909e-02, 5.8034e-02, ..., 3.2525e-02,
4.1229e-02, -5.6601e-02],
[-4.7655e-02, -2.8847e-02, -3.8000e-02, ..., -4.6562e-02,
-5.2667e-02, 2.9935e-02],
[ 5.5504e-03, -5.4691e-02, 6.1758e-02, ..., -9.1322e-03,
6.1392e-02, 5.7605e-02],
...,
[-4.8402e-02, 5.3339e-02, -5.0831e-02, ..., -1.7351e-02,
4.6152e-03, -4.4799e-02],
[-1.6280e-03, 4.3636e-02, -8.4079e-03, ..., 1.1818e-02,
-1.2078e-02, -4.2325e-02],
[ 2.6265e-02, -4.1911e-02, 2.6554e-03, ..., -3.7637e-02,
6.0576e-02, -1.0682e-02]],
[[-2.5160e-02, 1.7909e-02, -5.3088e-02, ..., -4.8543e-03,
4.6576e-02, 6.4892e-02],
[-2.2408e-02, -5.7084e-02, -1.9767e-02, ..., 4.1396e-02,
-2.9300e-02, 2.9984e-02],
[ 2.9883e-02, -4.2334e-02, -5.9209e-03, ..., 5.4005e-02,
2.2152e-02, 3.1059e-02],
...,
[-5.1632e-02, -4.4185e-02, -2.2569e-02, ..., 5.2823e-02,
4.4972e-02, -6.0780e-02],
[-1.9577e-02, -1.0263e-02, 5.3751e-02, ..., -1.9650e-02,
-6.9757e-03, -1.7787e-02],
[ 2.7924e-02, 4.2241e-02, -4.3026e-02, ..., -3.6483e-02,
-2.9932e-02, 4.5918e-02]],
[[-1.7613e-02, -6.0798e-03, 5.3120e-03, ..., -5.7576e-02,
3.3984e-02, -2.8436e-02],
[ 1.1403e-02, 5.7581e-02, -2.6341e-02, ..., 7.1004e-02,
-2.8514e-02, 1.5650e-02],
[-4.6390e-02, 4.4177e-02, 1.2899e-02, ..., -5.6352e-02,
5.1271e-02, 5.0293e-02],
...,
[ 9.1651e-03, 5.7372e-03, 1.4991e-02, ..., 2.1029e-03,
-3.0885e-02, 4.3017e-02],
[ 6.8353e-02, -1.3979e-02, -7.0712e-02, ..., -1.8778e-02,
6.2261e-02, 1.4509e-02],
[-2.4441e-02, -3.5634e-02, -2.3089e-02, ..., -3.2105e-02,
8.5668e-03, -3.9226e-02]]]], requires_grad=True)), ('bias', Parameter containing:
tensor([-0.0445, 0.0040, 0.0392, 0.0385, -0.0514, -0.0104, -0.0717, -0.0291,
0.0167, -0.0073, 0.0307, 0.0449, 0.0475, -0.0680, 0.0523, 0.0273,
-0.0640, 0.0044, -0.0258, -0.0035, -0.0719, -0.0314, -0.0503, -0.0417,
0.0648, 0.0304, -0.0177, -0.0026, -0.0607, 0.0625, -0.0555, 0.0668,
0.0078, 0.0045, -0.0422, 0.0116, -0.0027, 0.0628, 0.0614, 0.0439,
-0.0389, 0.0479, 0.0269, 0.0228, 0.0663, -0.0178, -0.0409, -0.0090,
0.0084, 0.0665, -0.0602, -0.0536, -0.0477, -0.0283, 0.0131, -0.0618,
-0.0695, 0.0230, 0.0153, -0.0544, -0.0311, -0.0020, -0.0165, -0.0670,
-0.0341, -0.0441, -0.0254, 0.0358, 0.0556, -0.0388, -0.0686, 0.0233,
-0.0317, 0.0422, 0.0605, -0.0333, -0.0183, 0.0307, 0.0098, -0.0364,
-0.0460, 0.0349, 0.0477, 0.0615, 0.0323, -0.0500, 0.0214, 0.0299,
0.0703, 0.0162, -0.0040, -0.0338, 0.0464, 0.0585, -0.0137, 0.0279,
-0.0337, 0.0041, 0.0197, 0.0315], requires_grad=True))]
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.005, momentum=0.9)
def train_model(model, criterion, optimizer, num_epochs=25):
since = time.time()
# Will save the best model of "model" in validation data
# Since "model" is small, this step is fast
best_model = copy.deepcopy(model.state_dict())
best_acc = 0.0
for epoch in range(num_epochs):
print(f'Epoch {epoch + 1}/{num_epochs}')
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
model.train() # Set model to evaluation mode
else:
model.eval() # Set model to evaluation mode
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for inputs, labels in data_loaders[phase]:
# This is a synchronous way to transfer data to the GPU
# It is inneficient. We will see more efficient ways later
inputs = inputs.to(device)
labels = labels.to(device)
# zero the gradients of model
optimizer.zero_grad()
# Only compute gradients in "train" phase
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs) ## Perform forward pass
loss = criterion(outputs, labels) # loss negative log-likelihood loss using the output "probabilities"
# actually, the CrossEntropyLoss() does
# the softmax for us
_, preds = torch.max(outputs, 1) # predicted label (we will use later)
# compute gradients & optimize only if in training phase
if phase == 'train':
loss.backward() # Compute gradient
optimizer.step() # One optimization step
# compute statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
print(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')
# Early "stopping"
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model = copy.deepcopy(model.state_dict())
time_elapsed = time.time() - since
print(f'\nTraining complete in {time_elapsed // 60:.0f}m {time_elapsed % 60:.0f}s')
print(f'Best val Acc: {best_acc:4f}')
# load best model weights of g obtained from early stopping
model.load_state_dict(best_model)
# returns g
return model
trained_model = train_model(model=model, criterion=criterion, optimizer=optimizer, num_epochs=100)
Epoch 1/100 ----------
CNNs with G-Invariances¶
Image invariances¶
Note that our vectorization of image patches leave the output of the filter rotation-sensitive.
- That is, consider the following image of a bird and the various rotation orientations that patches of this bird can be found in images:
Ideally, we would like patches to be permutation-invariant:¶
| Patch Version 1 | Patch Version 2 | Patch Version 3 |
|---|---|---|
Solution 1: Invariances via Data Agumentation (Most Common & Most Flexible)¶
Ideally, CNNs should be trained to be translation and rotation-invariant. However, existing CNN architectures are not rotation and translation invariant.
Cropping, Rotation, Translation, Illumination are data augmentation hacks that can help a neural network become more rotation / translation invariant
At each mini-batch gradient descent, randomly rotate, translate, and change the illumination of the mini-batch images
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(size=(224,224), scale=(0.6, 1.0), ratio=(0.75, 1.3333333333333333), interpolation=2), #interpolation=PIL.Image.BILINEAR
transforms.RandomHorizontalFlip(),
transforms.RandomRotation(degrees=(-30,30), resample=False, expand=False, fill=(0,0,0)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) # mean and std of ImageNet
]),
'val': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop((224,224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) # mean and std of ImageNet
]),
}
Solution 2: G-Invariances (via Invariant Subspaces)¶
Consider a set of linear transformations $\mathcal{T}$ that we want our neural network filter output $F(\text{vec}({\bf M})) = \sigma([\text{vec}({\bf M})^T,1] \: \text{vec}({\bf W}))$ to be invariant to a transformation: $$ F(\text{vec}({\bf M}); {\bf W}) = F(T(\text{vec}({\bf M})); {\bf W}), \quad \forall T \in \mathcal{T}. $$
But if we take an arbitrary ${\bf W}$, $F(\cdot; {\bf W})$ will not be invariant to transformations.
- Assume the set $\mathcal{T}$ is a linear transformation group, which implies satisfying six properties:
- (automorphism) $\forall T \in \mathcal{T}$, both input and the output of $T$ are images of the same size;
- (identity) $I(x)=x$, $I \in \mathcal{T}$;
- (is closed under composition) $\forall T,T' \in \mathcal{T}$, $T \circ T' \in \mathcal{T}$, where $T \circ T'(x) = T(T'(x))$;
- (associative) $\forall T,T',T^\dagger \in \mathcal{T}$, $T \circ (T' \circ T^\dagger) = (T \circ T') \circ T^\dagger$;
- (has inverses) $\forall T \in \mathcal{T},$ $\exists T^{-1} \in \mathcal{T}$ s.t.\ $T^{-1} \circ T = I$; and
- (is linear) $T \in \mathcal{T}$ is a linear function (a matrix).
Example:
- Consider an input $\text{vec}({\bf M}) \in \mathbb{R}^{3 n^2}$ represents a vectorized $n\times n$ RGB image.
- Examples of linear transformation groups:
- $\mathcal{T}_\text{rot} \equiv \{T^{(k)}\}_{k\in \{0^\circ,90^\circ,180^\circ,270^\circ\}}$, which rotates the image by $k$ degrees,
- $\mathcal{T}_\text{vflip} \equiv \{T^{(v)}, T^{(0)}\}$, which flips the image vertically.
- $\mathcal{T}_\text{hflip} \equiv \{T^{(h)}, T^{(0)}\}$, which flips the image horizontally.
Known result (see Lemma 2 (Mouli & Ribeiro, 2020)): Let $\bar{T} = \frac{1}{|\mathcal{T}|} \sum_{T \in \mathcal{T}} T$ and let $\{{\bf v}_k\}_{k=1}^K$, where ${\bf v}_k \bar{T} = {\bf v}_k$ be the left eigenvector of $\bar{T}$ with eigenvalue one.
Consider the convolutional filter ${\bf W}'$ $$ \text{vec}({\bf W}') = \sum_{k=1}^K \alpha_k {\bf v}_k , \quad \alpha_k \in \mathbb{R}, $$ where $\alpha_1,\ldots,\alpha_K$ are the new CNN filter parameters we need to learn.
Then, $$ F(\text{vec}({\bf M}); {\bf W}) = F(T(\text{vec}({\bf M})); {\bf W}), \quad \forall T \in \mathcal{T}. $$
G-Invariant Convolution Layer¶
Hence, we can achieve G-invariance if replace nn.Conv2d with the following InvariantConv2D layer
- Note that one also must make the rest of the CNN architecture G-invariant
class InvariantConv2D(nn.Module):
# Invariant 2D convolutional layer.
# Works like Conv2D (by Chandra Mouli & Bruno Ribeiro)
def __init__(
self,
in_channels,
out_channels,
precomputed_basis,
kernel_size=3,
stride=1,
padding=0,
bias=True,
penaltyAlpha=0,
):
super().__init__()
self.ksize = kernel_size
kernel_size = _pair(kernel_size)
stride = _pair(stride)
padding = _pair(padding)
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.basis = precomputed_basis
# The dimension one at the end is needed in the tensor, as we will use it to broadcast the
# coefficient parameters over the basis dimension
self.weights = nn.Parameter((out_channels, self.in_channels, self.basis.shape[0], 1), requires_grad=True)
if bias:
self.bias = nn.Parameter((out_channels),requires_grad=True)
else:
self.register_parameter("bias", None)
self.reset_parameters()
def reset_parameters(self):
n = self.in_channels
for k in self.kernel_size:
n *= k
stdv = 1.0 / math.sqrt(n)
self.weights.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input):
if self.basis.device != input.device:
self.basis = self.basis.to(input.device)
new_weights = torch.mul(self.weights, self.basis)
new_weights = new_weights.sum(dim=-2)
# Unvectorize
# Result after unvectorize: torch.Size([out_channels, in_channels, kernel_size[0], kernel_size[1]])
new_weights = new_weights.reshape(
self.out_channels,
self.in_channels,
self.kernel_size[0],
self.kernel_size[1],
)
# Input shape: torch.Size([minibatch, in_channels, iH, iW])
# Output shape: torch.Size([minibatch, out_channels, oH, oW])
out = F.conv2d(
input, weight=new_weights, bias=None, stride=self.stride, padding=self.padding
)
# One bias per channel
if self.bias is not None:
bias = self.bias.view(1, self.out_channels, 1, 1)
out = out + bias
return out