将矩阵扩展到张量

时间:2019-10-17 15:34:04

标签: numpy tensor

我有一个(m, n)矩阵,其中每一行都是具有n功能的示例。我想将其扩展为(m, n, n)矩阵,即为每个示例创建其功能的外部产品。我已经研究过tensordot,但还没有找到解决问题的方法-它似乎仅使张量收缩,而不扩展。

a = np.arange(5*3).reshape(5, 3, 1)
b = np.arange(5*3).reshape(1, 3, 5)
c = np.tensordot(a, b, axes=([1,2],[1,0]))  # gives a (5,5) matrix
c = np.tensordot(a, b, axes=([1,2],[0,1]))  # throws a shape-mismatch error

我将举一个简单的例子。假设您有col向量a = [1, 2, 3],我想获取的是a * a.T,即:

1, 2, 3
2, 4, 6
3, 6, 9

1 个答案:

答案 0 :(得分:2)

In [220]: a = np.arange(15).reshape(5,3)                                        
In [221]: a                                                                     
Out[221]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14]])

使用标准numpy广播:

In [222]: a[:,:,None]*a[:,None,:]                                               
Out[222]: 
array([[[  0,   0,   0],
        [  0,   1,   2],
        [  0,   2,   4]],

       [[  9,  12,  15],
        [ 12,  16,  20],
        [ 15,  20,  25]],

       [[ 36,  42,  48],
        [ 42,  49,  56],
        [ 48,  56,  64]],

       [[ 81,  90,  99],
        [ 90, 100, 110],
        [ 99, 110, 121]],

       [[144, 156, 168],
        [156, 169, 182],
        [168, 182, 196]]])
In [223]: _.shape                                                               
Out[223]: (5, 3, 3)
提到了

einsum

In [224]: np.einsum('ij,ik->ijk',a,a).shape                                     
Out[224]: (5, 3, 3)

广播的制作者:

(5,3) => (5,3,1) and (5,1,3) => (5,3,3)

None的索引就像您的reshape(5,3,1),添加了维度。在广播中,尺寸1的尺寸与其他阵列的相应尺寸匹配。 reshape很便宜;免费使用。

tensordot的名称不正确; “张量”意味着它可以使用大于2d的值(但是所有numpy都可以这样做)。 “点”是指点积,即收缩。使用einsummatmul/@时,tensordot是不需要的。从来没有创建更高维的数组。