gpt4 book ai didi

python - 求和矩阵行,不包括其他数组的索引

转载 作者:行者123 更新时间:2023-12-04 02:30:58 33 4
gpt4 key购买 nike

假设我有一些矩阵,W = MxN 和一长串索引 z,形状为 Mx1

现在,假设我想对 W 中每一行的元素求和,不包括 z 中该行出现的索引。

一维示例:

import numpy as np

W = np.array([1.0, 2.0, 8.0])
z = 2
np.sum(np.delete(W,z))

MxN 示例和期望的输出:

import numpy as np

W = np.array([[1.0,2.0,8.0], [5.0,15.0,3.0]])
z = np.array([0,2]).reshape(2,1)

# desired output
# [10. 20.]

我尝试使用 np.deleteaxis=1 但没有成功

我设法使用以下技巧绕过它:

W = np.array([[1.0,2.0,8.0], [5.0,15.0,3.0]])
z = np.array([0,2])
W[np.arange(z.shape[0]), z]=0
print(np.sum(W, axis=1))
# [10. 20.]

但我想知道是否有更优雅的方式。

最佳答案

使用 broadcasting获取掩码以模拟 deletion 然后 sum-reduce -

(W*(z != np.arange(W.shape[-1]))).sum(-1)

样本运行-

对于二维情况:

In [61]: W = np.array([[1.0,2.0,8.0], [5.0,15.0,3.0]])
...: z = np.array([0,2]).reshape(2,1)

In [62]: (W*(z != np.arange(W.shape[-1]))).sum(-1)
Out[62]: array([10., 20.])

同样适用于 1D 情况:

In [59]: W = np.array([1.0, 2.0, 8.0])
...: z = 2

In [60]: (W*(z != np.arange(W.shape[-1]))).sum(-1)
Out[60]: 3.0

对于二维情况:

np.einsum对于 sum-reduction -

In [53]: np.einsum('ij,ij->i',W,z != np.arange(W.shape[1]))
Out[53]: array([10., 20.])

2D 情况下对 z 索引值求和然后相减 -

In [134]: W.sum(1) - np.take_along_axis(W,z,axis=1).squeeze(1)
Out[134]: array([10., 20.])

扩展以处理 2D 和 1D 情况 -

W.sum(-1)-np.take_along_axis(W,np.atleast_1d(z),axis=-1).squeeze(-1)

关于python - 求和矩阵行,不包括其他数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64193237/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com