Week 01 · Tensors, shapes, and the forward pass

Trace a batch through two layers and catch a silent broadcast.

Subject contents · Week 2 →

Trace a batch through two layers and catch a silent broadcast.

Work through the problem

A dense layer maps an n×d input X to n×h activations with XW+b, where W is d×h and the bias b has h entries. A pointwise activation changes values without changing shape. With batch size 2, hidden size 3 and one output per row, the prediction has shape (2,1).

If a target has shape (2,), subtracting it from a (2,1) prediction broadcasts into a (2,2) grid. For prediction [2,4] and target [1,3], paired errors are [1,1]. Broadcasting also computes 2−3 and 4−1. Reshape targets or squeeze the final unit dimension deliberately.

Run the Python lab

import torch
x = torch.tensor([[1.,0.],[0.,1.]])
w = torch.tensor([[1.,2.,0.],[0.,2.,2.]])
hidden = torch.relu(x@w)
prediction = hidden @ torch.tensor([[0.],[1.],[1.]])
target = torch.tensor([1.,3.])
wrong = (prediction-target).square().mean()
right = (prediction[:,0]-target).square().mean()
print("Shapes:", tuple(hidden.shape), tuple(prediction.shape))
print("Wrong, correct:", wrong.item(), right.item())
assert right.item()==1 and wrong.item()==3

Output from the lab

Shapes: (2, 3) (2, 1)
Wrong, correct: 3.0 1.0

Practice

  1. What shape should the error tensor have for n scalar outputs?

Check your reasoning

  1. Either (n,) or (n,1), provided each row is compared with its own target exactly once.

Subject contents · Week 2 →

Further reading · Goodfellow, Bengio, and Courville · Deep Learning