Build a Linear Layer and Stable Softmax in NumPy
Machine LearningModel answerLast updated
Write a fully connected layer and a numerically stable row-wise softmax as Python classes in NumPy, paying attention to shapes, broadcasting and overflow.
Task
Using only NumPy, build two small neural-network building blocks as Python classes, each exposing a forward method.
1. Linear (fully connected) layer
Create a class Dense whose constructor receives input_dim and output_dim. It must store two attributes, weights and biases, and its forward(x) method must return
y = x @ weights + biases
2. Softmax layer
Create a class Softmax whose forward(x) accepts a 2D array of logits with shape (batch_size, num_classes) and returns a same-shaped array of probabilities, where every row is a probability distribution.
The implementation must be numerically stable: for each sample, shift the logits by that sample's largest value before exponentiating, so that huge logits cannot cause overflow.
Example
layer = Dense(input_dim=3, output_dim=2)
layer.weights = np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]])
layer.biases = np.array([0.1, 0.1])
x = np.array([[1.0, 2.0, 3.0]])
layer.forward(x) # -> [[2.3, 2.9]]
Constraints
xis a 2D array with shape(batch_size, input_dim).- Build softmax from
np.expandnp.sum. - Make every broadcast explicit and shape-correct.
What to cover in your answer
- The shapes of
weights,biasesand every intermediate array. - Why the max-shift leaves the softmax result unchanged and why it prevents overflow.
- Why the shift must be per row rather than global.
- Edge cases, complexity, and how you would extend the classes with a backward pass.
Hints
Hint 1
Give weights the shape (input_dim, output_dim) and biases the shape (output_dim,). A 1D bias is broadcast across the batch rows automatically.
Hint 2
For softmax, compute the maximum along axis=1 with keepdims=True so that it has shape (N, 1) and lines up against the (N, C) logits instead of the wrong axis.
Hint 3
Subtracting a constant from all logits in a row cancels in the numerator and denominator. Choose the row max so the largest exponent is exp(0) = 1 and the denominator is at least 1.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both layers are short, so the quality of the answer comes from getting shapes, broadcasting and numerical stability exactly right.
Dense layer
weights: shape(input_dim, output_dim)biases: shape(output_dim,)- Input
x: shape(N, input_dim)
(N, in) @ (in, out) -> (N, out)
(N, out) + (out,) -> (N, out) # bias broadcast over rows
Check against the example: column 0 is 1*0.1 + 2*0.3 + 3*0.5 + 0.1 = 2.3, and column 1 is 1*0.2 + 2*0.4 + 3*0.6 + 0.1 = 2.9, giving [[2.3, 2.9]].
For initialization, random weights are preferable to zeros (see the pitfalls below). Xavier/Glorot uniform with limit sqrt(6 / (in + out)) is a sound default, and biases can start at zero.
Softmax layer
For a row x with maximum m:
softmax(x)_i = exp(x_i - m) / sum_j exp(x_j - m)
Why the shift is valid. For any constant c, exp(x_i - c) / sum_j exp(x_j - c) multiplies numerator and denominator by the same factor e^{-c}, which cancels. The output is identical.
Why it is stable.
- The largest shifted value is 0, so the largest exponential is exactly 1 and nothing overflows. Without the shift,
np.exp(1000)isinfandinf/infgivesnan. - At least one denominator term equals 1, so the denominator is at least 1 and can never underflow to 0.
Why per row. A single global max is mathematically fine but can fail in practice: if one row sits far below the global max, all its exponentials underflow to 0 and you get 0/0. Using each row's own max avoids this.
Why keepdims=True. The max and sum then have shape (N, 1), which broadcasts correctly against (N, C). Without it you get shape (N,), which aligns against the last axis, so it either raises an error or, when N == C, silently subtracts along the wrong axis.
Code
import numpy as np
class Dense:
def __init__(self, input_dim, output_dim, seed=None):
rng = np.random.default_rng(seed)
limit = np.sqrt(6.0 / (input_dim + output_dim)) # Xavier uniform
self.weights = rng.uniform(-limit, limit, size=(input_dim, output_dim))
self.biases = np.zeros(output_dim)
self._x = None
def forward(self, x):
x = np.asarray(x, dtype=float)
assert x.ndim == 2 and x.shape[1] == self.weights.shape[0], \
f"expected (batch, {self.weights.shape[0]}), got {x.shape}"
self._x = x # cache for backward
return x @ self.weights + self.biases
class Softmax:
def __init__(self):
self._out = None
def forward(self, x):
x = np.asarray(x, dtype=float)
shifted = x - np.max(x, axis=1, keepdims=True) # (N, C) - (N, 1)
exps = np.exp(shifted)
probs = exps / np.sum(exps, axis=1, keepdims=True)
self._out = probs # cache for backward
return probs
Softmax().forward(np.array([[1000., 1001.]])) returns approximately [[0.2689, 0.7311]] with no overflow.
Complexity
- Dense forward: time O(N * in * out), extra space O(N * out), parameters O(in * out).
- Softmax forward: time and space O(N * C); max, subtract, exp, sum and divide are each one linear pass.
Edge cases
- Huge or very negative logits such as
[1000, 1001]or[-1000, -1001]: handled by the shift. - All-equal logits: give a uniform distribution of
1/Cper entry. - Batch of one: fine, because the input is still 2D
(1, C). - Integer input: cast to float first so that subtraction and
expbehave correctly. - Wrong feature count: validate
x.shape[1] == input_dimfor a clear error message rather than a cryptic matmul failure.
Common mistakes
- Forgetting
keepdims, which causes wrong-axis subtraction or broadcast errors. - Using a global max instead of a per-row max.
- Storing weights as
(output_dim, input_dim)and then forgetting the transpose. - Initializing all weights to zero. Every unit then computes the same output and receives the same gradient, so symmetry is never broken, and gradients sent to earlier layers are also zero.
- Computing
log(softmax(x))naively for a loss. Use log-sum-exp instead to avoidlog(0).
Extending to a backward pass
Given dy = dL/dy with shape (N, out):
def backward(self, dy): # Dense
self.dW = self._x.T @ dy # (in, out)
self.db = dy.sum(axis=0) # (out,) - bias was broadcast, so sum over batch
return dy @ self.weights.T # (N, in)
For softmax output s, the per-sample Jacobian is diag(s) - s s^T, and the vectorized product is:
dx = s * (dy - np.sum(dy * s, axis=1, keepdims=True))
In practice softmax is fused with cross-entropy, where the combined gradient is simply (probs - one_hot) / N. This is cheaper and more stable.
Trade-offs worth mentioning
- Xavier initialization suits tanh/sigmoid-like activations; He initialization (
Var = 2/fan_in) suits ReLU. - Float32 is faster and lighter but has less headroom than float64; the max-shift matters even more there.