spflmm 发表于 2023-5-11 12:43:30

has no attribute 问题

import torch
from torch import nn
from torch.nn import ReLU
input = torch.tensor([,
                      [-1.,3.]])
input = torch.reshape(input,(-1,1,2,2))
class Test(nn.Module):
    def __int__(self):
      super(Test,self).__int__()
      self.relu1 = ReLU()

    def forward(self,input):
      output = self.relu1(input)
      return output
test = Test()
output = test(input)
print(output)

运行后为什么会出现AttributeError: 'Test' object has no attribute 'relu1'?应该怎么解决?
请大神解惑,谢谢!

isdkz 发表于 2023-5-11 12:43:57

本帖最后由 isdkz 于 2023-5-11 13:42 编辑

这个问题是因为Test类的__init__()方法被写成了__int__() ,导致在实例化Test类时没有正确初始化relu1属性,所以在调用test(input)时就会出现AttributeError: 'Test' object has no attribute 'relu1'错误。

要解决这个问题,只需要将__int__()改成__init__()即可正确初始化relu1属性。修改后的代码如下:

import torch
from torch import nn
from torch.nn import ReLU

input = torch.tensor([, [-1.,3.]])
input = torch.reshape(input,(-1,1,2,2))

class Test(nn.Module):
    def __init__(self):
      super(Test,self).__init__()
      self.relu1 = ReLU()

    def forward(self,input):
      output = self.relu1(input)
      return output

test = Test()
output = test(input)
print(output)


运行结果为:

tensor([[[,
          ]],


      [[,
          ]]])
页: [1]
查看完整版本: has no attribute 问题