Introduction to Machine Learning

# Weekly Homework 7: Old Japanese Characters

### Author:

University of Redlands - DATA 301

Prof: Joanna Bieri joanna_bieri@redlands.edu

Class Website


Due Wednesday 11/11 at 11:59pm. This covers Day 13 and Day 14, and uses batch normalization from Day 12.

Can a network learn to read handwriting that most people today can not read? This week the data is pictures of Kuzushiji, the cursive style of Japanese writing used in classical Japanese books. Most people in Japan today can not read books written more than 150 years ago, and there are millions of them! (That comes from the paper that made this dataset, arxiv.org/abs/1812.01718.) You build a CNN, watch it overfit, and then use dropout and early stopping to fix it. Just like Weekly Homework 6, you write the whole process in one cell, and the comments in each code cell outline the steps for you.

GOALS:

  1. Look at picture data and make a guess about which classes will be hard.
  2. Build an MLP baseline on the flattened pictures.
  3. Write the whole training process for a CNN with batch normalization, then add dropout and early stopping, and compare.
  4. Open the test set once and explain what the model can and can not do.

What you can copy. Copy freely from the Day 12, 13 and 14 notes and the practice problems, and change the names. The “What this looks like in real life” cells at the end of the Day 13 and Day 14 notes are your best guide for Parts 2 and 3. If you want to write or use helper functions that is okay too, just comment each line so it is clear you understand what is going on. Every sentence you write is yours.

Make your guess first. Question 1b asks for a guess before you train anything. Write it down and do not change it later, even if it turns out wrong! Being wrong is how you learn something from Part 4.

The data. data/kmnist_small.npz. These are 7,000 pictures from Kuzushiji-MNIST, a dataset made by the Center for Open Data in the Humanities (CODH) in Japan to get machine learning people interested in classical Japanese literature. Each picture is one handwritten character from an old book, 28 by 28 pixels, black and white, just like Fashion MNIST. There are 10 classes, and each one is a hiragana character (a sound in Japanese). We write them with their English sounds:

label 0 1 2 3 4 5 6 7 8 9
character o ki su tsu na ha ma ya re wo

All 7,000 pictures come from the KMNIST training set. We use 5,000 of them to train and validate, and 2,000 are kept aside as our test set. Source and license: “KMNIST Dataset” (created by CODH), adapted from “Kuzushiji Dataset” (created by NIJL and others), doi:10.20676/00000341, CC BY-SA 4.0. More at github.com/rois-codh/kmnist.

How long does it take? Plan on about two hours. All of the code together runs in a few minutes on a laptop.

How to turn this in. Your repository on GitHub is your submission. There is nothing to hand in on Canvas.

  1. The finished work is on your main branch.
  2. It is pushed to GitHub before the deadline.
  3. Your name is on the Author line at the top of this notebook.
git add .
git commit -m "Weekly homework 7"
git push

I grade from whatever is on GitHub at the deadline. If it is not pushed, I cannot see it.


Part 1: Look at the pictures

The code in this part is given. Run it and look at the output.

1a. How many training pictures are there of each character? Why does that make accuracy a fair way to score a model on this data? (Think back to Day 5: when is accuracy a bad score?)

1b. Look at the grid of pictures. Each row is one character. Pick one row where the pictures of the same character look very different from each other and describe what you see. Then make a guess: which two characters do you think the network will mix up the most, and why? Write your guess down now and do not change it later!

# RUN THIS. Imports, and load the pictures.
import copy
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.utils.data import TensorDataset, DataLoader

data = np.load("data/kmnist_small.npz")                     # a .npz file holds several numpy arrays
class_names = ["o", "ki", "su", "tsu", "na", "ha", "ma", "ya", "re", "wo"]

train_images = data["train_images"]                         # 5000 pictures, 28 x 28, whole numbers 0 to 255
train_labels = data["train_labels"]                         # 5000 labels, 0 to 9
print("pictures:", train_images.shape, "  labels:", train_labels.shape)

# How many pictures of each character?
counts = np.bincount(train_labels)                          # counts[k] = how many labels are equal to k
for k in range(10):
    print(class_names[k], counts[k])
pictures: (5000, 28, 28)   labels: (5000,)
o 503
ki 493
su 492
tsu 475
na 493
ha 498
ma 488
ya 475
re 533
wo 550
# RUN THIS. 8 pictures of each character, one character per row.
fig, axes = plt.subplots(10, 8, figsize=(8, 10.5))
for k in range(10):
    examples = np.where(train_labels == k)[0][:8]           # the positions of the first 8 pictures of character k
    for j in range(8):
        ax = axes[k, j]
        ax.imshow(train_images[examples[j]], cmap="gray")
        ax.set_xticks([])
        ax.set_yticks([])
    axes[k, 0].set_ylabel(class_names[k], rotation=0, fontsize=14, labelpad=20)
plt.tight_layout()
plt.show()

Your answers here.


Part 2: Split, and a baseline

