鱼C论坛

 找回密码
 立即注册
查看: 1747|回复: 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  属性。修改后的代码如下:
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 __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.0000, 0.0000],
          [0.0000, 3.0000]]],


        [[[0.0000, 0.0000],
          [0.0000, 0.0000]]]])
想知道小甲鱼最近在做啥?请访问 -> 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  属性。修改后的代码如下:
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 __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.0000, 0.0000],
          [0.0000, 3.0000]]],


        [[[0.0000, 0.0000],
          [0.0000, 0.0000]]]])
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-9-23 07:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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