TorchedUp
LearnBetaProblemsSystem DesignSoonPremium
TorchedUp
LearnBetaProblemsSystem DesignSoonPremium
←

103. PyTorch: 2-Layer MLP

Easy

Build a 2-layer MLP as a proper nn.Module subclass and run a forward pass.

Signature: def mlp_forward(x, w1, b1, w2, b2)

  • x: input (batch, in_features) (nested list)
  • w1: first layer weight (hidden, in_features)
  • b1: first layer bias (hidden,)
  • w2: second layer weight (out_features, hidden)
  • b2: second layer bias (out_features,)
  • Returns: output as nested list (batch, out_features)

The shapes (in_features, hidden, out_features) are inferred from the weight tensors.

What you must do:

  1. Define an nn.Module subclass whose __init__ creates self.fc1 = nn.Linear(in, hidden), self.relu = nn.ReLU(), and self.fc2 = nn.Linear(hidden, out).
  2. Implement forward(x): return self.fc2(self.relu(self.fc1(x))).
  3. Instantiate it, then under torch.no_grad() copy the supplied weights into the layers using .copy_().
  4. Run the input through the model and return the output as a nested list.

The point: real PyTorch code lives in nn.Module subclasses composed in forward — not one-liners over raw tensors.

Math

y=W2​⋅ReLU(W1​x+b1​)+b2​

Asked at

NumPy

import numpy as np

 

def mlp_forward(...):

    pass

🔒

Premium problem

Free accounts include problems #1–20. Upgrade to unlock the editor, hidden test cases, and reference solutions for every problem.

Upgrade to PremiumBack to problems

Already premium?