The split is given: the first 4,000 pictures are for training and the last 1,000 are for validation. The test pictures stay in the file until Part 4.

Our baseline is the network we already know from Day 14: an MLP on the flattened pictures. It is the number our CNN has to beat. You write it, in one cell, like the end of the Day 14 notes.

2a. What is the MLP’s validation accuracy after 10 epochs? How many of the 1,000 validation pictures does it get wrong? How does that compare to guessing (there are 10 characters)?

# RUN THIS. Pixels from 0 to 1, the shape a CNN wants, and the split.
images = torch.tensor(train_images, dtype=torch.float32) / 255     # pixels from 0 to 1
images = images.reshape(-1, 1, 28, 28)                              # (pictures, channels, height, width)
labels = torch.tensor(train_labels)

X_train = images[:4000]
y_train = labels[:4000]
X_valid = images[4000:]
y_valid = labels[4000:]
train_data = TensorDataset(X_train, y_train)                        # pair the pictures with the labels for the DataLoader

print("training pictures:  ", X_train.shape)
print("validation pictures:", X_valid.shape)
training pictures:   torch.Size([4000, 1, 28, 28])
validation pictures: torch.Size([1000, 1, 28, 28])
# 2a: the MLP baseline, the whole process in one cell
# NO CONVOLUTION HERE

# Step 1: torch.manual_seed(42), then mlp = nn.Sequential(...)
#         nn.Flatten(), nn.Linear(784, 100), nn.ReLU(), nn.Linear(100, 10)

# Step 2: train_loader, a DataLoader of train_data with batch_size=32 and shuffle=True,
#         loss_fn = nn.CrossEntropyLoss(), and the optimizer torch.optim.Adam with lr=0.001

# Step 3: the training loop for 10 epochs. For every epoch:
#           mlp.train()
#           the five steps for every batch: zero_grad, scores, loss, backward, optimizer.step()
#           mlp.eval(), then inside torch.no_grad() the validation accuracy:
#               y_pred = mlp(X_valid).argmax(dim=1)
#               accuracy = (y_pred == y_valid).float().mean().item()
#           print the epoch and the accuracy

Your answers here.


Part 3: A CNN, then dropout and early stopping

Now the CNN. Write it the way we did at the end of the Day 13 and Day 14 notes: everything in one cell. There is one new thing in the loop. After every epoch we save the training accuracy and the validation accuracy, because we want to compare them (just like we compared training and validation RMSE on Day 13).

3a. Write the first cell below: a CNN with two rounds of nn.Conv2d, nn.BatchNorm2d, nn.ReLU() and nn.MaxPool2d(2), then nn.Flatten() and one nn.Linear layer with 10 scores. Train it with Adam for 20 epochs. How does its validation accuracy compare to the MLP? Look at the training accuracy too. What is happening to it, and what does that tell you?

3b. Copy your cell into the next cell and add two things: an nn.Dropout(p=0.5) right after nn.Flatten(), and early stopping with a patience of 10 and at most 50 epochs. Which epoch was best, and when did it stop? Compare the training accuracy of this model to the 3a model. Why is it lower, and why is that okay?

Then run the plot cell.

3c. Which model would you keep, and why? Use the plot and the numbers. Then explain why the model.train() and model.eval() lines matter even more for this model than for the MLP. (Hint: two of the layers in it do something different in training mode.)

# 3a: a CNN with batch normalization, the whole process in one cell

# Step 1: torch.manual_seed(42), then cnn = nn.Sequential(...)
#         Round 1: nn.Conv2d(1, 16, kernel_size=3, padding=1), nn.BatchNorm2d(16), nn.ReLU(), nn.MaxPool2d(2)
#         Round 2: nn.Conv2d(16, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2)
#         Then nn.Flatten() and nn.Linear(?, 10). Work out the ? from the shape after the second pooling layer.

# Step 2: train_loader, loss_fn and the Adam optimizer (lr=0.001), the same as Part 2

# Step 3: two empty lists, train_accuracy_cnn = [] and valid_accuracy_cnn = []

# Step 4: the training loop for 20 epochs. For every epoch:
#           cnn.train()
#           the five steps for every batch
#           cnn.eval(), then inside torch.no_grad():
#               the accuracy on X_train, y_train    -> append it to train_accuracy_cnn
#               the accuracy on X_valid, y_valid    -> append it to valid_accuracy_cnn
#           print both after the first epoch and every 5 epochs
# 3b: copy your 3a cell here and add dropout and early stopping
#     Change the model name to dropout_cnn and the list names to train_accuracy_dropout and valid_accuracy_dropout.
#
# Step 1: add nn.Dropout(p=0.5) right after nn.Flatten()
#
# Step 2: before the loop, set up early stopping like the end of the Day 13 notes:
#         patience = 10, best_accuracy = 0, best_weights = None, epochs_without_improving = 0
#         (we want the accuracy to go UP, so we start at 0 and look for a bigger number)
#
# Step 3: train for at most 50 epochs. At the end of every epoch, after you append the accuracies:
#           if valid_acc > best_accuracy: save best_accuracy, best_epoch = epoch + 1,
#               best_weights = copy.deepcopy(dropout_cnn.state_dict()), and set epochs_without_improving = 0
#           otherwise add 1 to epochs_without_improving
#           if epochs_without_improving == patience: print when it stopped and break
#
# Step 4: after the loop, put the best weights back with dropout_cnn.load_state_dict(best_weights)
#         and print the best epoch and the best validation accuracy
# RUN THIS after 3a and 3b. The learning curves of both CNNs, side by side.
fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)    # sharey=True puts both plots on the same y axis

