可变相互作用的计算(矩阵中向量的点积)

Dre*_*rey 5 python numpy vector dot-product numpy-einsum

如果我将一个向量x(1,n)与它自身相乘,即np.dot(x.T, x)我将获得二次形式的矩阵.

如果我有一个矩阵Xmat(k,n),我怎样才能有效地计算行方点积并只选择上三角形元素?

所以,atm.我有以下解决方案:

def compute_interaction(x):
    xx = np.reshape(x, (1, x.size))
    return np.concatenate((x, np.dot(xx.T, xx)[np.triu_indices(xx.size)]))
Run Code Online (Sandbox Code Playgroud)

然后compute_interaction(np.asarray([2,5]))屈服array([ 2, 5, 4, 10, 25]).

当我有一个矩阵我用

np.apply_along_axis(compute_interaction, axis=1, arr = np.asarray([[2,5], [3,4], [8,9]]))
Run Code Online (Sandbox Code Playgroud)

产生我想要的东西:

array([[ 2,  5,  4, 10, 25],
       [ 3,  4,  9, 12, 16],
       [ 8,  9, 64, 72, 81]])
Run Code Online (Sandbox Code Playgroud)

有没有其他方法来计算这个使用apply_along_axis?也许用np.einsum