The __init__ method sets up a layer's parts when you create it. It tells the layer what it needs to work.
__init__ for layers in PyTorch
Introduction
Syntax
PyTorch
class MyLayer(torch.nn.Module): def __init__(self, input_size, output_size): super().__init__() self.linear = torch.nn.Linear(input_size, output_size)
The __init__ method runs once when you create the layer.
Always call super().__init__() to set up the base class properly.
Examples
PyTorch
class SimpleLayer(torch.nn.Module): def __init__(self): super().__init__() self.linear = torch.nn.Linear(10, 5)
PyTorch
class DropoutLayer(torch.nn.Module): def __init__(self, drop_prob): super().__init__() self.dropout = torch.nn.Dropout(drop_prob)
Sample Model
This code defines a layer that changes 3 numbers into 2 numbers. It then runs one example input through it and prints the result.
PyTorch
import torch class MyLayer(torch.nn.Module): def __init__(self, input_size, output_size): super().__init__() self.linear = torch.nn.Linear(input_size, output_size) def forward(self, x): return self.linear(x) # Create layer with 3 inputs and 2 outputs layer = MyLayer(3, 2) # Create a sample input tensor input_tensor = torch.tensor([[1.0, 2.0, 3.0]]) # Get output from the layer output = layer(input_tensor) print(output)
Important Notes
Inside __init__, you only set up parts; actual data flows in the forward method.
Use super().__init__() to make sure PyTorch knows this is a special layer.
Keep __init__ simple: just create layers and parameters here.
Summary
__init__ prepares your layer when you make it.
Always call super().__init__() first inside __init__.
Define parts like linear or dropout layers inside __init__.
Practice
1. What is the main purpose of the
__init__ method in a PyTorch layer class?easy
Solution
Step 1: Understand the role of
The__init__in PyTorch__init__method is used to prepare the layer by defining its parts, such as linear or dropout layers.Step 2: Differentiate from other methods
The forward pass runs the data through the layer, training updates weights, and saving stores the model. These are not done in__init__.Final Answer:
To set up the parts of the layer like linear or dropout layers -> Option BQuick Check:
__init__prepares layer parts = D [OK]
Hint: Remember:
__init__ builds the layer parts first [OK]Common Mistakes:
- Confusing
__init__with the forward method - Thinking
__init__trains the model - Assuming
__init__saves the model
2. Which of the following is the correct way to start the
__init__ method in a PyTorch layer class?easy
Solution
Step 1: Check the method signature
The__init__method must haveselfas the first parameter.Step 2: Call the parent class initializer correctly
Usesuper().__init__()to properly initialize the parent class.Final Answer:
def __init__(self): super().__init__() -> Option CQuick Check:
Correct__init__start = B [OK]
Hint: Always include self and call super().__init__() first [OK]
Common Mistakes:
- Omitting self parameter
- Calling super() without __init__()
- Wrong method signature without self
3. What will be the output shape of the linear layer defined below inside
__init__ when input tensor has shape (10, 5)?
class MyLayer(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(5, 3)
def forward(self, x):
return self.linear(x)
layer = MyLayer()
input_tensor = torch.randn(10, 5)
output = layer(input_tensor)
print(output.shape)medium
Solution
Step 1: Understand the linear layer dimensions
The linear layer is defined as Linear(5, 3), so it expects input features of size 5 and outputs size 3.Step 2: Match input tensor shape and output shape
The input tensor has shape (10, 5), meaning 10 samples with 5 features each. The output will have shape (10, 3) after the linear layer.Final Answer:
torch.Size([10, 3]) -> Option AQuick Check:
Input features 5 to output 3, batch 10 = torch.Size([10, 3]) [OK]
Hint: Output shape = (batch size, output features) [OK]
Common Mistakes:
- Confusing input and output feature sizes
- Mixing batch size with feature dimension
- Ignoring the linear layer's output size
4. Identify the error in the following
__init__ method of a PyTorch layer:
class MyLayer(torch.nn.Module):
def __init__(self):
self.linear = torch.nn.Linear(4, 2)
super().__init__()medium
Solution
Step 1: Check order of super().__init__() call
In PyTorch,super().__init__()must be called first inside__init__to properly initialize the parent class.Step 2: Identify the error in the code
The code callssuper().__init__()after definingself.linear, which is incorrect and can cause errors.Final Answer:
super().__init__() must be called before defining layers -> Option DQuick Check:
Call super().__init__() first in __init__ = C [OK]
Hint: Always call super().__init__() before defining layers [OK]
Common Mistakes:
- Defining layers before calling super().__init__()
- Thinking __init__ needs a return statement
- Defining layers outside __init__
5. You want to create a custom PyTorch layer that has two linear layers and a dropout layer. Which
__init__ method correctly sets up these parts?hard
Solution
Step 1: Check the order of super().__init__() call
It must be called first to initialize the parent class properly.Step 2: Verify layer dimensions and definitions
Linear layers should connect properly: first from 10 to 20, second from 20 to 5. Dropout is correctly defined with 0.3 probability.Step 3: Identify the correct option
def __init__(self): super().__init__() self.linear1 = torch.nn.Linear(10, 20) self.linear2 = torch.nn.Linear(20, 5) self.dropout = torch.nn.Dropout(0.3) matches correct order, layer sizes, and dropout setup. Codes that call super().__init__() last or have mismatched dimensions like Linear(20,10) and Linear(5,20) are incorrect.Final Answer:
def __init__(self): super().__init__() self.linear1 = torch.nn.Linear(10, 20) self.linear2 = torch.nn.Linear(20, 5) self.dropout = torch.nn.Dropout(0.3) -> Option AQuick Check:
Correct order and layer sizes = A [OK]
Hint: Call super first, then define layers with matching sizes [OK]
Common Mistakes:
- Calling super().__init__() last
- Using wrong input/output sizes for linear layers
- Misplacing dropout layer definition
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