epochs_cnn = range(1, len(train_accuracy_cnn) + 1)
axes[0].plot(epochs_cnn, train_accuracy_cnn, label="training accuracy")
axes[0].plot(epochs_cnn, valid_accuracy_cnn, label="validation accuracy")
axes[0].set_title("3a: CNN with batch norm")

epochs_dropout = range(1, len(train_accuracy_dropout) + 1)
axes[1].plot(epochs_dropout, train_accuracy_dropout, label="training accuracy")
axes[1].plot(epochs_dropout, valid_accuracy_dropout, label="validation accuracy")
axes[1].axvline(best_epoch, color="gray", linestyle="--", label="best epoch")
axes[1].set_title("3b: plus dropout and early stopping")

for ax in axes:
    ax.set_xlabel("epoch")
    ax.set_ylim(0.8, 1.01)
    ax.legend()
    ax.grid()
axes[0].set_ylabel("accuracy")
plt.tight_layout()
plt.show()

print("3a CNN after 20 epochs:      train", round(train_accuracy_cnn[-1], 4), "  valid", round(valid_accuracy_cnn[-1], 4))
print("3b CNN at its best epoch", best_epoch, ": train", round(train_accuracy_dropout[best_epoch - 1], 4), "  valid", round(valid_accuracy_dropout[best_epoch - 1], 4))

Your answers here.


Part 4: The test set, once

Now the 2,000 test pictures come out of the file. BEWARE! They get exactly the same steps as the training pictures: divide by 255 and reshape. Nothing is fit on them, there is nothing to fit.

4a. Compute the test accuracy of the model you chose in 3c, one time. Compare it to its validation accuracy, and to the MLP’s accuracy on the same test pictures. We used the validation set to make choices (which model, which epoch). What does the test accuracy tell you that the validation accuracy could not? Why do we only look at the test set once?

4b. The second cell (given) shows the accuracy for each character, the two characters the model mixes up the most, and some pictures it got wrong. Which character is hardest? Does it match your guess from 1b? Look at the wrong pictures. Would you have gotten them right?

4c. A librarian wants to use your model to help turn old Japanese books into typed text. Write three or four sentences to them. Say what the model does, how often it is wrong, and one reason to be careful with it. No jargon: no “accuracy”, no “CNN”, no “dropout”.

# 4a: the test set, once
# Step 1: X_test from data["test_images"] (float32 tensor, divide by 255, reshape to (-1, 1, 28, 28))
#         and y_test from data["test_labels"] (a tensor)
# Step 2: your chosen model in .eval() mode, and inside torch.no_grad():
#         y_pred_test = the model's predictions on X_test (argmax), and test_accuracy against y_test
# Step 3: the MLP's accuracy on the same test pictures, call it mlp_test_accuracy
# Step 4: print the test accuracy, the model's validation accuracy, and mlp_test_accuracy
# RUN THIS after 4a. 4b: the accuracy for each character, the biggest mix-up, and some mistakes
for k in range(10):
    this_char = (y_test == k)                               # the test pictures of character k
    acc_k = (y_pred_test[this_char] == k).float().mean().item()
    print(class_names[k].ljust(4), "  test pictures:", this_char.sum().item(), "  accuracy:", round(acc_k, 3))

# Count every (real, predicted) pair the model got wrong, and find the most common one
mixups = np.zeros((10, 10), dtype=int)
for real, pred in zip(y_test.tolist(), y_pred_test.tolist()):
    if real != pred:
        mixups[real, pred] = mixups[real, pred] + 1
both_ways = mixups + mixups.T                               # count "a read as b" and "b read as a" together
a, b = np.unravel_index(both_ways.argmax(), both_ways.shape)
print()
print("most mixed up:", class_names[a], "and", class_names[b], "  ",
      mixups[a, b], "times", class_names[a], "was read as", class_names[b], "and",
      mixups[b, a], "times", class_names[b], "was read as", class_names[a])

# The first 10 test pictures it got wrong
wrong = np.where(y_pred_test != y_test)[0][:10]
fig, axes = plt.subplots(2, 5, figsize=(10, 4.8))
for ax, i in zip(axes.flatten(), wrong):
    ax.imshow(X_test[i, 0], cmap="gray")
    ax.set_title("real " + class_names[y_test[i]] + ", said " + class_names[y_pred_test[i]])
    ax.axis("off")
plt.tight_layout()
plt.show()

Your answers here.