训练模型时出现内存错误:无法为形状为(3094, 720, 1280, 3)且数据类型为float32的数组分配31.9 GiB的内存

因此,我根据是否有人存在,将我的图像标记为“0”和“1”。当我传递所有图像并尝试训练我的模型时,会出现内存错误。

    import warnings    warnings.filterwarnings('ignore')    import tensorflow as to    import tensorflow.keras    from tensorflow.keras.preprocessing.image import ImageDataGenerator    from tensorflow.keras.callbacks import ReduceLROnPlateau, CSVLogger, EarlyStopping    from tensorflow.keras.models import Model    from tensorflow.keras.layers import GlobalAveragePooling2D, Dense    from tensorflow.keras.applications.resnet50 import ResNet50    from PIL import Image    import os    import numpy as np    train_x=[]    train_y=[]    for path in os.listdir('C:\\Users\\maini_\\Desktop\\TestAndTrain\\in\\train'):        img = Image.open('C:\\Users\\maini_\\Desktop\\TestAndTrain\\in\\train\\'+path)        train_x.append(np.array(img))        train_y.append(1)        img.close()    for path in os.listdir('C:\\Users\\maini_\\Desktop\\TestAndTrain\\notin\\train'):        img = Image.open('C:\\Users\\maini_\\Desktop\\TestAndTrain\\notin\\train\\'+path)        train_x.append(np.array(img))        train_y.append(0)        img.close()    print("done" )   train_x = np.array(train_x)   train_x = train_x.astype(np.float32)   train_x /= 255.0   train_y = np.array(train_y)

enter image description here

我正在使用

  • Jupyter notebook版本:6.0.3
  • Python版本:3.7
  • Anaconda版本:4.8.3

回答:

您尝试将3094张大小为720x1280的图像作为一个单一批次传递到您的模型中,导致总共31.9GB的数据。您的GPU超载,无法一次性存储和处理所有这些数据,您需要使用批次处理。

由于每次尝试处理数据时都会遇到问题,我建议使用ImageDataGenerator()flow_from_directory(),这些会自动加载图片进行训练。

理想的设置方式如下

train_datagen = ImageDataGenerator(    rescale=1./255,    validation_split=0.3)   #将数据按70/30的比例分割用于训练和验证train_generator = train_datagen.flow_from_directory(        train_data_dir,        color_mode='grayscale',         target_size=(img_width, img_height),        batch_size=batch_size,        class_mode='categorical',        shuffle=True,        subset='training')validation_generator = train_datagen.flow_from_directory(        train_data_dir,          color_mode='grayscale',        target_size=(img_width, img_height),        batch_size=batch_size,        class_mode='categorical',        shuffle=True,        subset='validation')

然后要拟合模型,您需要调用model.fit_generator()

model.fit_generator(train_generator, epochs=epochs, callbacks=callbacks, validation_data=validation_generator)

这是处理大量图像训练模型的最佳方式,因为数据是按批次从目录中生成(或流动)的,而不是在Python中手动加载。唯一的注意事项是目录设置与您当前的略有不同。您需要将目录设置更改为

TestAndTrain -Train   -in   -notin -Test   -in   -notin

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中创建了一个多类分类项目。该项目可以对…

发表回复

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