【问题标题】:Preparing data for Keras CNN training without the use of ImageDataGenerator在不使用 ImageDataGenerator 的情况下为 Keras CNN 训练准备数据
【发布时间】:2018-08-26 22:03:16
【问题描述】:

我想弄清楚如何在不使用 ImageDataGenerator 的情况下在 Keras 中训练 CNN。本质上,我试图找出 ImageDataGenerator 类背后的魔力,这样我就不必在所有项目中都依赖它。

我有一个数据集,分为 2 个文件夹:training_settest_set。每个文件夹都包含 2 个子文件夹:catsdogs

我在 for 循环中使用 Keras 的 load_img 类将它们全部加载到内存中,如下所示:

trainingImages = []
trainingLabels = []
validationImages = []
validationLabels = []

imgHeight = 32
imgWidth = 32
inputShape = (imgHeight, imgWidth, 3)

print('Loading images into RAM...')

for path in imgPaths:

    classLabel = path.split(os.path.sep)[-2]
    classes.add(classLabel)
    img = img_to_array(load_img(path, target_size=(imgHeight, imgWidth)))

    if path.split(os.path.sep)[-3] == 'training_set':
        trainingImages.append(img)
        trainingLabels.append(classLabel)
    else:
        validationImages.append(img)
        validationLabels.append(classLabel)

trainingImages = np.array(trainingImages)
trainingLabels = np.array(trainingLabels)
validationImages = np.array(validationImages)
validationLabels = np.array(validationLabels)

当我打印 trainingImages 和 trainingLabels 的 shape() 时,我得到:

Shape of trainingImages: (8000, 32, 32, 3)
Shape of trainingLabels: (8000,)

我的模型如下所示:

model = Sequential()
model.add(Conv2D(
        32, (3, 3), padding="same", input_shape=inputShape))
model.add(Activation("relu"))
model.add(Flatten())
model.add(Dense(len(classes)))
model.add(Activation("softmax"))

当我编译并尝试拟合数据时,我得到: ValueError: Error when checking target: expected activation_2 to have shape (2,) but got array with shape (1,)

这告诉我我的数据没有正确输入系统。如何在不使用ImageDataGenerator 的情况下正确准备我的数据数组?

【问题讨论】:

    标签: python keras


    【解决方案1】:

    错误是因为您的模型定义而不是ImageDataGenerator(我在您发布的代码中没有看到使用)。我假设 len(classes) = 2 因为您收到错误消息。您收到错误是因为模型的最后一层期望 trainingLabels 的每个数据点都有一个大小为 2 的向量,但您的 trainingLabels 是一维数组。

    为了解决这个问题,您可以将最后一层更改为只有 1 个单元,因为它是二进制分类:

    model.add(Dense(1))
    

    或者您可以使用一种热编码将您的训练和验证标签更改为向量:

    from keras.utils import to_categorical
    training_labels_one_hot = to_categorical(trainingLabels)
    validation_labels_one_hot = to_categorical(validationLabels)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 2020-09-05
      • 2018-03-29
      • 2020-04-22
      • 1970-01-01
      • 2017-10-26
      • 2017-07-15
      相关资源
      最近更新 更多