【发布时间】:2022-01-24 09:59:09
【问题描述】:
使用 PyTorch 构建卷积神经网络时出现以下错误
TypeError: 'bool' 对象不可调用。
附上相关代码:
class alpha(nn.Module):
'''
This is the alpha class
'''
def __init__(self, alpha_val=0, minus=False, train=True):
super(alpha, self).__init__()
if train:
self.alpha = nn.Parameter(torch.Tensor([alpha_val]).to(device))
# This sentence defines that alpha is a parameter that to be optimized
self.alpha.requires_grad = True
else:
self.alpha = torch.Tensor([alpha_val]).to(device)
self.alpha.requires_grad = False
self.minus = minus
def forward(self, x):
out = torch.mul(self.alpha, x)
if self.minus:
out = torch.mul(out, -1)
return out
class InterMedium_Layer(nn.Module):
def __init__(self, train=False, alpha_threshold=0.9) -> object:
super(InterMedium_Layer, self).__init__()
self.alpha1 = alpha()
self.train = train
self.alpha_threshold = alpha_threshold
def forward(self, x):
if (not self.train) and self.alpha1.alpha.item() < self.alpha_threshold:
return x
else:
out = self.alpha1(x)
out += F.relu(out)
out += self.alpha1(x, minus=True)
return out
class BN_Conv2d_f(nn.Module):
def __init__(self, in_channels: object, out_channels: object, kernel_size: object, stride: object, padding: object,
dilation=1, groups=1, bias=False, activation=True) -> object:
super(BN_Conv2d_f, self).__init__()
layers = [nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride,
padding=padding, dilation=dilation, groups=groups, bias=bias),
nn.BatchNorm2d(out_channels)]
self.InterMedium_Layer = InterMedium_Layer()
if activation:
# Error: bool obj not callable
layers.append(self.InterMedium_Layer)
self.seq = nn.Sequential(*layers)
我想我在某个地方调用了一个 bool var,但我没有找到。
附回溯及调试详情:
Debug page
我发现模型变成了 bool 类型的 var,而不是 cnn 网络。 我的代码有什么问题吗?
【问题讨论】:
标签: pytorch conv-neural-network