如果我将一个向量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]))
yield 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
发布于 2018-06-06 07:20:24
In [165]: arr = np.asarray([[2,5], [3,4], [8,9]])
In [166]: arr
Out[166]:
array([[2, 5],
[3, 4],
[8, 9]])
In [167]: compute_interaction(arr[0])
Out[167]: array([ 2, 5, 4, 10, 25])
就其价值而言,apply_along_axis
只是:
In [168]: np.array([compute_interaction(row) for row in arr])
Out[168]:
array([[ 2, 5, 4, 10, 25],
[ 3, 4, 9, 12, 16],
[ 8, 9, 64, 72, 81]])
apply...
只是一个方便的工具,可以使多个轴上的迭代更清晰(但不是更快)。
https://stackoverflow.com/questions/50706947
复制相似问题