【问题标题】:Generate large amounts of data with numpy使用 numpy 生成大量数据
【发布时间】:2021-05-20 03:53:11
【问题描述】:

尝试使用numpy 生成大量数据但没有成功。需要明确的是,这不是库的错——我的电脑内存不足~ 32gb 的内存。

有没有更好的方法来做到这一点,例如同时保存在磁盘上而不是内存中?

这是工作代码:

import numpy as np
import tensorflow as tf


def main():
    
    (images, labels), (_, _) = tf.keras.datasets.mnist.load_data(path="mnist.npz")
    rescaled_images = np.reshape(images, (images.shape[0], images.shape[1] * images.shape[1]))

    indices = np.where(labels==0)
    zero_images = np.take(rescaled_images, indices, axis=0)[0]
    x0 = np.array(zero_images).astype(np.float32)

    length = zero_images.shape[1]
    ones = np.ones(length)
    
    steps = 1000000 # <--- problem even with one step
    mu = -2.0
    sigma = 1.5
    dt = 0.01

    data = []
    for image in x0:
        diff_imgs = [image]
        x = x0
        for i in range(steps):
            x = x + mu * ones * dt + sigma * ones * np.sqrt(dt) * np.random.randn(length)
            diff_imgs.append(x)
        data.append(diff_imgs)

    data = np.array(data, dtype=np.float32)

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    将数据保存到磁盘,可以为您提供更多空间。但是,当您不需要同时需要所有数据或生成的数据的保存历史记录时,您只需创建如何创建数据的配方即可。

    这个想法可以通过使用yield而不是return创建一个生成器来实现(更多的生成器信息参见this thread)。因此,您可以为逻辑创建配方,然后在每次需要更多数据时调用该对象的 next 函数。

    你的例子:

    import numpy as np
    import tensorflow as tf
    import 
    
    # Constants:
    MU = -2.0
    SIGMA = 1.5
    DT = 0.01
    
    
    def img_add_noise(image):
        return(image+MU*DT+SIGMA*np.sqrt(DT)*np.random.randn(len(image)))
    
    def data_add_noise(images, steps):
        for image in images:
            batch_data = [image]
            for i in range(steps):
                batch_data.append(img_add_noise(batch_data[-1]))
            yield(np.stack(batch_data).astype(np.float32))
    
    
    def main():
        (images, labels), (_,_) = tf.keras.datasets.mnist.load_data(path="mnist.npz")
        rescaled_images = images.reshape(len(images), -1)
        zero_images = np.take(rescaled_images, indices, axis=0)[0]
        data = data_add_noise(zero_images, 10)
        sample_data = next(data)
        print(sample_data.shape)
    
    if __name__ == '__main__':
        main()
    

    这样你也可以把data_add_noise函数中for image in images的for循环改成可以生成无限量数据的函数

    counter = 0
    while True:
        image = images[counter%len(images)]
        counter += 1
    

    如果生成的数据用于训练 tensorflow 模型,请查看 here,如何使用 sequence 来实现。

    【讨论】:

      猜你喜欢
      • 2016-06-04
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2017-02-04
      • 2021-02-13
      • 2018-10-12
      • 2014-08-16
      • 2016-08-10
      相关资源
      最近更新 更多