gpt4 book ai didi

python - 将 numpy.bincount 与数组权重一起使用

转载 作者:太空狗 更新时间:2023-10-30 01:17:21 24 4
gpt4 key购买 nike

我想使用 bincount 对数组求和,但它只支持 double 。例如,这有效:

np.bincount([1, 1, 0],weights=np.array([1, 2, 4]))
Out: array([ 4., 3.])

但是我想使用 2 维数组作为:

np.bincount([1, 1, 0],weights=np.array([[1,1], [2,2], [4,4]]))
ValueError: object too deep for desired array

期望的输出是:

Out: array([[ 4.,  4.],[3., 3.]])

评论后更好的解释:

我想将数组的每一行求和到对应的索引中。

有了循环,它会是:

Bin=np.zeros(2,2)
for i in [1,1,0]:
Bin[i]+=a[i]

a 是之前的 3x2 矩阵有没有一种有效的方法来获得这个结果?

最佳答案

根据 numpy 文档:

numpy.bincount(x, weights=None, minlength=None)

weights : array_like, optional; Weights, array of the same shape as x.

所以你不能以这种方式直接使用 bincount 除非你以某种方式改变 x

编辑: 所以我想出了一个稍微棘手的方法来执行此操作,但是当您使用大型数组时无法保证性能。基本上我将利用 scipy 稀疏矩阵如何处理相同索引处的重复条目(它们对它们求和):

 from scipy.sparse import *
a = np.array([[1,1], [2,2], [4,4]])
ii = np.array([1, 1, 0])

ares = a.reshape((-1,),order='F')
# ares == array([1, 2, 4, 1, 2, 4])

col = np.tile(ii,(a.shape[1],))
# col == np.array([1, 1, 0, 1, 1, 0])

row = np.tile([0,1],(a.shape[0],1)).reshape((-1,),order='F')
# row == np.array([0,0,0,1,1,1])

g = coo_matrix((ares,(col,row)),shape=(2,2))
print g.todense()

现在您必须将其概括为您的精确数据。基本思想是您希望将每个数据点映射到结果数组的正确元素,然后让稀疏数组处理对重复条目的求和。

否则,如果您被迫使用循环来解决这个问题,我会考虑使用 Cython。

编辑 2:对于踢球,我用两种不同的方法计时:

import numpy as np
from scipy.sparse import *

def method1():
return np.array([np.bincount(ii, r) for r in a.T]).T

def method2():
ares = a.reshape((-1,),order='F')
col = np.tile(ii,(a.shape[1],))
row = np.tile(np.arange(a.shape[1]),(a.shape[0],1)).reshape((-1,),order='F')

return coo_matrix((ares,(col,row)),shape=(np.unique(ii).size,a.shape[1])).todense()

if __name__ == '__main__':
from timeit import Timer

a = np.random.randint(0,1000,(1000000,3))
ii = np.random.randint(0,10,(a.shape[0],))

N = 100
t1 = Timer("method1()", "from __main__ import method1")
t2 = Timer("method2()", "from __main__ import method2")
print 't2/t1: %f' % (t2.timeit(N)/t1.timeit(N))

在我的机器上,method2method1 慢 3-5 倍,具体取决于输入的形状,因此循环不一定是一个坏选择。

关于python - 将 numpy.bincount 与数组权重一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5205345/

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