了解双线性层

时间:2018-08-10 08:35:07

标签: python matrix neural-network linear-algebra pytorch

在PyTorch中有一个双线性层时,我无法为计算的完成而烦恼。

这是一个小例子,我试图弄清楚它是如何工作的:

在:

import torch.nn as nn
B = nn.Bilinear(2, 2, 1)
print(B.weight)

退出:

Parameter containing:
tensor([[[-0.4394, -0.4920],
         [ 0.6137,  0.4174]]], requires_grad=True)

我正在经历一个零向量和一个向量。

在:

print(B(torch.ones(2), torch.zeros(2)))
print(B(torch.zeros(2), torch.ones(2)))

退出:

tensor([0.2175], grad_fn=<ThAddBackward>)
tensor([0.2175], grad_fn=<ThAddBackward>)

我尝试过各种方式加总权重,但结果却不一样。

谢谢!

1 个答案:

答案 0 :(得分:8)

nn.Bilinear完成的操作是B(x1, x2) = x1*A*x2 + b(参见doc),

  • A存储在nn.Bilinear.weight
  • b存储在nn.Bilinear.bias

如果考虑(可选)偏见,则应获得预期的结果。


import torch
import torch.nn as nn

def manual_bilinear(x1, x2, A, b):
    return torch.mm(x1, torch.mm(A, x2)) + b

x_ones = torch.ones(2)
x_zeros = torch.zeros(2)

# ---------------------------
# With Bias:

B = nn.Bilinear(2, 2, 1)
A = B.weight
print(B.bias)
# > tensor([-0.6748], requires_grad=True)
b = B.bias

print(B(x_ones, x_zeros))
# > tensor([-0.6748], grad_fn=<ThAddBackward>)
print(manual_bilinear(x_ones.view(1, 2), x_zeros.view(2, 1), A.squeeze(), b))
# > tensor([[-0.6748]], grad_fn=<ThAddBackward>)

print(B(x_ones, x_ones))
# > tensor([-1.7684], grad_fn=<ThAddBackward>)
print(manual_bilinear(x_ones.view(1, 2), x_ones.view(2, 1), A.squeeze(), b))
# > tensor([[-1.7684]], grad_fn=<ThAddBackward>)

# ---------------------------
# Without Bias:

B = nn.Bilinear(2, 2, 1, bias=False)
A = B.weight
print(B.bias)
# None
b = torch.zeros(1)

print(B(x_ones, x_zeros))
# > tensor([0.], grad_fn=<ThAddBackward>)
print(manual_bilinear(x_ones.view(1, 2), x_zeros.view(2, 1), A.squeeze(), b))
# > tensor([0.], grad_fn=<ThAddBackward>)

print(B(x_ones, x_ones))
# > tensor([-0.7897], grad_fn=<ThAddBackward>)
print(manual_bilinear(x_ones.view(1, 2), x_ones.view(2, 1), A.squeeze(), b))
# > tensor([[-0.7897]], grad_fn=<ThAddBackward>)