我对 Python 和机器学习总体来说非常陌生,最近一直在参与一个与学校相关的项目。我目前被这个代码块困住了,因为当我加载 npy 文件时它占用了太多的内存空间。
features_list = []
labels_list = []
for i in range(9221):
npy_path = f'E:/padFrames/video_{i}.npy'
frames_array = np.load(npy_path, mmap_mode='r')
# Append frames to the features list
features_list.append(frames_array)
# Extract labels for the current video
labels = df.iloc[i][categoryEmotions].values
labels_list.append(labels)
# Convert features list to numpy array
features = np.asarray(features_list)
# Convert labels list to numpy array
labels = np.array(labels_list)
features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size = 0.25, shuffle = True, random_state = 42)
我有 16GB 的 RAM,.npy 文件总共有 (9221) 个,形状为 (298, 32, 32, 3),每个文件大小为 895kb。我的代码中是否有错误或缺失?有没有办法加载这些 npy 文件而不占用太多内存?
我尝试过这个潜在的解决方案: 删除数据 gc.collect()
但它不适用于我的情况。希望得到好的答复。
features_list
约为 9 GB,features
又是 9 GB。超过 16GB。
将一个
.npy
文件直接读取到 features
中,重新调整其形状以添加大小为 1 的额外维度,将该维度大小调整为 9221,然后将接下来的 9220 个文件分配给 features
的切片可能会更容易。这意味着您一次分配 895 kB,而仅使用 9 GB 多一点。
numpy 和大数据的技巧是将所有内容保留在 numpy 中,而不是原始 Python 列表中,当然也不要在两者之间进行转换。