Need help with setting Weight

I am new to Pytorch and need some help. I have a simple ANN:

n_in, n_h0, n_h1, n_h2, n_out, batch_size = 12, 0, 0, 0, 8, 32

class Net(nn.Module):
def init(self):
super(Net, self).init()
self.fc1 = nn.Linear(n_in, n_out)
def forward(self, x):
x = self.fc1(x)
x = nn.Tanh()(x)
return x

model = Net()

I want to change some weights by myself. I try:

model.fc1.weight[0][0] = 0.5

This changes in model.fc1.weight:
requires_grad=True to grad_fn=CopySlices>
Also if i now train the model i get the message: ValueError: can’t optimize a non-leaf Tensor.
Can someone please help how to do it ?

1 Like

Hi,
You should access the weights by calling data. Here is an example:

for x in model.parameters():
    print(x.size(), x.data)

p = list(disc_one.parameters())

p[1].data[0] = 3 #####
p[1]

Actually, here is your code:

n_in, n_h0, n_h1, n_h2, n_out, batch_size = 12, 0, 0, 0, 8, 32

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(n_in, n_out)

    def forward(self, x):
        x = self.fc1(x)
        x = nn.Tanh()(x)
        return x
model = Net()

model.fc1.weight.data[0][0] = 0.5

By the way, you can format your code by putting β€œ```” before and at the end of your code.

best

It works.

Many Thanks

Your Welcome, Good luck.