[pytorch] TypeError cannot assign torch.FloatTensor as parameter weight

TypeError: cannot assign ‘torch.FloatTensor’ as parameter ‘weight’ (torch.nn.Parameter or None expected)

在尝试赋值线性层权重时候出现的错误

错误定位

    def __init__(self, input_dim, atten_dim, attribute, classifier):
        super(MODEL,self).__init__()
        
		nclass, smt_dim = attribute.size()
        self.fc_smt = nn.Linear(smt_dim, nclass, False)
        self.fc_smt.weight = attribute
        for para in self.fc_smt.parameters():
            para.requires_grad = False

错误原因

将tensor赋值给了线性层的权重,应该是parameter才能赋值,或者将tensor赋值给weight.data

解决办法

from torch.nn.parameter import Parameter

        self.fc_smt.weight = Parameter(attribute)

参考Tensor, Parameter& Variable

你可能感兴趣的:(Pytorch,深度学习,bug,debug)