如何最快将仅含0、1的np.uint64数组映射为{1,-1}的np.float64数组?
问题描述
我有一个仅包含0和1值的np.uint64类型NumPy数组,需要将0映射为np.float64(1.0),1映射为np.float64(-1.0)。原本考虑到解释器会使用通用转换算法导致耗时,尝试用结果数组结合原数组索引的方式优化,但实际测试后发现这种方法速度更慢。
测试代码
import numpy as np import timeit random_bit = np.random.randint(0, 2, size=(10000), dtype=np.uint64) def np_cast(random_bit): vectorized_result = 1.0 - 2.0 * np.float64(random_bit) return vectorized_result def product(random_bit): mapped_result = 1.0 - 2.0 * random_bit return mapped_result np_one_minus_one = np.array([1.0, -1.0]).astype(np.float64) def _array(random_bit): mapped_result = np_one_minus_one[random_bit] return mapped_result one = np.float64(1) minus_two = np.float64(-2) def astype(random_bit): mapped_result = one + minus_two * random_bit.astype(np.float64) return mapped_result function_list = [np_cast, product, _array, astype] print("start benchmark") for function in function_list: _time = timeit.timeit(lambda: function(random_bit), number=100000) print(f"{function.__name__}: {_time:.3f} seconds")
测试耗时结果
np_cast: 178.604 seconds product: 172.939 seconds _array: 239.305 seconds astype: 186.031 seconds
结论
测试结果显示,product方法(直接通过算术运算1.0 - 2.0 * random_bit完成映射)的耗时最短,是当前最优方案。
内容的提问来源于stack exchange,提问作者tutizeri
相关产品推荐
相关产品推荐

