Introduction to Machine Learning

# Practice Problems Day 14

### Author:

University of Redlands - DATA 301

Prof: Joanna Bieri joanna_bieri@redlands.edu

Class Website


These are practice problems. They are not graded and you do not turn them in. They are here so you can practice today’s code before the weekly homework. Weekly Homework 7 assumes you have done them. Plan on about 45 minutes. Each training run takes a minute or two on a laptop.

Solutions are in HW-day14-solutions.ipynb in this folder. Try every problem yourself first, then check your work.

Reading: Geron chapter 12, Convolutional Layers, Pooling Layers and CNN Architectures.

GOALS:

  1. Build a small CNN with nn.Conv2d, nn.MaxPool2d and nn.Flatten.
  2. Work out the shapes, so the last nn.Linear layer gets the right size.
  3. Explain a convolution in words.

How much of this should you write yourself? The data cell is given. Problem 1 gives you the training loop, you write the layers. Problem 2 lists the steps. Problem 3 is words only. The Optional exploration at the end is extra, only if you are curious.

Save your work. Commit and push when you are done, so you have your code for the weekly homework and the exam:

git add .
git commit -m "Day 14 practice"
git push

# RUN THIS. The Fashion MNIST pictures from the notes, as tensors.
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torchvision
from torch.utils.data import TensorDataset, DataLoader

fashion = torchvision.datasets.FashionMNIST(root="data", train=True, download=True)
class_names = fashion.classes

images = fashion.data[:12000].float() / 255     # pixels from 0 to 1
labels = fashion.targets[:12000]
images = images.reshape(-1, 1, 28, 28)          # (pictures, channels, height, width)

X_train = images[:10000]
y_train = labels[:10000]
X_valid = images[10000:]
y_valid = labels[10000:]
train_data = TensorDataset(X_train, y_train)

print("training pictures:  ", X_train.shape)
print("validation pictures:", X_valid.shape)

Problem 1: A CNN with one round of convolution and pooling

What to copy, what to write: The training loop is given. Write the layers the comments ask for.

1a. Build a CNN with one round: nn.Conv2d with 1 channel in, 8 filters, kernel_size=3 and padding=1, then nn.ReLU(), then nn.MaxPool2d(2), then nn.Flatten(), then an nn.Linear layer that gives 10 scores. Train it for 5 epochs.

1b. What is the shape of each picture after the pooling layer (channels, height, width)? Use it to explain the number you put in the nn.Linear layer.

1c. Compare your final validation accuracy to the notes: the MLP got 0.858 and the CNN with two rounds got 0.877.

torch.manual_seed(42)
model = nn.Sequential(
    # Write the nn.Conv2d layer: 1 channel in, 8 filters, kernel_size=3, padding=1

    nn.ReLU(),
    nn.MaxPool2d(2),
    nn.Flatten(),
    # Write the nn.Linear layer. How many numbers come out of nn.Flatten()? 10 scores go out.

)

# The batches, the loss and the optimizer
train_loader = DataLoader(train_data, batch_size=32, shuffle=True)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

# The training loop
n_epochs = 5
for epoch in range(n_epochs):
    model.train()
    for X_batch, y_batch in train_loader:
        optimizer.zero_grad()
        scores = model(X_batch)
        loss = loss_fn(scores, y_batch)
        loss.backward()
        optimizer.step()

    model.eval()
    with torch.no_grad():
        y_pred = model(X_valid).argmax(dim=1)
        accuracy = (y_pred == y_valid).float().mean().item()
    print("epoch", epoch + 1, "  valid accuracy:", round(accuracy, 4))

Your answers here.


Problem 2: Add a second round (steps outlined)

What to copy, what to write: Copy your Problem 1 cell and change the model. The training loop stays the same.

2a. Add a second round after the first pooling layer: nn.Conv2d with 8 channels in and 16 filters, kernel_size=3, padding=1, then nn.ReLU(), then nn.MaxPool2d(2). Fix the size of the nn.Linear layer and train it for 5 epochs.

2b. Count the numbers to learn in your Problem 1 model and your Problem 2 model. Which one has more? Which one did better?

# Step 1: copy your Problem 1 cell

# Step 2: after the first nn.MaxPool2d(2), add nn.Conv2d(8, 16, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(2)

# Step 3: work out the new shape after the second pooling layer, and fix the nn.Linear size

# Step 4 (2b): count the numbers to learn with a for loop over model.parameters(), adding up p.numel()

Your answers here.


Problem 3: In words

3a. Explain what a convolution layer does to a friend in DATA 101 who has never seen one. Use the words filter and feature map. Three or four sentences, no code.

3b. A classmate gets this error when they train their CNN:

RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x1568 and 784x10)

Their last layer is nn.Linear(784, 10). What went wrong, and what should the layer be?

Your answers here.


Optional exploration

Only if you are curious. Nothing here is needed for the weekly homework.

A. Use your Problem 2 model to find 5 validation pictures it gets wrong. Plot them with their real class and the predicted class as the title. Would you have gotten them right?

B. Add nn.BatchNorm2d(8) right after the first nn.Conv2d and nn.BatchNorm2d(16) right after the second. Does it change the accuracy on this small CNN?

# your code here

Your answers here.