v9.1.1
Menu

Build with nn.Sequential

easyPROModelingPyTorch ModelingPytorch

Problem Statement

Build a neural network using the nn.Sequential container.

Background

nn.Sequential is a convenient container for building simple feed-forward networks. Modules are added in order, and each module's output is automatically passed as input to the next.

Your Task

Write a function build_sequential_net(input_size, hidden_size, output_size) that builds a two-layer network with a ReLU activation between them and returns a dictionary describing it.

Output Format

Return a dictionary with keys: "num_layers" (int), "output_shape" (list — shape for a single sample), "has_relu" (boolean).

Example

Input
input_size=784, hidden_size=128, output_size=10
Output
{'num_layers': 3, 'output_shape': [1, 10], 'has_relu': True}
Reasoning
  • Inputs: input_size =784=784 is the length of one flattened sample, hidden_size =128=128 is the width of the middle representation, and output_size =10=10 is the number of scores produced.
  • Stage 1 (affine): a single sample is a 1×7841 \times 784 row xx. Multiplying by a 784×128784 \times 128 weight matrix and adding a bias gives h=xW1+b1h = xW_1 + b_1, a 1×1281 \times 128 row (784⋅128+128=100,480784 \cdot 128 + 128 = 100{,}480 learnable numbers).
  • Stage 2 (activation): each entry becomes max⁡(0,hj)\max(0, h_j). Negatives turn into 00, the shape stays 1×1281 \times 128, and nothing here is learned, yet it still counts as a stage.
  • Stage 3 (affine): y=max⁡(0,h) W2+b2y = \max(0,h)\,W_2 + b_2 with W2W_2 of size 128×10128 \times 10, so yy is 1×101 \times 10 (1,2901{,}290 learnable numbers).
  • Output: three stages gives 'num_layers': 3; the final row gives 'output_shape': [1, 10] (the leading 11 is the single sample); the rectifier stage is present, so 'has_relu': True.
  • Notice that hidden_size never shows up in the result: (10,20,5)(10, 20, 5) still yields 3 stages and shape [1,5][1, 5]. Only the last dimension tracks output_size.

Constraints

  • Use nn.Sequential
  • Include nn.Linear and nn.ReLU
  • Network: Linear → ReLU → Linear

Learn this in

More from Pytorch

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.