AI from scratch · Start 4 · Stage 0: start here

Your first shared model

A model on your laptop helps nobody else. In this lesson you see what it takes to put one on the web: the pieces every deployed model has, what happens to a photo before a network sees it, how scores become an answer, and the two free tools (Gradio and Hugging Face Spaces) that turn a trained model into a page anyone can use. The practice notebook does it for real: you train a pet-breed classifier and get a link you can send to a friend.

1. What "deploying a model" means

Training produces a file of numbers: the weights. To be useful, three more things wrap around it:

InputA photo from a person: any size, any format.
→
PreprocessResize and scale it into exactly the array shape and range the model was trained on.
→
ModelThe architecture plus the saved weights: numbers in, scores out.
→
PostprocessScores → probabilities → the top few labels, shown in the interface.

Get the preprocessing even slightly different from training (another image size, colors in a different order, a missing normalization) and a model that scored 95% in testing quietly turns useless. It's the most common deployment bug, so sections 3 and 4 do both steps by hand.

A team trains on photos scaled to 0–1, but the app sends raw pixel values 0–255. What happens?

That's why preprocessing ships with the model, as code, not as a note in a README: the same function must run in training and in the app.

A deployed model is weights plus the exact preprocessing, the code that turns scores into an answer, and an app around them.

2. Try one

Below is MobileNet, a small network trained on ImageNet (1.2 million photos, 1,000 categories), running entirely in your browser. Pick a photo, or use the sample. Its top five guesses and their probabilities appear next to it.

The photo being classified

Loading the model (about 4 MB)…

The street sample gets odd answers ("scoreboard", "mobile home"): ImageNet photos show one main object, so a busy street is outside what MobileNet learned. For counting cars, a detector is the right tool (chapter 9). Try something that isn't in its 1,000 categories at all, like a face, a drawing, or a screenshot. It still answers, often confidently. A classifier can only choose among the labels it knows; nothing in it says "none of these". That's worth remembering when you put your own model in front of people.

Your pet-breed model gets a photo of a car. What will it say?

Softmax spreads 100% over the classes it knows. Apps handle this with a confidence threshold ("not sure"), an extra "other" class, or a first model that checks what kind of picture it is.

A model trained on certain photos answers best on photos like them, and always answers with one of its classes.

3. What the model needs from a photo

Pretrained image models expect the exact recipe used in training. For the ImageNet family it's: resize so the short side is 256 pixels, cut the central 224×224 square, scale pixel values from 0–255 to 0–1, then normalize each color channel with ImageNet's mean and standard deviation, and arrange the array as (batch, channels, height, width). Here's that recipe on a made-up 300×400 image:

How many numbers does the network receive for one 224×224 color image?

\(224 \times 224 \times 3 = 150{,}528\). In PyTorch, torchvision's weights.transforms() does all five steps for you, which is the safest choice: it's the recipe the weights were trained with.

Resize, crop, scale and normalize exactly as in training, or the model quietly gets worse.

Why the preprocessing has to match exactly
  1. The network's first layer multiplies each pixel by weights that were tuned on normalized pixels, numbers between about −2.1 and 2.2.
  2. Send raw pixels (0 to 255) through the same normalization and a white pixel becomes about 1,111 instead of 2.2: every input is hundreds of times bigger than anything seen in training.
  3. Those huge numbers flow through every layer, the final scores become enormous, and softmax puts nearly 100% on some class that has nothing to do with the photo.
  4. Smaller mismatches fail more quietly: colors in another order (blue first instead of red) make the "red" filters read blue, and a different crop shows the network a different part of the object. Accuracy drops a few points or a lot, with no error message.
  5. That's why the app takes the preprocessing from the same place as the weights.

4. From scores to an answer

The network returns one score per class, called logits. Softmax (chapter 5) turns them into probabilities; the app shows the top few. Gradio's label widget expects exactly this: a dictionary from label to probability.

The top probability is 0.45 and the next is 0.40. What should a careful app show?

Showing the top few with probabilities, as Gradio's Label does, lets people see when the model is torn. Hiding uncertainty is how a decent model earns a bad reputation.

Softmax turns the network's scores into probabilities, and a careful app shows the top few, not just one.

5. The app: Gradio, and a home on Hugging Face Spaces

Gradio is a Python library that builds a web interface around any function: you say what goes in (an image) and what comes out (a label with probabilities), and it makes the page. This is a whole app, the one the practice notebook writes as app.py:

import gradio as gr, torch, torchvision, json

labels = json.load(open("labels.json"))
model = torchvision.models.resnet18(num_classes=len(labels))
model.load_state_dict(torch.load("model.pt", map_location="cpu"))
model.eval()
preprocess = torchvision.models.ResNet18_Weights.DEFAULT.transforms()   # the training recipe

def predict(img):
    with torch.no_grad():
        p = model(preprocess(img)[None]).softmax(-1)[0]
    return {labels[i]: float(p[i]) for i in p.argsort(descending=True)[:5]}

gr.Interface(predict, gr.Image(type="pil"), gr.Label(num_top_classes=5)).launch()

Hugging Face Spaces hosts apps like this for free (a small CPU, which is plenty for one image at a time). A Space is a Git repository with three files: app.py, requirements.txt (the libraries), and the model files. Push them and Spaces installs, starts the app and gives it a public address. The notebook does it with the huggingface_hub library in a few lines, using a free account's access token.

Why does the app load the preprocessing from torchvision's weights object instead of writing its own?

One source of truth for preprocessing removes the most common deployment bug from section 1.
Words you'll meet in the notebooks

The practice notebooks use a few training words before the lessons that explain them in depth. For now:

The glossary has every term on the path in one place.

Gradio builds the page around a function, and a Hugging Face Space hosts it free from three files.

Where it breaks: what real users send

6. What to carry forward

All lessons: AI from scratch. Demo model: MobileNet for TensorFlow.js (Apache 2.0). Sample photos: the PyTorch vision gallery (BSD) and NYC DOT's public traffic cameras. fast.ai's lesson 2 (course.fast.ai) deploys a model the same way.

Last updated