3D 张量 * Torch 中的 2D 张量点
3D tensor * 2D tensor dot in Torch
在 Theano 中,当我有一个形状为 [A,B,C] 的 3D 张量 x
和一个形状为 [C,D] 的二维张量 y
时,然后 theano.tensor.dot(x, y)
returns 形状为 [A,B,D] 的 3D 张量。
Torch 中的等效操作是什么? torch.dot
似乎没有这样做,x * y
和 torch.mm
抱怨说他们想要两个参数的 2D 张量,而 torch.bmm
想要两个参数的 3D 张量。
您需要将 y 扩展为大小 [A,C,D],然后使用 torch.bmm。查看 torch.expand 或 torch.repeatTensor.
的文档
正如@smhx 所建议的,可能的解决方案是重复第二个张量(有一种方法可以在不分配内存的情况下做到这一点),然后执行批量矩阵矩阵乘积:
function repeatNoCopy(tensor, k)
local tens_size = tensor:size():totable()
return torch.expand(tensor:view(1, unpack(tens_size)), k, unpack(tens_size))
end
A = torch.rand(3, 2, 5)
B = torch.rand(5, 4)
B_rep = repeatNoCopy(B, 3)
result = torch.bmm(A, B_rep)
print(result)
> [torch.DoubleTensor of size 3x2x4]
在 Theano 中,当我有一个形状为 [A,B,C] 的 3D 张量 x
和一个形状为 [C,D] 的二维张量 y
时,然后 theano.tensor.dot(x, y)
returns 形状为 [A,B,D] 的 3D 张量。
Torch 中的等效操作是什么? torch.dot
似乎没有这样做,x * y
和 torch.mm
抱怨说他们想要两个参数的 2D 张量,而 torch.bmm
想要两个参数的 3D 张量。
您需要将 y 扩展为大小 [A,C,D],然后使用 torch.bmm。查看 torch.expand 或 torch.repeatTensor.
的文档正如@smhx 所建议的,可能的解决方案是重复第二个张量(有一种方法可以在不分配内存的情况下做到这一点),然后执行批量矩阵矩阵乘积:
function repeatNoCopy(tensor, k)
local tens_size = tensor:size():totable()
return torch.expand(tensor:view(1, unpack(tens_size)), k, unpack(tens_size))
end
A = torch.rand(3, 2, 5)
B = torch.rand(5, 4)
B_rep = repeatNoCopy(B, 3)
result = torch.bmm(A, B_rep)
print(result)
> [torch.DoubleTensor of size 3x2x4]