如何修复 pytorch conv2d 函数的错误?
How to fix error with pytorch conv2d function?
我正在尝试对这两个张量使用 conv2d 函数:
Z = np.random.choice([0,1],size=(100,100))
Z = torch.from_numpy(Z).type(torch.FloatTensor)
print(Z)
tensor([[0., 0., 1., ..., 1., 0., 0.],
[1., 0., 1., ..., 1., 1., 1.],
[0., 0., 0., ..., 0., 1., 1.],
...,
[1., 0., 1., ..., 1., 1., 1.],
[1., 0., 1., ..., 0., 0., 0.],
[0., 1., 1., ..., 1., 0., 0.]
和
filters = torch.tensor(np.array([[1,1,1],
[1,0,1],
[1,1,1]]), dtype=torch.float32)
print(filters)
tensor([[1., 1., 1.],
[1., 0., 1.],
[1., 1., 1.]])
但是当我尝试做 torch.nn.functional.conv2d(Z,filters)
这个错误 returns:
RuntimeError: weight should have at least three dimensions
我真的不明白这里有什么问题。如何解决?
torch.nn.functional.conv2d(input, weight)
的输入应该是
您可以使用 unsqueeze()
添加假批次和通道维度,因此具有大小:输入:(1, 1, 100, 100)
和权重:(1, 1, 3, 3)
.
torch.nn.functional.conv2d(Z.unsqueeze(0).unsqueeze(0), filters.unsqueeze(0).unsqueeze(0))
我正在尝试对这两个张量使用 conv2d 函数:
Z = np.random.choice([0,1],size=(100,100))
Z = torch.from_numpy(Z).type(torch.FloatTensor)
print(Z)
tensor([[0., 0., 1., ..., 1., 0., 0.],
[1., 0., 1., ..., 1., 1., 1.],
[0., 0., 0., ..., 0., 1., 1.],
...,
[1., 0., 1., ..., 1., 1., 1.],
[1., 0., 1., ..., 0., 0., 0.],
[0., 1., 1., ..., 1., 0., 0.]
和
filters = torch.tensor(np.array([[1,1,1],
[1,0,1],
[1,1,1]]), dtype=torch.float32)
print(filters)
tensor([[1., 1., 1.],
[1., 0., 1.],
[1., 1., 1.]])
但是当我尝试做 torch.nn.functional.conv2d(Z,filters)
这个错误 returns:
RuntimeError: weight should have at least three dimensions
我真的不明白这里有什么问题。如何解决?
torch.nn.functional.conv2d(input, weight)
的输入应该是
您可以使用 unsqueeze()
添加假批次和通道维度,因此具有大小:输入:(1, 1, 100, 100)
和权重:(1, 1, 3, 3)
.
torch.nn.functional.conv2d(Z.unsqueeze(0).unsqueeze(0), filters.unsqueeze(0).unsqueeze(0))