将矩阵行的成对差异放入3-d数组中 [英] Put pairwise differences of matrix rows in 3-d array
问题描述
我有一个形状为(n,d)的矩阵Y.我已经通过以下方式计算了成对行差异:
I have a matrix Y of shape (n, d). I already calculated the pairwise row-differences in the following way:
I, J = np.triu_indices(Y.shape[0], 0)
rowDiffs = (Y[I, :] - Y[J, :])
否,我想创建一个3d数组,其中包含位置(i,j,:)上Y行i和j的差.你会怎么做?
No i want to create a 3d-array, containing the differences of the rows i and j of Y at position (i,j, :). How would you do it?
它的目的是取代这个低效的循环:
The aim of it is to replace this inefficient loop:
for i in range(Y.shape[0]):
for j in range(Y.shape[0]):
C[i,:] = C[i,:] + W[i, j] * (Y[i, :]-Y[j, :])
推荐答案
我发现此方法有些成功:
I have found some success with this:
row_diffs = Y[:, np.newaxis] - Y
Y[:, np.newaxis]
创建尺寸为(n,1,3)的Y版本.然后,减法使用广播来执行您想要的操作.
Y[:, np.newaxis]
creates a version of Y with dimensions (n, 1, 3). Then, the subtraction uses broadcasting to do what you want.
不幸的是,我发现这种方法相对较慢,而且还没有找到更好的方法.
Unfortunately, I've found this approach to be relatively slow and I haven't yet found a better way.
完整示例:
>>> x = np.random.randint(10, size=(4, 3))
>>> x
array([[4, 0, 8],
[8, 5, 3],
[4, 1, 6],
[2, 2, 4]])
>>> x[:, np.newaxis] - x
array([[[ 0, 0, 0],
[-4, -5, 5],
[ 0, -1, 2],
[ 2, -2, 4]],
[[ 4, 5, -5],
[ 0, 0, 0],
[ 4, 4, -3],
[ 6, 3, -1]],
[[ 0, 1, -2],
[-4, -4, 3],
[ 0, 0, 0],
[ 2, -1, 2]],
[[-2, 2, -4],
[-6, -3, 1],
[-2, 1, -2],
[ 0, 0, 0]]])
这篇关于将矩阵行的成对差异放入3-d数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!