v9.1.1
Menu

MLP Forward Pass

mediumPRONeural NetworksMachine Learning 2

Implement the forward pass of a two-layer Multi-Layer Perceptron (MLP).

Given input xx, two weight matrices W1W_1, W2W_2 and two bias vectors b1b_1, b2b_2:

  1. Hidden layer: h=ReLU(W1⋅x+b1)h = \text{ReLU}(W_1 \cdot x + b_1)
  2. Output layer: o=W2⋅h+b2o = W_2 \cdot h + b_2

Where ReLU(z)=max⁡(0,z)\text{ReLU}(z) = \max(0, z) applied element-wise.

Return the output vector, rounded to 4 decimal places.

Example

Input
x = [1, 2]
W1 = [[0.5, 0.3], [-0.2, 0.8]]
b1 = [0.1, -0.1]
W2 = [[0.4, -0.5]]
b2 = [0.2]
Output
[0.03]
Reasoning
  • Inputs: x=[1,2]x = [1, 2] is a vector with din=2d_{in} = 2 features. W1W_1 is 2×22 \times 2, so the hidden layer has dhidden=2d_{hidden} = 2 units; W2W_2 is 1×21 \times 2, so there is a single output (dout=1d_{out} = 1).
  • Hidden pre-activations: each hidden unit takes the dot product of its row of W1W_1 with xx, plus its bias. Unit 1: 0.5⋅1+0.3⋅2+0.1=1.20.5 \cdot 1 + 0.3 \cdot 2 + 0.1 = 1.2. Unit 2: −0.2⋅1+0.8⋅2−0.1=1.3-0.2 \cdot 1 + 0.8 \cdot 2 - 0.1 = 1.3.
  • ReLU: both values are positive, so h=[1.2,1.3]h = [1.2, 1.3] passes through unchanged.
  • Output layer: o=0.4⋅1.2+(−0.5)⋅1.3+0.2=0.48−0.65+0.2=0.03o = 0.4 \cdot 1.2 + (-0.5) \cdot 1.3 + 0.2 = 0.48 - 0.65 + 0.2 = 0.03, with no activation applied.
  • Result: one output unit gives a length-1 list, [0.03] after rounding to 4 decimal places.
  • Notice that ReLU only matters when a pre-activation is negative: with x=[2]x = [2] and W1=[[−1],[1]]W_1 = [[-1], [1]], the first hidden unit is −2-2 and gets zeroed, so only the second unit (value 22) reaches the output.

Constraints

  • x: 1D list (input vector, d_in features)
  • W1: 2D list (d_hidden x d_in), b1: 1D list (d_hidden)
  • W2: 2D list (d_out x d_hidden), b2: 1D list (d_out)
  • Return 1D list of output values rounded to 4 decimal places

Learn this in

More from Machine Learning 2

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.