【问题标题】:Pytorch 'Tensor' object is not callablePytorch“张量”对象不可调用
【发布时间】:2020-07-17 13:23:30
【问题描述】:

我正在尝试将 sobel 过滤器应用于我的网络。我收到此错误:“'Tensor' 对象不可调用” 这是我的代码:

class SobelFilter(nn.Module):
    def __init__(self):
        super(SobelFilter, self).__init__()

        kernel1=torch.Tensor([[1, 0, -1],[2,0,-2],[1,0,-1]])
        kernela=kernel1.expand((1,1,3,3))

        kernel2=torch.Tensor([[1, 2, 1],[0,0,0],[-1,-2,-1]])
        kernelb=kernel2.expand((1,1,3,3))

        inputs = torch.randn(1,1,64,128)

        self.conv1 = F.conv2d(inputs,kernela,stride=1,padding=1)
        self.conv2 = F.conv2d(inputs,kernelb,stride=1,padding=1)

    def forward(self, x ):

        print(x.shape)
        G_x = self.conv1(x)    %GIVES ERROR AT THIS LINE
        G_y = self.conv2(x)
        out = torch.sqrt(torch.pow(G_x,2)+ torch.pow(G_y,2))

        return out
class EXP(nn.Module):
    def __init__(self, maxdisp):
        super(EXP, self).__init__()
        self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
        self.SobelFilter = SobelFilter()

    def forward(self, im):
        % just think "im" to be [1,32,64,128]

        for i in range(im.shape[1]):
            out1= im[:,i,:,:].unsqueeze(1)
            im[:,i,:,:] = self.SobelFilter(out1)

什么会导致问题? 谢谢!

【问题讨论】:

    标签: python-3.x pytorch gradient sobel


    【解决方案1】:

    我认为您的问题是您使用的是torch.nn.functional 而不仅仅是torch。 功能 API 的目的是直接执行操作(在本例中为 conv2d),无需创建类实例然后调用其 forward 方法。 因此,声明self.conv1 = F.conv2d(inputs,kernela,stride=1,padding=1) 已经在进行inputkernela 之间的卷积,而self.conv1 中的内容就是这种卷积的结果。 这里有两种方法可以解决这个问题。在__init__ 中使用torch.Conv2d,其中inputs 是输入的通道,而不是与实际输入具有相同形状的张量。 第二种方法是坚持使用函数式 API,但将其移至 forward() 方法。你想要达到的目标可以通过将 forward 改为:

    def forward(self, x ):
      print(x.shape)
      G_x = F.conv2d(x,self.kernela,stride=1,padding=1)
      G_y = F.conv2d(x,self.kernelb,stride=1,padding=1)
      out = torch.sqrt(torch.pow(G_x,2)+ torch.pow(G_y,2))
      return out
    

    请注意,我创建了 kernelakernelb 类属性。因此,您还应该将__init__() 更改为

    def __init__(self):
      super(SobelFilter, self).__init__()
    
      kernel1=torch.Tensor([[1, 0, -1],[2,0,-2],[1,0,-1]])
      self.kernela=kernel1.expand((1,1,3,3))
    
      kernel2=torch.Tensor([[1, 2, 1],[0,0,0],[-1,-2,-1]])
      self.kernelb=kernel2.expand((1,1,3,3))
    

    【讨论】:

    • 谢谢!有效。我还添加了“self.inputs”而不仅仅是“inputs”
    • 代码有效,但是输出不是我想要的。输出看起来像混合随机变量。我想应用 sobel 过滤器来获得边缘...... :(
    • 我更新了转发,请确保在 F.conv2d() 调用中添加变量 x。让我知道它现在是否有效:)
    • 现在它显示“RuntimeError:输入类型 (torch.cuda.FloatTensor) 和权重类型 (torch.FloatTensor) 应该相同”
    • 错误本身似乎很容易解释。其中一个张量已通过 .cuda() 调用移至 GPU,而另一个则保留在 CPU 中。确保两者都在 CPU 或 GPU 中
    猜你喜欢
    • 2019-05-18
    • 2017-06-14
    • 2017-06-19
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    相关资源
    最近更新 更多