Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 2: Neural Network Internals

Week 02 / Lesson 1

Tensors and a neural network forward pass

Track shapes and calculate the output of a small layered network.

Section 1.1 1 of 7

Overview

Focus

Track shapes and calculate the output of a small layered network.

Your route through the lesson

  • 1.2 Scalars, vectors, matrices, and batches
  • 1.3 Matrix multiplication, broadcasting, and affine layers
  • 1.4 Nonlinear activations and network architecture
  • 1.5 Put it into practice
  • 1.6 Guided comparison
  • 1.7 A variable-size sensor batch

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 1.2 2 of 7

Scalars, vectors, matrices, and batches

Focus

Read tensor dimensions and identify examples, features, and outputs.

A tensor is an array of numbers with a shape. A scalar has no axes, a vector has one, and a matrix has two. For a batch of examples, conventionally place examples along the first axis. Two sensors with three measurements each form a 2 by 3 matrix. Its six values are not six separate examples.

Python represents a shape as a tuple, such as (2,3). Index X[0] selects the first row; indexing starts at zero. PyTorch is a numerical and differentiation library. torch.tensor([[1.,2.,3.],[4.,5.,6.]]) constructs a floating-point tensor and .shape reports its dimensions. Floating-point values are needed when differentiating learned numerical parameters.

A batch lets the same mapping process several examples together. Adding five more sensor records changes batch size from two to seven, but each record still has three measurements. Changing the number of features is a different architectural change. Write down both axis meanings before performing arithmetic: a plausible-looking result can still combine the wrong quantities.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A tensor contains seven sensor records, each with three measurements. What is its shape?
2. What does X[0] select from a Python tensor organized as examples by features?
3. A matrix stores examples on its first axis and features on its second. Its shape changes from (2,3) to (7,3). What changed?

Section 1.3 3 of 7

Matrix multiplication, broadcasting, and affine layers

Focus

Calculate an affine layer and distinguish matrix multiplication from elementwise operations.

An affine layer multiplies inputs by a learned weight matrix and adds a learned bias. With X shaped (B,d), W shaped (d,h), and bias b shaped (h,), the output X@W+b has shape (B,h). Python's @ operator performs matrix multiplication; * multiplies corresponding entries element by element. The inner dimensions d must match for matrix multiplication.

Take one input row [1,2], weights [[1,0],[0,2]], and bias [0.5,−1]. The first output is 1×1+2×0+0.5=1.5. The second is 1×0+2×2−1=3. The same W and b apply to every input row. Broadcasting repeats the bias across rows for arithmetic; it does not create different learned biases for each example.

This layer has four weights and two biases, six learned values. Increasing the batch size changes the number of output rows, not those six parameters. If an operation silently broadcasts an unwanted axis, it can produce a wrong result without a shape error, so check expected shapes explicitly.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. X has shape (4,3) and W has shape (3,2). What shape is X@W?
2. Input [1,2] multiplies weights [[1,0],[0,2]] and adds bias [0.5,−1]. What is the result?
3. A dense layer has a 3 by 2 weight matrix and two biases. What happens to its parameter count when batch size doubles?

Section 1.4 4 of 7

Nonlinear activations and network architecture

Focus

Explain why nonlinear activations allow layered networks to represent more than one affine mapping.

A neural network composes layers. If every layer is affine, their composition is still affine: (XW1+b1)W2+b2 = X(W1W2)+(b1W2+b2). Adding more such layers does not by itself create a nonlinear decision boundary.

An activation function introduces a nonlinear transformation. The rectified linear unit, often represented by the code name ReLU, returns max(0,z): negative inputs become zero and positive inputs pass through. For preactivations [−2,3], it produces [0,3]. A subsequent layer receives these activated values, so its response changes when an earlier value crosses zero.

