如何在Kaggle笔记本中加载大型numpy文件而不导致内存溢出?

我在使用一个数据集,在配备GPU的Kaggle笔记本上训练Keras深度学习模型。数据集包含一个csv文件,其中包含一个id,对应于另一个目录中的.tif图像,以及一个标签,1或0。我平衡了数据并使用numpy.save()保存(见代码1)。这运行得很好,之后我下载了文件并重新上传为数据集。然而,当我在另一个笔记本中使用numpy.load()(见代码2)尝试使用这个数据集时,我遇到了以下错误:

Your notebook tried to allocate more memory than is available. It has restarted.

我一直在跟随这个教程,它已经有几年了,所以我在创建数组时可能做了不必要的步骤。我该如何解决内存溢出的问题?

我已经尝试使用pickle来保存代码1生成的数组,但它有同样的内存溢出错误。

代码1:

import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport osimport cv2import randomdf = pd.read_csv("../input/histopathologic-cancer-detection/train_labels.csv")ones_subset = df.loc[df["label"] == 1, :]num_ones = len(ones_subset)zeros_subset = df.loc[df["label"] == 0, :]sampled_zeros = zeros_subset.sample(num_ones)print(num_ones)print(sampled_zeros)df = pd.concat([ones_subset, sampled_zeros], ignore_index=True)df = df.groupby("label").sample(50000).sample(frac=1).reset_index(drop=True)print(df)DATADIR = "../input/histopathologic-cancer-detection/train"IMG_SIZE = 96training_data = []def create_training_data():    for i in range(0,len(df.index)):        img_path = df.iloc[i,0]+".tif"        path = os.path.join(DATADIR, img_path)        img_array = cv2.imread(path, cv2.IMREAD_GRAYSCALE)        class_num = df.iloc[i,1]        training_data.append([img_array,class_num])        print(i)create_training_data()print(len(training_data))random.shuffle(training_data)X = []y = []count = 0for features, label in training_data:    X.append(features)    y.append(label)    count += 1    print(count)X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 1)np.save('image_arrays.npy',X)np.save('labels.npy',y)

代码2:

更新1:
我尝试使用评论建议的np.memmap()。我对它不太熟悉,所以我不确定我是否正确使用了它,但我尝试了以下代码,并且出现了同样的内存错误:

X = np.memmap("../input/metastasis-cancer-100000/image_arrays.npy", mode="r")y = np.memmap("../input/metastasis-cancer-100000/labels.npy", mode="r")

回答:

问题通过使用以下方法解决:

X = np.load('../input/metastasis-cancer-100000/image_arrays.npy', mmap_mode='r') 

这样做只是作为一个普通的数组,但由磁盘支持。还要考虑到,它的速度会比由RAM支持的数组慢。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注