【发布时间】:2019-07-22 17:30:14
【问题描述】:
我记得在过去,nn.Linear 只接受 2D 张量。
但今天,我发现nn.Linear 现在接受 3D,甚至是任意维度的张量。
X = torch.randn((20,20,20,20,10))
linear_layer = nn.Linear(10,5)
output = linear_layer(X)
print(output.shape)
>>> torch.Size([20, 20, 20, 20, 5])
当我查看 Pytorch 的文档时,它确实说现在需要
输入::math:
(N, *, H_{in})其中 :math:*表示任意数量的 附加维度和:math:H_{in} = \text{in\_features}
所以在我看来,Pytorch nn.Linear 现在自动通过 x.view(-1, input_dim) 重塑输入。
但我在source code 中找不到任何x.shape 或x.view:
class Linear(Module):
__constants__ = ['bias']
def __init__(self, in_features, out_features, bias=True):
super(Linear, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = Parameter(torch.Tensor(out_features, in_features))
if bias:
self.bias = Parameter(torch.Tensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
if self.bias is not None:
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in)
init.uniform_(self.bias, -bound, bound)
@weak_script_method
def forward(self, input):
return F.linear(input, self.weight, self.bias)
def extra_repr(self):
return 'in_features={}, out_features={}, bias={}'.format(
self.in_features, self.out_features, self.bias is not None
)
谁能证实这一点?
【问题讨论】:
标签: python-3.x pytorch