PIXELBANKv9.1.0
Menu

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:
  • First, we calculate the hidden layer hh using the given input xx, weight matrix W1W_1, and bias vector b1b_1: h=ReLU(W1⋅x+b1)=ReLU([0.50.3−0.20.8]⋅[12]+[0.1−0.1])h = \text{ReLU}(W_1 \cdot x + b_1) = \text{ReLU}(\begin{bmatrix} 0.5 & 0.3 \\ -0.2 & 0.8 \end{bmatrix} \cdot \begin{bmatrix} 1 \\ 2 \end{bmatrix} + \begin{bmatrix} 0.1 \\ -0.1 \end{bmatrix})
  • We perform the matrix multiplication and addition: h=ReLU([0.5∗1+0.3∗2−0.2∗1+0.8∗2]+[0.1−0.1])=ReLU([0.5+0.6+0.1−0.2+1.6−0.1])=ReLU([1.21.3])h = \text{ReLU}(\begin{bmatrix} 0.5*1 + 0.3*2 \\ -0.2*1 + 0.8*2 \end{bmatrix} + \begin{bmatrix} 0.1 \\ -0.1 \end{bmatrix}) = \text{ReLU}(\begin{bmatrix} 0.5 + 0.6 + 0.1 \\ -0.2 + 1.6 - 0.1 \end{bmatrix}) = \text{ReLU}(\begin{bmatrix} 1.2 \\ 1.3 \end{bmatrix})
  • Applying the ReLU function: h=[max⁡(0,1.2)max⁡(0,1.3)]=[1.21.3]h = \begin{bmatrix} \max(0, 1.2) \\ \max(0, 1.3) \end{bmatrix} = \begin{bmatrix} 1.2 \\ 1.3 \end{bmatrix}
  • Then, we calculate the output oo using the hidden layer hh, weight matrix W2W_2, and bias vector b2b_2: $o = W_2 \cdot h + b_2 = \begin{bmatrix} 0.4 & -0.5 \end{bmatrix} \cdot \begin{bmatrix} 1.2 \ 1.3 \end{bmatrix} + \begin{bmatrix} 0.2 \end{bmatrix} = \begin{bmatrix} 0.41.2 - 0.51.3 + 0.2 \end{bmatrix} = \begin{bmatrix}

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
🔒

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

0/0
Run code to see test results.
MLP Forward Pass - Medium | PixelBank