【发布时间】:2012-04-19 00:36:13
【问题描述】:
我想计算一个大(1,000,000 x 3,000) 布尔 numpy 数组。大型布尔数组更改 很少,但权重是在查询时出现的,我需要答案 非常快,无需复制整个大数组,或扩展 小权重数组到大数组的大小。
结果应该是一个包含 1,000,000 个条目的数组,每个条目都有 与该行的 True 对应的权重数组条目的总和 价值观。
我研究过使用掩码数组,但它们似乎需要构建一个 权重数组我的大型布尔数组的大小。
下面的代码给出了正确的结果,但我买不起那个副本 在乘法步骤中。甚至不需要乘法,因为 values 数组是布尔值,但至少它处理广播 正确。
我是 numpy 的新手,我很喜欢它,但我即将放弃它 这个特殊的问题。我已经学会了足够的 numpy 知道要留下来 远离任何在 python 中循环的东西。
我的下一步是用 C 语言编写这个例程(其中添加了 让我通过使用位而不是字节来节省内存的好处,通过 方式。)
除非你们中的一位 numpy 大师可以将我从 cython 中拯救出来?
from numpy import array, multiply, sum
# Construct an example values array, alternating True and False.
# This represents four records of three attributes each:
# array([[False, True, False],
# [ True, False, True],
# [False, True, False],
# [ True, False, True]], dtype=bool)
values = array([(x % 2) for x in range(12)], dtype=bool).reshape((4,3))
# Construct example weights, one for each attribute:
# array([1, 2, 3])
weights = array(range(1, 4))
# Create expensive NEW array with the weights for the True attributes.
# Broadcast the weights array into the values array.
# array([[0, 2, 0],
# [1, 0, 3],
# [0, 2, 0],
# [1, 0, 3]])
weighted = multiply(values, weights)
# Add up the weights:
# array([2, 4, 2, 4])
answers = sum(weighted, axis=1)
print answers
# Rejected masked_array solution is too expensive (and oddly inverts
# the results):
masked = numpy.ma.array([[1,2,3]] * 4, mask=values)
【问题讨论】:
-
用你需要的例子做得很好。