Torch7:具有像 numpy 这样大小不一致的张量的附加层

Torch7: Addition layer with Tensors of inconsistent size like numpy

我想添加两个具有不同维数的张量。

例如:

x = torch.ones(4,5)
y = torch.ones(4,3,5)

在 numpy 中,我可以通过以下方式做到这一点:

import numpy as np
x = np.ones((4,5))
y = np.ones((4,3,5))
y + x[:,None,:]

#Prints out
array([[[ 2.,  2.,  2.,  2.,  2.],
    [ 2.,  2.,  2.,  2.,  2.],
    [ 2.,  2.,  2.,  2.,  2.]],

   [[ 2.,  2.,  2.,  2.,  2.],
    [ 2.,  2.,  2.,  2.,  2.],
    [ 2.,  2.,  2.,  2.,  2.]],

   [[ 2.,  2.,  2.,  2.,  2.],
    [ 2.,  2.,  2.,  2.,  2.],
    [ 2.,  2.,  2.,  2.,  2.]],

   [[ 2.,  2.,  2.,  2.,  2.],
    [ 2.,  2.,  2.,  2.,  2.],
    [ 2.,  2.,  2.,  2.,  2.]]])

It has a shape of (4,3,5)

有没有办法在 nn.CMulTable() 上重现这个?当我像这样查看 x 张量时 x:view(4,1,5) 它给我一个错误 inconsistent tensor size.

m = nn.CAddTable()
m:forward({y, x:view(4,1,5)})

有什么想法吗?

使用expandAs得到一个4x3x5张量:

m:forward({y, x:view(4,1,5):expandAs(y)})