Pytorch 报错 TypeError: ‘tuple‘ object is not callable

发布时间:2024年01月02日

使用Pytorch编写网络时,有时遇到 TypeError:‘tuple‘ object is not callable 错误。

bug原因:在编写网络时,因为习惯或者不注意在其中一层网络结尾时添加了逗号“,”。

如下所示:

class BlockA(nn.Module):  
    def __init__(self, in_channels, out_channels,downsample=None, stride=1):
        super(BlockA, self).__init__()
        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, stride=stride)
        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)
        self.leakyrelu = nn.LeakyReLU(0.1),
        
    def forward(self, X):
        Y = self.conv1(X)
        Y = self.leakyrelu(Y)
        Y = self.conv2(Y)
        return self.leakyrelu(Y + X)

运行会出现如下报错:

在这里插入图片描述

正确的应该改为:

class BlockA(nn.Module):  
    def __init__(self, in_channels, out_channels,downsample=None, stride=1):
        super(BlockA, self).__init__()
        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, stride=stride)
        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)
        self.leakyrelu = nn.LeakyReLU(0.1)
        
    def forward(self, X):
        Y = self.conv1(X)
        Y = self.leakyrelu(Y)
        Y = self.conv2(Y)
        return self.leakyrelu(Y + X)
文章来源:https://blog.csdn.net/yycocl/article/details/135344583
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。