Home > database >  invalid syntax when copying weight in pytorch
invalid syntax when copying weight in pytorch

Time:03-22

I tried this:

model2.down1.maxpool_conv.1.double_conv.0.weight.copy_(state_dict['layer1.0.conv1.weight'])

But I got below error message:

model2.down1.maxpool_conv.1.double_conv.0.weight.copy_(state_dict['layer1.0.conv1.weight'])
                             ^
SyntaxError: invalid syntax

But my model output show its has "down1.maxpool_conv.1.double_conv.0.weight"

enter image description here

CodePudding user response:

Python does not allow numbers to be attributes, so if you somehow create an object that has such attributes (it can be done only by low level function calls) you will not have access to them through dot notation (and this is why you get an invalid syntax error, rather than something like Attribute not found error).

You should instead take the param reference that you already have in your loop and do the copy

for name, param in model2.named_parameters():
  if name == 'down1.maxpool_conv.1.double_conv.0.weight':
     param.copy_(state_dict['layer1.0.conv1.weight'])
 
  • Related