A PyTorch MNIST Digit Classifier: From Input Features to Output Scores
PyTorch
Machine Learning
Python
Jupyter
PyTorch nn.Linear: Tensor transformation of input to output feature
Author
Dennis Chua
Published
November 25, 2026
In an earlier post, we inspected our DigitClassifier, auditing the \(101,770\)float32 parameters sitting in memory, with self.layer1 = nn.Linear(784, 128) accounting for \(100,352\) of those weights on its own. Understanding where the numbers live in memory is half the picture; the other half is watching what they actually do once data starts moving through the network.
That forward pass comes down to one consistent rule: PyTorch layers transform the feature dimension while leaving the batch dimension untouched. Whether we are testing a single standalone layer or pushing a handwritten digit through an entire classifier, every step involves reshaping and projection of features encoded in tensors.
Isolating the Engine: How nn.Linear(20, 30) Projects Features
Before tracing a \(784\)-pixel image through our full classifier, it helps to strip away the surrounding architecture and observe a single nn.Linear module in isolation. Below, we instantiate a layer configured to map a smaller feature set of \(20\) input to \(30\) output features, and feed it a synthetic batch of \(128\) samples.
The leading dimension (128) passes straight through unaltered, while the trailing feature axis shifts from 20 to 30. Under the hood, this expansion is neither padding nor interpolation. Instead it is is an affine transformation computed via matrix multiplication:
Under the Hood: Inside forward() of a fully-realized model, PyTorch does not loop over samples in Python. It dispatches the entire batch to a single C++/GPU BLAS matrix multiplication via torch.nn.functional.linear.
To make that equation concrete, let’s focus on the first sample in sample_tensor — a \(1\text{D}\) vector of \(20\) numbers, \([x_1, x_2, \dots, x_{20}]\). Inside sample_layer, PyTorch stores a weight matrix of shape (30, 20) alongside a bias vector of shape (30,). Each row of weight acts as an independent weighted-sum recipe:
Computing one output feature: To produce the first output value (\(y_1\)), the layer takes Row 0 of weight (\([w_{1,1}, w_{1,2}, \dots, w_{1,20}]\)), multiplies each input feature by its paired weight, sums all \(20\) products, and adds \(b_1\):
Twenty input numbers have now collapsed into a single scalar score.
Expanding to \(30\) output features: To generate the full \(30\)-element vector for that sample, the layer evaluates \(30\) distinct weight rows in parallel:
Because every row holds a different set of \(20\) weights, each output coordinate captures a different linear combination of the original inputs. Stacking \(128\) samples into a single input tensor simply evaluates all \(128\) rows against those exact same \(30\) weight columns in one pass, yielding [128, 30].
Respecting the Batch-First Contract (unsqueeze(0))
Now let’s bring back the handwritten 5 and the DigitClassifier we built in Part 1. Before we can pass that single image into the network, we have to resolve a subtle shape mismatch.
A single sample pulled from MNIST arrives as a \(3\text{D}\) tensor with shape [1, 28, 28]—representing [Channels, Height, Width]. However, PyTorch modules enforce a batch-first convention: dimension 0 is always reserved for the batch size (\(N\)), even for a single-sample inference.
Why unsqueeze(0) Matters:nn.Flatten() defaults to start_dim=1, preserving axis 0 as the batch. On a 3-channel RGB image ([3, 28, 28]), omitting unsqueeze(0) would silently treat the Red, Green, and Blue channels as three separate images.
Calling image.unsqueeze(0) inserts a new axis of length 1 at the front of the tensor:
In memory, this is a zero-copy metadata view. None of the \(784\) pixel floats are moved or duplicated. The tensor now conforms to the standard \(4\text{D}\) layout [Batch, Channels, Height, Width], representing a batch of one grayscale image.
End-to-End Transformation: From [1, 1, 28, 28] to [1, 10]
With the batch axis in place, we can pass single directly through DigitClassifier and inspect what comes out the other side.
class DigitClassifier(nn.Module):def__init__(self):super().__init__()self.flatten = nn.Flatten()self.layer1 = nn.Linear(784, 128)self.activation = nn.ReLU()self.layer2 = nn.Linear(128, 10)def forward(self, x): x =self.flatten(x) x =self.layer1(x) x =self.activation(x) x =self.layer2(x)return xmodel = DigitClassifier()single = image.unsqueeze(0) # [1, 28, 28] -> [1, 1, 28, 28]output = model(single)print("Model output shape:", output.shape)print("Raw scores:", output)
Model output shape: torch.Size([1, 10])
Raw scores: tensor([[-0.0193, -0.0748, 0.0064, 0.1658, -0.0154, 0.2206, -0.1676, 0.0800,
0.0165, 0.0459]], grad_fn=<AddmmBackward0>)
Tracing the tensor shape across every line of forward() makes the pipeline transparent:
Stage
Operation
Tensor Shape
What Changed
Input
image.unsqueeze(0)
[1, 1, 28, 28]
Added batch axis of size \(1\)
flatten
nn.Flatten(1, -1)
[1, 784]
Unrolled \(1 \times 28 \times 28\) grid into \(784\) pixel features
layer1
nn.Linear(784, 128)
[1, 128]
Projected \(784\) pixel features into \(128\) hidden features
activation
nn.ReLU()
[1, 128]
Clamped negative values to \(0.0\) (shape unchanged)
layer2
nn.Linear(128, 10)
[1, 10]
Projected \(128\) hidden features into \(10\) class scores
From start to finish, the batch dimension (1) never budges. The final [1, 10] tensor holds one row for our single image and ten raw floating-point scores. Each one is a logit, the model’s raw scoring of its “guess”, for each digit class from 0 through 9. Because our bare-bones model does not have the harness code for neural network training, those ten scores are effectively random noise; their structure is right, even though the weights haven’t learned anything yet.
Closing the Loop: layer1 Through the Same Lens
We opened this post by pointing at self.layer1 = nn.Linear(784, 128), the largest parameter block in DigitClassifier.
With the mechanics of nn.Linear(20, 30) already unpacked, layer1 needs no new math; it is the exact same operation at a different scale:
In our standalone test, \(128\) samples of \(20\) features met \(30\) weight rows to produce [128, 30].
Inside layer1, \(1\) flattened MNIST image of \(784\) pixel features meets \(128\) weight rows—each acting as a \(784\)-weight pattern detector—to compress [1, 784] down into [1, 128].
Later, when we update our basic model and move from a single image to a training mini-batch of \(N\) images, nothing inside layer1 changes. We simply stack \(N\) flattened rows into the input ([N, 784]), multiply against the exact same [784, 128] transposed weights to obtain [N, 128], and let layer2 repeat the identical projection one final time ([N, 128]\(\rightarrow\)[N, 10]).