We look at model parameters to understand what the model has learned and to check its size. This helps us know how complex the model is.
Model parameters inspection in PyTorch
for name, param in model.named_parameters(): print(name, param.shape, param.requires_grad)
model.named_parameters() gives you the name and value of each parameter.
param.shape shows the size of the parameter tensor.
for name, param in model.named_parameters(): print(name)
for name, param in model.named_parameters(): print(param.data)
total_params = sum(param.numel() for param in model.parameters()) print(f"Total parameters: {total_params}")
This code creates a small neural network with two layers. It then prints each parameter's name, shape, and if it will update during training. Finally, it counts all parameters.
import torch import torch.nn as nn # Define a simple model class SimpleModel(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(4, 3) self.fc2 = nn.Linear(3, 1) def forward(self, x): x = self.fc1(x) x = torch.relu(x) x = self.fc2(x) return x model = SimpleModel() # Inspect parameters for name, param in model.named_parameters(): print(f"{name}: shape={param.shape}, requires_grad={param.requires_grad}") # Count total parameters total_params = sum(param.numel() for param in model.parameters()) print(f"Total parameters: {total_params}")
Parameters with requires_grad=True will be updated during training.
You can freeze parameters by setting param.requires_grad = False.
Inspecting parameters helps in debugging and understanding model size.
Model parameters include weights and biases that the model learns.
You can list parameters with their names and shapes using named_parameters().
Counting parameters helps estimate model complexity and memory needs.
Practice
named_parameters() method in a PyTorch model return?Solution
Step 1: Understand the purpose of
This method is designed to give access to each parameter's name and its tensor, which includes weights and biases.named_parameters()Step 2: Identify what it returns
It returns an iterator over tuples, where each tuple contains the parameter's name and the tensor itself.Final Answer:
An iterator over tuples of parameter names and their tensors -> Option BQuick Check:
named_parameters() = iterator of (name, tensor) [OK]
- Confusing parameters with layers
- Thinking it returns loss or optimizer info
- Assuming it returns just tensors without names
model?Solution
Step 1: Check correct method usage
The methodnamed_parameters()returns (name, parameter) pairs, so unpacking into two variables is correct.Step 2: Verify printing name and shape
Accessingparam.shapegives the tensor shape. for name, param in model.named_parameters(): print(name, param.shape) correctly prints both.Final Answer:
for name, param in model.named_parameters(): print(name, param.shape) -> Option AQuick Check:
Use named_parameters() with unpacking [OK]
- Trying to access .name on param tensor (no such attribute)
- Using parameters() without names
- Calling non-existent methods like print_parameters()
import torch.nn as nn
class SimpleNet(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(4, 3)
self.fc2 = nn.Linear(3, 2)
model = SimpleNet()
params = list(model.named_parameters())
print(len(params))Solution
Step 1: Count parameters in each layer
Each nn.Linear has weights and biases, so 2 parameters per layer.Step 2: Calculate total parameters
Two layers x 2 parameters each = 4 parameters total.Final Answer:
4 -> Option CQuick Check:
2 layers x 2 params = 4 [OK]
- Counting only layers, not parameters
- Assuming one parameter per layer
- Confusing number of parameters with tensor sizes
for name, param in model.parameters():
print(name, param.shape)
What is the error and how to fix it?Solution
Step 1: Understand what model.parameters() returns
This method returns only parameter tensors, no names.Step 2: Correct method to get names and parameters
Use model.named_parameters() which returns (name, param) pairs.Final Answer:
model.parameters() returns tensors only; use model.named_parameters() to get names -> Option DQuick Check:
parameters() = tensors only, named_parameters() = (name, tensor) [OK]
- Trying to unpack parameters() into name and param
- Using .items() on parameters() which is not a dict
- Swapping variable order in for loop
model. Which code snippet correctly computes this?Solution
Step 1: Understand what counts as trainable parameters
Only parameters withrequires_grad=Trueare trainable.Step 2: Use
Summingnumel()to count elements in each tensorp.numel()for all trainable parameters gives total count.Final Answer:
sum(p.numel() for p in model.parameters() if p.requires_grad) -> Option AQuick Check:
Sum numel() of trainable params = total count [OK]
- Using len() which counts parameters, not elements
- Trying to sum shapes directly (shapes are tuples)
- Assuming model has count_parameters() method
Ready to prove it?
Pass the test and this pattern moves unknown
