A Model by Hand: Weights, Scores and a First Guess

A model that sorts images into classes is, underneath, a short piece of arithmetic: it multiplies the numbers of an image by numbers of its own, adds the results up into one score for each class, and answers with the class whose score is highest. This page builds that arithmetic by hand with PyTorch tensors, starts it from random numbers, and measures how often such an untrained model is right, which gives the level that training later has to beat.

Inputs, parameters and a fixed computation

Two kinds of numbers meet inside a model. The inputs are what the model is given: for a small greyscale image of a handwritten digit, 28 rows of 28 pixels, that is 784 brightness values. The parameters are numbers the model keeps for itself. They do not come from the image, and they stay the same whichever image arrives.

The model is nothing more than a fixed computation on both. The steps (multiply, add, pick the largest) never change; only the parameters do. Training is the process of changing the parameters until the same steps give good answers. So when people say a model has "learned" something, what has actually changed is a set of numbers stored in tensors.

  • Input 784 pixel values
  • Parameters weights and biases
  • Fixed computation multiply, add
  • Scores one per class
  • Predicted class highest score
  • Input to Fixed computation
  • Parameters to Fixed computation: training changes these
  • Fixed computation to Scores
  • Scores to Predicted class

True or false?

Showing a model a new image changes its parameters.

False. The image is an input. Parameters change only when training adjusts them; using the model leaves them as they are.

Two models with the same computation but different parameters can give different answers for the same image.

True. The steps are identical, but the numbers they multiply by differ, so the scores and the answer can differ.

A score is a weighted sum plus a bias

The simplest way to turn many input values into one score is a weighted sum. Every input value gets its own weight, a parameter that says how much that value counts. You multiply each value by its weight, add all the products up, and then add one more parameter, the bias, which shifts the score up or down whatever the input is.

A weight can be positive or negative. A positive weight on a pixel means "a bright pixel here makes this class more likely", a negative one means the opposite, and a weight near zero means the pixel hardly matters for that class.

Take a tiny input of three pixel values, 0.0, 0.5 and 1.0, and one class, call it A, with weights 0.2, -0.1 and 0.4 and a bias of 0.1:

Score for class A
PixelValueWeight for AValue x weight
10.00.20.00
20.5-0.1-0.05
31.00.40.40
Sum of products0.35
Plus the bias0.10
Score0.45

Written as a formula, with \( x_1, x_2, x_3 \) the input values, \( w_1, w_2, w_3 \) the weights and \( b \) the bias, the score is:

$$score = x_1 w_1 + x_2 w_2 + x_3 w_3 + b$$

one weighted sum

One score is not enough to choose between classes, so each class gets its own set of weights and its own bias. A second class B, with weights -0.3, 0.6 and 0.1 and a bias of -0.2, scores the same input as \( 0 + 0.3 + 0.1 - 0.2 = 0.2 \). With ten digit classes and 784 pixels, that is 784 weights and one bias per class: 7,840 weights and 10 biases in all, every one of them a parameter.

True or false?

All classes share one set of weights, and only the bias tells them apart.

False. Each class has its own weights and its own bias. With shared weights the classes would differ only by a constant, and the same class would win for every input.

With 784 inputs and 10 classes, a model of this kind has 7,850 parameters.

True. 784 weights for each of 10 classes is 7,840, plus one bias per class gives 7,850.

Matrix multiplication: every weighted sum at once

Working out each score with its own loop would be slow and long to write. Matrix multiplication does all the weighted sums in one operation. Put the inputs in a table with one row per example, and the weights in a table with one column per class. Each entry of the result is one row of inputs combined with one column of weights: multiply them value by value and add up. That is exactly the weighted sum from the table above, without the bias.

In Python the operator for it is @ (the same as calling torch.matmul). The plain * does something else: it multiplies element by element and adds nothing up. Here are the two classes from before, applied to two examples in one line:

import torch

x = torch.tensor([[0.0, 0.5, 1.0],     # example 1
                  [1.0, 0.0, 0.5]])    # example 2
W = torch.tensor([[0.2, -0.3],         # weights of pixel 1 for A, B
                  [-0.1, 0.6],         # pixel 2
                  [0.4, 0.1]])         # pixel 3
b = torch.tensor([0.1, -0.2])          # bias for A, B

scores = x @ W + b
print(scores.shape)    # torch.Size([2, 2])

The result has one row per example and one column per class. The first row holds 0.45 and 0.2, the scores worked out by hand above; the second row, for the second example, holds 0.5 and -0.45. Adding b uses broadcasting: the one row of biases is added to every row of the result, so each class gets its own bias in every example.

The shape rule

Whether two tables can be multiplied, and what comes out, can be read from their shapes alone. For shapes \( (n, m) \) and \( (m, p) \):

  • the inner sizes, the last of the first and the first of the second, must be equal, because each row is paired value by value with each column;
  • the result takes the outer sizes: \( (n, p) \).
$$(n, m)\ @\ (m, p) \rightarrow (n, p)$$

inner sizes match, outer sizes remain

Reading shapes before multiplying
InputsWeightsResult
(2, 3)(3, 2)(2, 2): 2 examples, 2 scores each
(64, 784)(784, 10)(64, 10): 64 images, 10 scores each
(1, 784)(784, 10)(1, 10): one image, 10 scores
(64, 784)(10, 784)error: inner sizes 784 and 10 differ
(64, 28, 28)(784, 10)error: inner sizes 28 and 784 differ

Two practical points follow. An image stored as a 28 by 28 grid has to be reshaped into one row of 784 values before it meets a weight table of shape (784, 10), so a batch of images becomes shape (N, 784). And the two tensors should both hold floating-point numbers: pixel values stored as whole numbers from 0 to 255 are usually converted with .float() and divided by 255, so they run from 0 to 1.

