'Got: TypeError: 'bool' object is not callable when building CNN using PyTorch
I got the following error when using PyTorch to build a convolutional neural network
TypeError: 'bool' object is not callable.
Attached is the related code:
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)
I guess I called a bool var somewhere but I didn't find one.
Attached is the traceback and debug detail:
Debug page
I find that the model becomes a bool type var, not a cnn network. Is there anything wrong with my code?
Solution 1:[1]
It seems quite odd that You are calling self.alpha = alpha()
as a function, can You provide the code to that? (Or perhaps this is the issue)
Solution 2:[2]
"def init(self, alpha_val=0, minus=False, train=True)", define the 'train' paramater to an other word.
Solution 3:[3]
It seems necessary to change requires_grad to requires_grad_. maybe "_" is missing
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | w_sz |
Solution 2 | Quinn |
Solution 3 | SEONGWUK BAE |