将对象添加到Python数组中会随着添加的项的增加而线性变慢



我是python的新手,所以如果我所做的是愚蠢的请原谅我。我正在尝试创建一个numpy数组的python数组,其中每个数组的形状为(2000,89401)。我总共有35个这样的numpy数组我想把它们附加到python数组中。下面是我的代码:

import numpy as np
import glob
data_filepath = []
for filename in glob.glob('*.npy'):
data_filepath.append(filename)
LIST_SIZE = 2000
train_images  = []
train_labels = []
for i in range(len(data_filepath)):
print("reading file" + data_filepath[i])
train_images.append(np.load(data_filepath[i], encoding='latin1', allow_pickle=True)[0:LIST_SIZE])
train_labels.append(np.ones((LIST_SIZE, 1)) * i)

我添加了一行print("reading file" + data_filepath[i]),以便在代码运行时在终端中打印一行,因此我可以看到执行速度。前4个numpy数组几乎是立即读取的,但随着执行的进行,它变得越来越慢。我让程序运行5分钟,并添加了9个numpy数组。我清空了for循环中的python数组,看看append()是否是罪魁祸首:

.
.
.
for i in range(len(data_filepath)):
print("reading file" + data_filepath[i])
train_images.append(np.load(data_filepath[i], encoding='latin1', allow_pickle=True)[0:LIST_SIZE])
train_labels.append(np.ones((LIST_SIZE, 1)) * i)
train_images = []
train_labels = []

代码在几秒钟内执行。我如何读取我的numpy数组而不造成性能损失?

在将前几个numpy数组加载到python列表后,我的内存已经满了。我能够通过在以下函数中指定mmap_mode='r'来规避这个问题:

train_images.append(np.load(data_filepath[i], mmap_mode='r', encoding='latin1', allow_pickle=True)[0:LIST_SIZE])

mmap_mode告诉numpy打开.npy为只读,而不是将所有内容加载到内存中。

https://numpy.org/doc/stable/reference/generated/numpy.memmap.html numpy.memmap:

"内存映射文件用于访问磁盘上大文件的一小部分,而不需要将整个文件读入内存。NumPy的memmap是类似数组的对象。这与Python的mmap模块不同,后者使用类文件对象。">

最新更新