【问题标题】:Got: TypeError: 'bool' object is not callable when building CNN using PyTorch得到:TypeError:使用 PyTorch 构建 CNN 时,'bool' 对象不可调用
【发布时间】: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

Traceback Page

我发现模型变成了 bool 类型的 var,而不是 cnn 网络。 我的代码有什么问题吗?

【问题讨论】:

    标签: pytorch conv-neural-network


    【解决方案1】:

    "def init(self, alpha_val=0, minus=False, train=True)",将'train'参数定义为另一个词。

    【讨论】:

      【解决方案2】:

      您将self.alpha = alpha() 作为函数调用似乎很奇怪,您可以提供代码吗? (或许这就是问题所在)

      【讨论】:

      • 感谢您的回复。我已经更新了 alpha 类的代码。这是一个用于计算乘法的简单类,似乎没有发生任何错误。有什么问题吗?
      猜你喜欢
      • 2019-09-16
      • 2022-11-30
      • 1970-01-01
      • 2019-09-22
      • 2016-01-08
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      相关资源
      最近更新 更多