Deep Learning Foundations / Module 2 of 8
15-min lesson

Image Classification — American Sign Language

Loading the Data · Visualizing the Data · Build the Model · Training the Model

The American Sign Language Dataset

Sign Language MNIST has the same spirit as regular MNIST — 28×28 grayscale images — but real-world stakes: 24 letters of the ASL alphabet (A–Y, skipping J and Z, since both require hand motion that a single still image can't capture). It ships as a CSV: each row is one image, flattened into a label column plus 784 pixel columns.

Loading the Data

Pandas reads the CSV directly. We pop the label column off, normalize pixels to 0–1, then reshape each flat 784-length row back into its real shape: 1 channel, 28 rows, 28 columns.

import pandas as pd

train_df = pd.read_csv('sign_mnist_train.csv')
valid_df = pd.read_csv('sign_mnist_valid.csv')

y_train = train_df.pop('label').values
x_train = train_df.values / 255.0
x_train = x_train.reshape(-1, 1, 28, 28)

A custom Dataset wraps the tensors so a DataLoader can batch and shuffle them, same as Module 1. This is the first time we've written our own Python class, so before the code — a quick detour on what these four pieces actually mean:

Python detour: a class is a blueprint for a custom "thing" that bundles data together with the actions that work on it. self just means "this particular one" — it's how the thing refers to its own data. __init__ runs once, automatically, the moment you create one of these things — it's where you set up its starting data. __len__ and __getitem__ are two specific behaviors PyTorch's DataLoader expects every dataset to have: "how many items do you hold?" and "hand me item number i." You're not calling these yourself — DataLoader calls them for you, behind the scenes.
from torch.utils.data import Dataset, DataLoader
import torch

class ASLDataset(Dataset):
    def __init__(self, x, y):
        self.x = torch.tensor(x, dtype=torch.float32)
        self.y = torch.tensor(y, dtype=torch.long)
    def __len__(self):
        return len(self.x)
    def __getitem__(self, idx):
        return self.x[idx], self.y[idx]

train_loader = DataLoader(ASLDataset(x_train, y_train), batch_size=32, shuffle=True)

Visualizing the Data

Before training anything, look at what you're feeding the model — it catches loading bugs early (wrong reshape, flipped labels) that are much harder to spot once training's underway.

import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 5, figsize=(10, 2))
for i, ax in enumerate(axes):
    ax.imshow(x_train[i][0], cmap='gray')
    ax.set_title(f"label: {y_train[i]}")
    ax.axis('off')
plt.show()

Build the Model

With 24 letters instead of 10 digits, the model gets a bit more capacity — two hidden layers instead of one:

import torch.nn as nn

model = nn.Sequential(
    nn.Flatten(),
    nn.Linear(784, 512),
    nn.ReLU(),
    nn.Linear(512, 512),
    nn.ReLU(),
    nn.Linear(512, 25)  # 25 label slots; index 9 ("J") stays unused
)

Training the Model

Same four-step loop as Module 1 — but now we also check performance on data the model has never trained on, using a validation set. model.eval() switches off training-only behavior, and torch.no_grad() skips gradient tracking since we're not updating weights. To score accuracy, output.argmax(dim=1) just picks, for each image, whichever of the 25 letters the model gave the highest score — that's the model's actual guess:

def get_accuracy(output, y):
    return (output.argmax(dim=1) == y).float().mean().item()

for epoch in range(20):
    model.train()
    train_acc = 0
    for x, y in train_loader:
        optimizer.zero_grad()
        output = model(x)
        loss = loss_fn(output, y)
        loss.backward()
        optimizer.step()
        train_acc += get_accuracy(output, y)

    model.eval()
    valid_acc = 0
    with torch.no_grad():
        for x, y in valid_loader:
            output = model(x)
            valid_acc += get_accuracy(output, y)
Train accuracy tells you if the model is learning. Validation accuracy tells you if it's actually understanding — or just memorizing.

Vocabulary

CSV
A plain-text table format — comma-separated values, one row per record.
Dataset (class)
A Python blueprint bundling data with the actions that work on it.
self
How an object refers to its own data, inside its own class.
Constructor (__init__)
Runs once, automatically, when a new object is created — sets up its starting data.
Validation set
Data the model never trains on, used to check if it's actually generalizing.
argmax
Finds the position of the highest value — here, the model's most confident guess.
model.eval() / model.train()
Switches the model between evaluation mode and training mode, since some layers behave differently in each.
torch.no_grad()
Skips gradient tracking, since prediction alone never needs to update weights.

15-min quiz