For a binary classifier, a final scalar can be interpreted through a probability mapping such as the sigmoid, 1/(1+exp(−z)). Here exp is the exponential function. A hidden activation and an output interpretation serve different purposes. PyTorch's Linear and ReLU modules package these operations; Sequential applies modules in order. A useful architecture must match the requested output shape and loss rather than merely contain many layers.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. What does a rectified linear activation return for [−2,3]?
2. Two affine layers are composed without a nonlinear activation. What mapping can represent the result?
3. A binary classifier has one final scalar per example. What does a sigmoid supply?

Section 1.5 5 of 7

Put it into practice

Focus

Run a forward pass and compare it with a hand calculation.

Use the exercise environment from Week 1. Install the processor build of PyTorch with python -m pip install torch --index-url https://download.pytorch.org/whl/cpu using that environment's interpreter. A processor build avoids requiring an accelerator for these small examples.

Download week02.py and run python week02.py --lesson 1. The script constructs explicit tensors, multiplies them, adds a shared bias, and applies a nonlinear activation. Before running, calculate the output for input [1,2] and the identity-style diagonal weights from this section. Then compare both output values, not only the printed shape.

In PyTorch, torch.allclose compares numerical tensors within a tolerance; assert tuple(output.shape)==(2,2) checks dimensions. These checks complement each other: a transposed or wrongly broadcast result may have plausible values somewhere yet the wrong organization. The script also repeats the mapping on seven rows with the original weights. Watch which dimensions change and which stored tensors remain identical.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A learner wants a numerical comparison of a computed tensor with hand-calculated expected values. What is suitable?
2. A shared affine mapping accepts two rows, then seven rows. Which tensor should keep its original shape?
3. A forward-pass script matches output shape but produces incorrect numbers. Is the computation checked?

Section 1.6 6 of 7

Guided comparison

Focus

Trace multiplication, bias broadcasting, and activation in the correct order.

Consider X=[[1,2],[3,4]], W=[[1,0],[0,2]], and b=[0.5,−1]. Matrix multiplication yields [[1,4],[3,8]]. Adding the shared bias gives [[1.5,3],[3.5,7]]. The rectified linear activation leaves these positive values unchanged. A different input row [−2,0] gives preactivation [−1.5,−1] and activated output [0,0].

The order matters: activation follows the affine computation. Clipping an input before multiplying is a different function. In this example W contains four numbers and b two; processing another row reuses all six. A layer can therefore learn from many examples without storing one parameter per row.

If the lab fails, first compare shapes, then inspect the intermediate product, then bias addition, and finally activation. This order locates the earliest divergence. Randomly changing model settings until the final assertion passes would hide the mechanism that caused the mismatch.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. For X=[[1,2],[3,4]] and W=[[1,0],[0,2]], what is the second row before adding bias?
2. An affine output is [−1.5,−1]. What happens under a rectified linear activation?
3. A wrong final output appears after an affine layer and activation. What is a useful debugging order?

Section 1.7 7 of 7

A variable-size sensor batch

Focus

Use one learned mapping on a different number of sensor records.

A service first receives two sensors, each with temperature, pressure, and vibration: shape (2,3). Its first layer has weights shaped (3,4) and bias shaped (4,), giving four hidden values per sensor. A later batch of seven sensors has shape (7,3) and produces hidden values shaped (7,4). The learned parameter count remains 3×4+4=16.

Now imagine a sensor omits pressure. A two-feature row does not automatically fit the three-feature mapping. It needs the same documented preprocessing policy used in training, such as filling missing pressure with a saved training value. Padding an arbitrary number or silently swapping feature order changes meaning even if dimensions become acceptable.

Batch flexibility therefore relies on a stable feature contract. Names, order, units, and missing-value handling must agree across training and inference. Shape checks detect missing dimensions, while a named input schema and known fixture detect swapped temperature and pressure columns.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A layer maps (7,3) sensor inputs with weights (3,4). What is its output shape?
2. Weights are (3,4) and bias is (4,). How many learned numbers are present?
3. A deployment swaps temperature and pressure columns but preserves shape. What catches this failure?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Backpropagation and checking gradients →