如何在 keras 生成器中使用 numpy memmap 不超过 RAM 内存?

2024-02-10

我正在尝试在生成器内实现 numpy.memmap 方法,以使用 keras 训练神经网络,以免超出内存 RAM 限制。我用这个作为参考post https://stackoverflow.com/questions/45132940/numpy-memmap-memory-usage-want-to-iterate-once然而没有成功。这是我的尝试:

def My_Generator(path, batch_size, tempo, janela):
  samples_per_epoch  = sum(1 for line in np.load(path))
  number_of_batches = samples_per_epoch/batch_size
  #data = np.memmap(path, dtype='float64', mode='r+', shape=(samples_per_epoch, 18), order='F')
  data = np.load(path)
  # create a memmap array to store the output
  X_output = np.memmap('output', dtype='float64', shape=(samples_per_epoch, 96, 100, 17), mode='r+', order='F')
  y_output = np.memmap('output', dtype='float64', shape=(samples_per_epoch, 1), mode='r+', order='F')
  holder = np.zeros([batch_size, 18], dtype='float64')
  counter=0

  while 1:
    holder[:] = data[counter:batch_size+counter]
    X, y = input_3D(holder, tempo, janela) 
    lenth_X = len(X)
    lenth_y = len(y)
    print(lenth_X, lenth_y)
    y = y.reshape(-1, 1)
    X_output[0:lenth_X, :] = X
    y_output[0:lenth_y, :] = y
    counter += 1
    yield X_output[0:lenth_X, :].reshape(-1, 96, 10, 10, 17), y_output[0:lenth_y, :]
    #restart counter to yeild data in the next epoch as well
    if counter >= number_of_batches:
        counter = 0

尽管如此,它仍然将这些块保存在 RAM 内存中,以便在一些时期之后它会超出其限制。

Thanks


按照这里的方法:

https://stackoverflow.com/a/61472122/2962979 https://stackoverflow.com/a/61472122/2962979

您也许可以通过每次重建 memmap 对象来解决您的问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 keras 生成器中使用 numpy memmap 不超过 RAM 内存? 的相关文章

随机推荐