我编写了一些程序,它numpy
在每次迭代中更新一个列表并对其进行一些操作。迭代次数取决于时间。例如在 1 秒内,可能有 1000 到 2500 次迭代。这意味着 numpy 列表中的项目对于运行程序 1 秒不会超过 2500。
我已经实现了一个基本算法,我不确定它是否是最快的计算方法bonus
:
import numpy as np
cdef int[:, :] pl_list
cdef list pl_length
cdef list bonus
pl_list = np.array([[8, 7]], dtype=np.int32)
def modify(pl_list, pl_length):
cdef int k_const = 10
mean = np.mean(pl_list, axis=0)
mean = np.subtract(mean, pl_length)
dev = np.std(pl_list, axis=0)
mean[0] / dev[0] if dev[0] != 0 else 0
mean[1] / dev[1] if dev[1] != 0 else 0
bonus = -1 + (2 / (1 + np.exp(-k_const * mean)))
return list(bonus)
for i in range(2499): # I just simplified the loop. the main loop works like startTime - time.clock() < seconds
rand = np.random.randint(8, 64)
pl_length = [rand, rand-1]
pl_list = np.append(pl_list, [pl_length], axis=0)
bonus = modify(pl_list, pl_length)
我正在考虑使用这些想法加速这个程序:
- 使用
np.vstack
,np.stack
或者np.concatenate
代替np.append(pl_list, [pl_length])
. (哪一个可能更快?) 像这样使用自制函数计算np.std、np.mean(因为在内存视图中迭代在cython中非常快):
cdef int i,sm = 0
for i in range(pl_list.shape[0]):
sm += pl_list[i]
mean = sm/pl_list.shape[0]
我也在考虑为内存视图定义一个静态长度(比如 2500),所以我不需要使用
np.append
,我可以在那个 numpy 列表上构建一个队列结构。(队列库怎么样?在这种操作中这比 numpy 列表快吗?)
对不起,如果我的问题太多和复杂。我只是想在速度上获得最佳性能。