Summary - nn.Module
- Machine Learning course
- Advanced
- Lesson 34/78
- 6 min
In this group you learned nn.Module, __init__, forward, and nn.Linear.
Summary: nn.Module
In this group:
- Every model is an
nn.Module; layers in__init__, computation inforward; called asm(x). super().__init__()is required;nn.ModuleListfor lists of layers (a plain list hides the parameters).nn.Sequentialfor simple chains;torch.nn.functionalfor parameter-free operations.nn.Linear: weight (out, in),y = xWᵀ + b; initialisation withnn.init.parameters(),named_parameters(), freezing andstate_dict.
Practice Your own classifier
Write the class Siniflandirici(girdi, gizli, sinif): two nn.Linear in __init__, a ReLU between them in forward. For Siniflandirici(4, 16, 3), print the output shape for the input torch.zeros(10, 4) and the parameter count on one line.
Starter code
import torch
from torch import nn
# buraya yazSample solution
import torch
from torch import nn
class Siniflandirici(nn.Module):
def __init__(self, girdi, gizli, sinif):
super().__init__()
self.l1 = nn.Linear(girdi, gizli)
self.l2 = nn.Linear(gizli, sinif)
def forward(self, x):
return self.l2(torch.relu(self.l1(x)))
m = Siniflandirici(4, 16, 3)
print(m(torch.zeros(10, 4)).shape, sum(p.numel() for p in m.parameters()))Expected output
torch.Size([10, 3]) 131
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the recommended way to save a model?
- print(model)
- Printing the model.parameters() list
- The whole Python session with pickle
- torch.save(model.state_dict(), path) Correct answer
Explanation: A state_dict contains only tensors; the model class is rebuilt in code and loaded.
2 Load the saved weights into the model.
model.____(torch.load("model.pt"))
model.load_state_dict(torch.load("model.pt"))
Explanation: load_state_dict copies tensors with matching names.
3 Match the tools.
| Term | Meaning |
|---|---|
nn.Module |
Base class |
nn.Sequential |
Classless chain |
nn.ModuleList |
Registered list |
state_dict |
Weight dict |