How to change weights and bias nn.Module layers?

Hi, so i have this network:


class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Sequential( 
                        nn.Conv2d(1, 20, 5),
                        nn.ReLU())
        self.conv2 = nn.Sequential(
                       nn.Conv2d(20, 20, 5),
                       nn.Sigmoid())

    def forward(self, x):
        x = self.conv1(x)
        return self.conv2(x)

how can i access the weights an bias of each layer and modify them?

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Sequential( 
                        nn.Conv2d(1, 20, 5), # layer1
                        nn.ReLU())
        self.conv2 = nn.Sequential(
                       nn.Conv2d(20, 20, 5), # layer2
                       nn.Sigmoid())

    def forward(self, x):
        x = self.conv1(x)
        return self.conv2(x)

One can get the weights and biases of layer1 and layer2 in the above code using,

model = Model()
weights_layer1 = model.conv1[0].weight.data # gets weights
bias_layer1 = model.conv1[0].bias.data # gets bias
weights_layer2 = model.conv2[0].weight.data
bias_layer2 = model.conv2[0].bias.data

Similarly you can modify the weights/bias using,

model.conv1[0].weight.data = my_weights # make sure the weights are of same shape
1 Like