如果我将一个向量x
(1,n)与其转置相乘,即np.dot(x.T, x)
,我将得到一个二次形式的矩阵。
如果我有一个矩阵Xmat
(k,n),如何有效地计算逐行点积并仅选择上三角元素?
所以,目前我的解决方案如下:
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)]))
然后,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]]))
这会得到我想要的结果:
array([[ 2, 5, 4, 10, 25],
[ 3, 4, 9, 12, 16],
[ 8, 9, 64, 72, 81]])
除了使用apply_along_axis
计算,还有其他方法吗?也许可以使用np.einsum
吗?
n
和k
的典型值是多少? - Divakar