logo

How to Obtain the Weight Values of a Model in PyTorch 📂Machine Learning

How to Obtain the Weight Values of a Model in PyTorch

Explanation

Let’s define a model as follows.

import torch
import torch.nn as nn

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.linear = nn.Linear(3, 3, bias=True)
        self.conv = nn.Conv2d(3, 5, 2)

f = Model()

Then, you can access the weights and biases of each layer with the .weight and .bias methods, respectively. Note that the values obtained through .weight (.bias) are not tensors but Parameter objects. So, if you want to get the tensor holding the weight values, you should use .weight.data (.bias.data) as shown.