鱼C论坛

 找回密码
 立即注册
查看: 2321|回复: 1

[已解决]has no attribute 问题

[复制链接]
发表于 2023-5-11 12:43:30 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
import torch
from torch import nn
from torch.nn import ReLU
input = torch.tensor([[1.,-0.5],
                      [-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'?应该怎么解决?
请大神解惑,谢谢!
最佳答案
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  属性。修改后的代码如下:

  1. import torch
  2. from torch import nn
  3. from torch.nn import ReLU

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

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

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

  13. test = Test()
  14. output = test(input)
  15. print(output)
复制代码


运行结果为:

  1. tensor([[[[1.0000, 0.0000],
  2.           [0.0000, 3.0000]]],


  3.         [[[0.0000, 0.0000],
  4.           [0.0000, 0.0000]]]])
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 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  属性。修改后的代码如下:

  1. import torch
  2. from torch import nn
  3. from torch.nn import ReLU

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

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

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

  13. test = Test()
  14. output = test(input)
  15. print(output)
复制代码


运行结果为:

  1. tensor([[[[1.0000, 0.0000],
  2.           [0.0000, 3.0000]]],


  3.         [[[0.0000, 0.0000],
  4.           [0.0000, 0.0000]]]])
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-24 01:16

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表