Solving tips
- A dense layer is one matrix multiply plus a bias add: X @ W + b, with shapes (n, d_in) @ (d_in, d_out) -> (n, d_out).
- The bias has shape (d_out,); NumPy broadcasts it across all n rows automatically, so no loop or tiling is needed.
- Check the inner dimensions line up: X's second axis (d_in) must equal W's first axis (d_in), or the matmul fails.
Implement the forward pass of a fully-connected layer, the fundamental building block of every neural network. Given a batch of inputs X of shape (n, d_in), a weight matrix W of shape (d_in, d_out), and a bias vector b of shape (d_out,), compute the affine transform X @ W + b. Interviewers use this to check that you understand the shapes flowing through a layer and that you reach for a single vectorized matmul instead of looping over samples.
Definition
A dense layer maps each input row x of length d_in to an output row of length d_out:
out[i, j] = sum_k X[i, k] * W[k, j] + b[j]
Stacked over the whole batch, this is one matrix product plus a broadcast bias add:
Y = X @ W + b # (n, d_in) @ (d_in, d_out) + (d_out,) -> (n, d_out)
Task
Complete dense_forward(X, W, b) so it returns the (n, d_out) output matrix, fully vectorized with NO Python loops. Take the matrix product X @ W, then add the bias b, which NumPy broadcasts across every row. Do not call any deep-learning framework (no PyTorch, TensorFlow, or Keras); use plain NumPy only.
Example
X = np.array([[1.0, 2.0],
[3.0, 4.0]])
W = np.array([[1.0, 0.0, -1.0],
[0.0, 1.0, 1.0]])
b = np.array([0.5, -0.5, 1.0])
dense_forward(X, W, b)
# -> array([[1.5, 1.5, 2.0],
# [3.5, 3.5, 2.0]])
For row 0, [1, 2] @ W = [1, 2, 1], then adding b = [0.5, -0.5, 1.0] gives [1.5, 1.5, 2.0].
Constraints
1 <= n <= 10^4,1 <= d_in, d_out <= 10^3; use vectorized NumPy, no Python loop over samples.X.shape[1]equalsW.shape[0](bothd_in), andb.shape[0]equalsW.shape[1](d_out).- Values fit in float64; the output is a dense
(n, d_out)float array.