在我的工作中,我经常需要聚合和扩展各种数量的矩阵,我正在寻找最有效的方法来完成这些操作.例如,我将有一个NxN
矩阵,我想将它从NxN
聚合到PxP
,其中P < N
.这是使用较大维度和较小维度之间的对应关系来完成的.通常情况下,P
会在NxN
左右.
例如,我会有一个假设的4x4
矩阵(尽管实际上,我的矩阵会大得多,大约是1000x1000
)
m=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
>>> m
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
和一封这样的信件:
0,0
1,1
2,0
3,1
我通常把它存到字典里.这意味着索引0和2都被分配给新的索引0,索引1和3都被分配给新的索引1.矩阵可以是任何东西,但当我想要压缩时,对应关系总是多对一.
此处的聚合过程将导致:
array([[ 24, 28 ],
[ 40, 44 ]])
要做到这一点,我可以制作一个大小合适的空矩阵,然后遍历初始矩阵的所有4x4=16个单元格,然后在嵌套循环中进行累积,但这似乎效率很低,人们总是强调NumPy的矢量化性质.我也用np.ix_
做了索引,用m[row_indices, col_indices].sum()
做了索引,但我想知道做这件事最有效的方式是什么.
相反,用另一种方式使用对应关系来扩展矩阵的明智和有效的方法是什么?例如,在相同的通信中,但反过来,我会这样写:
array([[ 1, 2 ],
[ 3, 4 ]])
至
array([[ 1, 2, 1, 2 ],
[ 3, 4, 3, 4 ],
[ 1, 2, 1, 2 ],
[ 3, 4, 3, 4 ]])
where the values simply get replicated in至 the new cells.
In my attempts so far for the aggregation, I have used approaches with pandas methods with groupby
on index and columns and then extracting the final matrix with, e.g. df.values
. However, I don't know the equivalent way 至 expand a matrix, without using a lot of things like unstack
and join
and so on. And I see people often say that using pandas is not time-efficient.
编辑1:我在一条 comments 中被问到应该如何进行聚合.如果我在原始维度和新维度之间使用嵌套循环和字典查找,则会执行以下操作:
>>> m=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
>>> mnew=np.zeros((2,2))
>>> big2small={0:0, 1:1, 2:0, 3:1}
>>> for i in range(4):
... inew = big2small[i]
... for j in range(4):
... jnew = big2small[j]
... mnew[inew, jnew] += m[i, j]
...
>>> mnew
array([[24., 28.],
[40., 44.]])