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:
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?
- The app refuses the photos
- The model gets inputs far outside anything it saw in training, and its answers become garbage, with no error message
- Nothing: the model adapts
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.
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?
- Some breed, possibly with high confidence: it can only choose among breeds
- "Not a pet"
- Nothing
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?
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
- The network's first layer multiplies each pixel by weights that were tuned on normalized pixels, numbers between about −2.1 and 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.
- 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.
- 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.
- 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?
- Just the top label
- An error
- Both, with their probabilities, or a "not sure" message
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?
- It's faster
- It's guaranteed to be the same recipe the weights were trained with, so training and the app can't drift apart
- Gradio requires it
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:
- Epoch: one full pass over the training data. Batch: the handful of examples used for one gradient step.
- Optimizer: the rule that turns gradients into weight updates; Adam (or AdamW) is the usual default.
- Tensor: PyTorch's array, which can live on a GPU, a processor that does matrix products tens of times faster.
- Pretrained: already trained on a big dataset; fine-tuning: training it a little more on your own task.
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
- Photos that aren't in its world. A pet-breed model shown a car still names a breed, sometimes with high probability. Add a check (a general model asking "is this an animal?") or say "not sure" when the top probability is low.
- Phone photos lying on their side. Phones often save a photo sideways with a note saying "rotate me". Code that ignores the note feeds the network a sideways picture.
ImageOps.exif_transposein Pillow applies it. - A free app that falls asleep. Free Spaces go to sleep after a while without visitors, and the next visitor waits while it wakes up and loads the model. Fine for a demo; a product needs a paid, always-on host (stage 7).
6. What to carry forward
- A deployed model is input → preprocessing → model → postprocessing; the preprocessing must match training exactly.
- Image models want a fixed size, a 0–1 scale, per-channel normalization and a (batch, channels, height, width) array.
- Logits → softmax → the top few labels with probabilities; show uncertainty, don't hide it.
- A classifier always picks one of its labels, even for things it has never seen.
- Gradio wraps a function in a web page; Hugging Face Spaces hosts it for free.
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