torch.nn.conv2d 不会给出与 torch.nn.functional.conv2d 相同的结果

torch.nn.conv2d does not give the same result as torch.nn.functional.conv2d

这是我的代码:

l1 = nn.Conv2d(3, 2, kernel_size=3, stride=2).double() #Layer
l1wt = l1.weight.data #filter
inputs = np.random.rand(3, 3, 5, 5) #input
it = torch.from_numpy(inputs) #input tensor
output1 = l1(it) #output
output2 = torch.nn.functional.conv2d(it, l1wt, stride=2) #output
print(output1)
print(output2)

我希望 output1 和 output2 得到相同的结果,但事实并非如此。 我做错了什么吗 nn 和 nn.functional 工作不同?

我想你忘记了偏见。

inp = torch.rand(3,3,5,5)
a = nn.Conv2d(3,2,3,stride=2)
a(inp)
nn.functional.conv2d(inp, a.weight.data, bias=a.bias.data)

我觉得一样

正如@Coolness 所提到的,在功能版本中默认情况下偏差是关闭的。

文档参考: https://pytorch.org/docs/stable/nn.html#conv2d https://pytorch.org/docs/stable/nn.functional.html#conv2d

import torch
from torch import nn
import numpy as np
# Bias Off
l1 = nn.Conv2d(3, 2, kernel_size=3, stride=1, bias=False).double() #Layer
l1wt = l1.weight.data #filter
inputs = np.random.rand(3, 3, 5, 5) #input
it = torch.from_numpy(inputs) #input tensor
it1 = it.clone()
output1 = l1(it) #output
output2 = torch.nn.functional.conv2d(it, l1wt, stride=1) #output
print(torch.equal(it, it1))
print(output1)
print(output2)