Torch.nn code Doubt

Define model

model = nn.Linear(3, 2)
print(model.weight)
print(model.bias)

When we run the above code, the output is weight and bias. But how does the code know what is ‘model.weight’ and ‘model.bias’ ? We have not specified anything about weight and bias.

Your model variable is an instance of nn.Linear class, which is implemented by in PyTorch.
This class contains these fields defined inside it’s constructor. Which means you can use them freely (more or less at least, unless you want to break something).

https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html#Linear

3 Likes