如何有效地填充np数组?

2024-09-26 22:12:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试将数据填充到numpy数组中。然而,对于更高的索引,它需要越来越多的时间。为什么?

我怎样才能防止这种情况? 我已经在最终维度中创建了数组

import random
import numpy as np

# p = [ ... 2200 values in a python list ... ]

iterations = 1000
max_draws = len(p)-1

percentiles = np.zeros(max_draws)
money_list = np.zeros(iterations)

invest = 100
for k in range(1,max_draws):
    print(k)
    for j in range(0,iterations):
        money_list[j] = (invest * np.random.choice(p, k)).sum()

    percentiles[k] = np.percentile(money_list, 5)

我有一个代表股票市场交易收益的因素清单。现在我想知道我必须做多少交易(从可能的交易列表中选择),这样我就有95%的概率赚钱而不赔钱(如果我做了所有的交易,我就赚钱而不赔钱)


Tags: inimportnumpynpzeros交易random数组
1条回答
网友
1楼 · 发布于 2024-09-26 22:12:42

在所有建议的改进之后,可以再做一个非常有效的改进

如果您不介意安装和使用非常繁重的额外python pip包numba(通过python -m pip install numba),那么您可以大大提高速度,如下面的代码所示

Numba设计用于将Python函数预编译为高效的机器代码,也设计用于NumPy。它将python循环转换为快速C代码,并使用LLVM对其进行编译

下一个代码在外循环的2199次迭代中实现了4.18x倍的加速,就像在代码中一样,在5-20次迭代中实现了100x倍的加速。在我的慢速PC上,使用Numba在90秒内完成所有2199次迭代

Try next code here online too!

# Needs: python -m pip install numpy numba
import random, numpy as np, numba, timeit

p = np.random.random((2200,)) # or do p = np.array(p) if p is a list

iterations = 1000
max_draws = len(p) - 1

invest = 100

def do_regular(hi):
    percentiles = np.zeros(max_draws)
    money_list = np.zeros(iterations)

    for k in range(1, hi):
        for j in range(0,iterations):
            money_list[j] = (invest * np.random.choice(p, k)).sum()

        percentiles[k] = np.percentile(money_list, 5)
        
    return percentiles, money_list

do_numba  = numba.jit(nopython = True)(do_regular)
            
do_numba(2) # Pre-compile, heat up
for hi in [8, 16, 32, 64, 128, 256, 512, max_draws]: #max_draws
    tr = timeit.timeit(lambda: do_regular(hi), number = 1)
    tn = timeit.timeit(lambda: do_numba(hi), number = 1)
    print(str(hi).rjust(4), 'regular', round(tr, 3), 'sec')
    print(str(hi).rjust(4), 'numba', round(tn, 3), 'sec, speedup', round(tr / tn, 2), flush = True)

产出:

   8 regular 0.604 sec
   8 numba 0.005 sec, speedup 131.2
  16 regular 1.296 sec
  16 numba 0.013 sec, speedup 101.36
  32 regular 2.672 sec
  32 numba 0.034 sec, speedup 78.18
  64 regular 5.515 sec
  64 numba 0.113 sec, speedup 48.87
 128 regular 11.3 sec
 128 numba 0.374 sec, speedup 30.19
 256 regular 23.758 sec
 256 numba 1.35 sec, speedup 17.59
 512 regular 51.767 sec
 512 numba 5.086 sec, speedup 10.18
2199 regular 376.327 sec
2199 numba 90.104 sec, speedup 4.18

相关问题 更多 >

    热门问题