KatInterview

Build a Linear Layer and Stable Softmax in NumPy

Machine LearningModel answer
MediumModel answerMachine Learningnumpyneural-networkssoftmax

Last 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

  • x is a 2D array with shape (batch_size, input_dim).
  • Build softmax from np.exp and np.sum.
  • Make every broadcast explicit and shape-correct.

What to cover in your answer

  • The shapes of weights, biases and 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.