变量交互的计算(矩阵中向量的点积)

4

如果我将一个向量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吗?


在您的实际使用情况中,nk的典型值是多少? - Divakar
假设k的值可能达到千位或百万级别,而n最大为100。 - Drey
2个回答

3

方法一

使用np.triu_indices的一种解决方案是 -

r,c = np.triu_indices(arr.shape[1])
out = np.concatenate((arr,arr[:,r]*arr[:,c]),axis=1)

方法二

更快的方法是使用slicing-

def pairwise_col_mult(a):
    n = a.shape[1]
    N = n*(n+1)//2
    idx = n + np.concatenate(( [0], np.arange(n,0,-1).cumsum() ))
    start, stop = idx[:-1], idx[1:]
    out = np.empty((a.shape[0],n+N),dtype=a.dtype)
    out[:,:n] = a
    for j,i in enumerate(range(n)):
        out[:,start[j]:stop[j]] = a[:,[i]] * a[:,i:]
    return out

时间 -

In [254]: arr = np.random.randint(0,9,(10000,100))

In [255]: %%timeit
     ...: r,c = np.triu_indices(arr.shape[1])
     ...: out = np.concatenate((arr,arr[:,r]*arr[:,c]),axis=1)
1 loop, best of 3: 577 ms per loop

In [256]: %timeit pairwise_col_mult(arr)
1 loop, best of 3: 233 ms per loop

这很简洁,谢谢!还在弄清楚为什么它能工作 :-) - Drey

0
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...只是一个方便的工具,使迭代多个轴更清晰(但不更快)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接