model.parameters() returns the learnable parameters owned by a PyTorch module and its registered submodules. A parameter is a tensor recognized by nn.Module and requiring gradients by default, so gradient descent can optimize it. section 6.2.2
The method recursively visits submodules assigned as attributes in the constructor and produces a flat sequence of their parameters. Passing that sequence to an optimizer connects backpropagated gradients with parameter updates. section 6.2.2 section 8.3.2
Passing parameters to SGD
linear_model = nn.Linear(1, 1)\noptimizer = optim.SGD(\n linear_model.parameters(),\n lr=1e-2)\n\nlist(linear_model.parameters())\n# [weight Parameter, bias Parameter] section 6.2.2
Keep these implementation details in mind:
- Calling model.parameters() returns a generator; use list(model.parameters()) when you need to inspect the collected tensors. section 6.2.2
- Register child modules as top-level attributes, or use nn.ModuleList and nn.ModuleDict for module collections; otherwise their parameters are not found. section 8.3.2
# In[11]: linear_model.parameters() # Out[11]: <generator object Module.parameters at 0x7f94b4a8a750> # In[12]: list(linear_model.parameters()) # Out[12]: [Parameter containing: tensor([[0.7398]], requires_grad=True), Parameter containing: tensor([0.7974], requires_grad=True)]
Inspect the generator and the weight and bias Parameters returned by a linear module. section 6.2.2
