如何对数组进行批量计算

时间:2018-06-26 14:36:10

标签: python numpy for-loop

我想为计算任务创建一个for循环,因为数据对于一次计算而言太大,而且我总是得到新的数据,所以我想拆分我的计算过程。

我的数组a的长度为n

我想使用x的第一个元素进行计算(c=b*x),而不要使用数组的下一个x元素。因此总共需要n/x次进行计算。最后,我想将所有c -array串联/附加到一个ctotal数组中。

例如:

a=np.random.rand(70000000)
ctotal=[]
x=7000
for i in range():
    c=model.predict(#each7000 elements of a)
    ctotal=ctotal.append(append with c)
    #calculate something with 20 first elements of a and return new 
    #array c, rand append to ctotal, repeat with new 20 elements  

1 个答案:

答案 0 :(得分:1)

以大块方式处理数组不是“拆分计算过程”,因为它们将按顺序运行。如果要同时运行多个计算,则应签出threading库。即使那不是您要问的重点,听起来也可能会帮助您处理和处理一千万个元素(?)。

如果您的问题只是一次获得20张,那么有多种方法可以做到这一点。 一种是创建一个生成器:

def chunkify(input_list, chunk):
    start = 0
    while input_list[start:start+chunk]:
        yield input_list[start:start+chunk]
        start = start + chunk

然后,您可以运行for i in chunkify(your_list, 20),并且在每个循环中,i将成为列表的下20个元素。