【问题标题】:Python 3 - Serialize generated numpy arraysPython 3 - 序列化生成的 numpy 数组
【发布时间】:2020-06-25 15:39:21
【问题描述】:

我有一个程序可以生成一百万个大小为 784 的 numpy 数组,我想在生成它们时将它们保存在一个文件中(因此任何时候只有一个数组保存在内存中)。我尝试了下面的代码,当n_arrays 大约为 10^5 时(内存使用量增加了大约 400MB,但随后又回落并继续这样做直到完成),我尝试了下面的代码。 但是,当 10^6 时,内存使用量会上升,直到达到限制并引发 MemoryError。 有没有办法做到这一点?

import numpy as np


def generator(n):
    num = 0
    while num < n:
        yield np.array(range(784))
        num += 1


class StreamArray(list):
    def __init__(self, n=0):
        super().__init__()
        self.n = n
        self.len = 1

    def __iter__(self):
        return generator(self.n)

    def __len__(self):
        return self.len


n_arrays = 10**6
np.save('out', StreamArray(n_arrays))

【问题讨论】:

    标签: python python-3.x numpy serialization generator


    【解决方案1】:
    def generator(n):
        num = 0
        while num < n:
            yield np.array(range(784))
            num += 1
    
    
    n_arrays = 10**6
    with open('out.npy', 'wb') as f:
        for item in generator(n_arrays):
            np.save(f, item)
    

    【讨论】:

    • 将每个数组的字节保存在一个文件中,但加载它只显示第一个(即len(np.load('out.npy')) 应该打印 10^6 但打印 784)
    • with open('out.py', 'rb') as f: np.load(f,) 第一个,np.load(f) 第二个等等... Don' t 关闭文件。
    • 然后呢?我在哪里使用np.load()
    • with open('out.npy', 'rb') as f: print(len(np.load(f))) 仍然给出 784。
    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2018-06-26
    相关资源
    最近更新 更多