|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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'?应该怎么解决?
请大神解惑,谢谢!
本帖最后由 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]]]])
复制代码
|
|