pytroch'Tensor'对象不可调用

问题描述 投票:0回答:1

我正在尝试将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个回答
0
投票

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

def forward(self, x ):
  print(x.shape)
  G_x = F.conv2d(inputs,self.kernela,stride=1,padding=1)
  G_y = F.conv2d(inputs,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))
© www.soinside.com 2019 - 2024. All rights reserved.