【问题标题】:Fastest way to create and fill huge numpy 2D-array?创建和填充巨大的 numpy 二维数组的最快方法?
【发布时间】:2013-04-22 16:22:26
【问题描述】:

我必须创建并填充巨大的(例如 96 Go,72000 行 * 72000 列)数组,在每种情况下都使用来自数学公式的浮点数。数组将在之后计算。

import itertools, operator, time, copy, os, sys
import numpy 
from multiprocessing import Pool


def f2(x):  # more complex mathematical formulas that change according to values in *i* and *x*
    temp=[]
    for i in combine:
        temp.append(0.2*x[1]*i[1]/64.23)
    return temp

def combinations_with_replacement_counts(n, r):  #provide all combinations of r balls in n boxes
   size = n + r - 1
   for indices in itertools.combinations(range(size), n-1):
       starts = [0] + [index+1 for index in indices]
       stops = indices + (size,)
       yield tuple(map(operator.sub, stops, starts))

global combine
combine = list(combinations_with_replacement_counts(3, 60))  #here putted 60 but need 350 instead
print len(combine)
if __name__ == '__main__':
    t1=time.time()
    pool = Pool()              # start worker processes
    results = [pool.apply_async(f2, (x,)) for x in combine]
    roots = [r.get() for r in results]
    print roots [0:3]
    pool.close()
    pool.join()
    print time.time()-t1
  • 创建和填充如此庞大的 numpy 数组的最快方法是什么?填充 列表然后聚合然后转换为numpy数组?
  • 我们可以并行计算知道案例/列/行 二维数组是独立的以加速数组的填充吗?使用多处理优化此类计算的线索/线索?

【问题讨论】:

  • 它需要实时还是可以离线计算并使用例如泡菜读吗?
  • 我更喜欢实时,但如果酸洗更快,我不介意...希望我能很好地理解你的问题?

标签: python matrix numpy multiprocessing multidimensional-array


【解决方案1】:

我知道您可以创建可以从不同线程更改的共享 numpy 数组(假设更改的区域不重叠)。这是您可以用来执行此操作的代码草图(我在stackoverflow的某处看到了原始想法,编辑:这里是https://stackoverflow.com/a/5550156/1269140

import multiprocessing as mp ,numpy as np, ctypes

def shared_zeros(n1, n2):
    # create a 2D numpy array which can be then changed in different threads
    shared_array_base = mp.Array(ctypes.c_double, n1 * n2)
    shared_array = np.ctypeslib.as_array(shared_array_base.get_obj())
    shared_array = shared_array.reshape(n1, n2)
    return shared_array

class singleton:
    arr = None

def dosomething(i):
    # do something with singleton.arr
    singleton.arr[i,:] = i
    return i

def main():
    singleton.arr=shared_zeros(1000,1000)
    pool = mp.Pool(16)
    pool.map(dosomething, range(1000))

if __name__=='__main__':
    main()

【讨论】:

  • 有效吗?我不明白单例类的兴趣/技巧。我有 TypeError: 'NoneType' 对象不支持项目分配。我尝试修改没有结果。你能帮我进一步吗?
  • 我的代码在 linux 上运行(已验证)。如果您有窗户,那么恐怕您的做法会有所不同。 (因为 singleton.arr 值不会被池中的进程继承)。
【解决方案2】:

您可以创建一个具有所需形状的空numpy.memmap 数组,然后使用multiprocessing.Pool 填充其值。正确执行此操作还可以使池中每个进程的内存占用相对较小。

【讨论】:

  • stackoverflow.com/questions/9964809/…,所以我认为这行不通
  • @sega_sai 很有趣。我不会删除我的答案,因为我相信其他人可以(像我一样)通过看到它以及您的评论排除它来学习。谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
  • 1970-01-01
  • 2017-03-22
相关资源
最近更新 更多