Layers and forward pass
Layers and the forward pass
A dense layer applies several affine transformations to the same input. Each output unit has its own weight vector and bias. A forward pass evaluates these layers in order, applying the chosen activation where specified. No parameters change during this calculation. A hidden layer is an intermediate representation rather than the original inputs or final outputs. This lesson uses a fully connected feedforward network without loops or skip connections; other architectures can organize computation differently.
Trace a two-input network by hand
Use one weight row per output unit. For an input of shape (2,), the first weight matrix has shape (2,2) and the first bias has shape (2,). For x = [2,3], rows [1,−1] and [1,1], biases [2,−1], the pre-activation vector is [1,4]. Apply ReLU elementwise to obtain hidden activations [1,4]. The output layer uses row [2,−1] and bias 1, giving 2×1 − 4 + 1 = −1. The output is a one-element vector. For input [0,3], the hidden pre-activations are [−1,2], hidden activations [0,2], and output [−1]. The second case demonstrates clipping a negative intermediate value. In this example a final identity activation leaves the raw output unchanged. Print the three vectors for both inputs to inspect each stage. The code expects small finite numbers and nonempty rectangular matrices.
def dense(inputs, weights, biases): if not inputs or not weights or len(weights) != len(biases): raise ValueError("Invalid layer dimensions") if any(len(row) != len(inputs) for row in weights): raise ValueError("Each weight row needs one value per input") return [sum(w * x for w, x in zip(row, inputs)) + b for row, b in zip(weights, biases)]
def forward(inputs): z = dense(inputs, [[1, -1], [1, 1]], [2, -1]) hidden = [max(0, v) for v in z] output = dense(hidden, [[2, -1]], [1]) return z, hidden, output
print(forward([2, 3]))print(forward([0, 3]))Shape contract and batches
For n input features and m output units, weights have shape (m,n), bias (m,), and the output for a single input has shape (m,). In column-vector notation z = Wx + b. In row-vector batch notation, X of shape (B,n) yields Z = XWᵀ + b of shape (B,m); B is the number of examples and each row receives the same bias. A 3-feature input cannot enter our 2-feature network without a deliberate change to representation and parameters. Never silently drop a column or transpose weights only to make an error disappear. Some libraries use different weight storage conventions; the PyTorch Linear documentation uses out_features by in_features, consistent with this lesson. The local example is not a tensor library or a benchmark.
Logits and output interpretation
A raw classification score before sigmoid or softmax is commonly called a logit. The previous output −1 could be a binary logit (sigmoid approximately 0.269), or an unrestricted regression prediction depending on how the model was designed. For mutually exclusive classes, softmax converts a vector of logits into nonnegative values summing to 1 up to rounding. Divide exp(zᵢ) by the sum of exponentials. Subtracting the largest logit from every value leaves the ratios unchanged and prevents positive exponential overflow. Scores [2,1,0] and [1002,1001,1000] yield approximately [0.6652,0.2447,0.0900]. The rounded values sum to 0.9999; the unrounded sum is approximately one. A single-element softmax is always 1, so it is not a substitute for binary sigmoid. Independent multi-label outputs can use separate sigmoids rather than compete for a total of one.
from math import exp
def softmax(logits): if not logits: raise ValueError("Need at least one logit") largest = max(logits) terms = [exp(z - largest) for z in logits] total = sum(terms) return [v / total for v in terms]
for scores in [[2, 1, 0], [1002, 1001, 1000]]: print([round(p, 4) for p in softmax(scores)])Debugging and practice
Check shapes, feature order, finite inputs and the intended output contract before interpreting predictions. For logits, argmax selects a highest-scoring class; ties require an explicit policy. Softmax preserves ordering but does not establish real-world calibration or reliability. Do not apply it twice to the same scores. In training, use the loss function’s documented input contract: many library classification losses accept logits directly. Count parameters in the toy network: 4 + 2 in the hidden layer and 2 + 1 in the output layer, for 9 total. Try x = [3,1]: pre-activation [4,3], hidden [4,3], output [6]. Now try a three-element input and explain the shape error. In Chapter 23, connect the forward result to loss and parameter updates.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Layers and forward pass quiz
Check neural network calculations and reasoning.
How many scalar weights, excluding biases, does a fully connected layer with 3 inputs and 2 outputs contain?
For the worked network, what is the hidden vector for [0,3]?
What is the purpose of the forward pass in the chapter’s fixed-parameter example?
In exact arithmetic, what happens to softmax probabilities when 100 is added to every finite logit?
What does the 2→2→1 dense network contain, including biases?