True or false?

A tensor of shape (5, 784) can be multiplied by one of shape (784, 10), and the result has shape (5, 10).

True. The inner sizes are both 784, and the result keeps the outer sizes, 5 and 10.

Swapping the two tensors, (784, 10) @ (5, 784), gives the same result.

False. The order matters. Here the inner sizes are 10 and 5, which differ, so the product cannot be computed at all.

x * W and x @ W compute the same thing.

False. * multiplies matching elements and keeps them separate; @ also adds the products up into weighted sums.

Random starting weights and a seed

Before training, nobody knows what the weights should be, yet they need some value to start from. The usual choice is small random numbers.

They are random so that the weights of different classes differ from the start. If every weight were the same, every class would get the same score.

They are small so that the scores start out moderate. A score adds up 784 products, and when the weights are random, that sum grows roughly with the square root of 784, which is 28. Dividing the random weights by 28 cancels that growth and keeps each score at about the size of a single random number. The biases can simply start at zero.

import math
import torch

torch.manual_seed(0)                            # same random numbers every run
W = torch.randn(784, 10) / math.sqrt(784)      # one column of weights per class
b = torch.zeros(10)                             # one bias per class

x = torch.rand(64, 784)                         # stand-in for 64 flattened images
scores = x @ W + b
print(scores.shape)                             # torch.Size([64, 10])

torch.randn fills a tensor with random numbers drawn around 0, most of them between about -2 and 2. Here torch.rand (numbers between 0 and 1) only stands in for real images so the code runs on its own.

A computer's random numbers come from a fixed recipe that starts from a number called the seed. torch.manual_seed(0) sets that seed, so every run of the program draws the same "random" weights, gets the same scores and prints the same results. That makes a run repeatable: a change in the results comes from a change in the code, not from luck.

The repeat is exact only in the same environment. PyTorch's documentation states that completely reproducible results are not guaranteed across PyTorch releases or different platforms, and not between CPU and GPU runs, even with the same seed. So a number someone else measured with the same seed should come out about the same on your machine, not necessarily digit for digit.

True or false?

Setting the seed to the same value makes the starting weights identical on every computer and every PyTorch version.

False. A seed repeats the same numbers in the same environment. Across library versions, platforms or CPU and GPU, PyTorch does not guarantee identical results.

Starting every weight and every bias at exactly zero would give every class the same score for every input.

True. Each weighted sum would be 0, plus a bias of 0, so every class scores 0 and the classes cannot be told apart. Random weights break that symmetry.

The highest score is the answer

The model's output for one image is a row of scores, one per class. The scores are not probabilities and need not be positive; only their order matters here. The predicted class is the class with the highest score, and its position in the row is the class itself: position 0 is the digit 0, position 7 the digit 7.

Scores for one image, classes 0 to 9 (the highest, 0.91, is class 7)
  1. 0.12
  2. -0.31
  3. 0.05
  4. 0.48
  5. -0.07
  6. 0.22
  7. -0.18
  8. 0.91
  9. 0.33
  10. -0.25

The function that returns the position of the largest value is torch.argmax. A batch of scores has shape (N, 10): one row per example, with the classes running along dimension 1. So scores.argmax(dim=1) looks along each row and returns N whole numbers, one predicted class per example. The class dimension is removed in the process.

Leave out dim and argmax returns a single position instead, counted across the whole tensor laid out as one row, which is not what you want here. If two scores tie for the highest, the first of them wins.

preds = scores.argmax(dim=1)    # shape (64,): one class per image

True or false?

For scores of shape (64, 10), argmax(dim=1) returns 64 numbers, each between 0 and 9.

True. It finds the largest of the 10 scores in each of the 64 rows and returns its position.

A predicted class with a score of 0.91 means the model is 91% sure.

False. Scores are raw numbers, not probabilities. Only which score is highest is used to pick the answer.

Accuracy, and the level a guess reaches

Accuracy is the share of examples the model gets right: the number of predictions that equal the correct label, divided by the number of examples. Eight examples with five right give an accuracy of 5 / 8, which is 62.5%.

Eight predictions against their labels
Correct labelPredictedRight?
33yes
71no
00yes
44yes
94no
11yes
83no
22yes

In PyTorch the same count takes one line. Comparing the predictions with the labels using == gives a tensor of True and False. Converted with .float(), each True becomes 1.0 and each False 0.0, so their average is exactly the share that is right. .item() turns the one-element result into a plain Python number.

labels = torch.tensor([3, 7, 0, 4, 9, 1, 8, 2])
preds = torch.tensor([3, 1, 0, 4, 4, 1, 3, 2])

accuracy = (preds == labels).float().mean()
print(accuracy.item())    # 0.625

The level any model has to beat

An accuracy only means something next to what a pure guess would reach. With ten classes, picking one at random is right about one time in ten, so a pure guess scores about 10%. A model with random starting weights has learned nothing, and its accuracy lands near that level too, a little above or below it depending on the seed and the examples, because its random weights favour some classes over others by chance.

When the classes are not equally common, a second baseline matters: always answering the most common class. If one class makes up 11% of the examples, a model that never looks at the input scores 11%. A model only shows it has learned something from the images when it clearly beats both of these levels.

True or false?

An untrained model with random weights always scores exactly 10% on ten classes.

False. It scores about 10%. Its random weights favour some classes by chance, and the classes are rarely exactly equal in number, so the result lands near 10% rather than on it.

A model that reaches 12% accuracy on ten roughly balanced classes has learned very little.

True. 12% is barely above the 10% a pure guess reaches, so it is no real evidence of learning.