【问题标题】:Keras ValueError: fit_generator yielding a listKeras ValueError:fit_generator 产生一个列表
【发布时间】:2017-06-19 17:15:51
【问题描述】:

我正在学习如何使用带有 TF 后端的 Keras 进行图像识别,所以我仍然不确定我在这里做错了什么。

我正在尝试堆叠 2 个模型,一个是 VGG16,另一个是我为学习如何堆叠而制作的随机模型。我想将一张图片分为 5 个类别。

问题出在最后一部分,当我运行 fit_generator 时。它不是产生一个有效的元组,而是产生看起来像一个列表的东西。我见过很多人遇到类似的问题,但在他们的情况下,输出为 None,所以我不确定解决方案是否相同。

参数

nb_train_samples = 576
nb_validation_samples = 144
epochs = 30
batch_size = 12
img_width, img_height = 150, 150

发电机

train_datagen = ImageDataGenerator(
    rescale=1./255,
    rotation_range=50,
    width_shift_range=0.3,
    height_shift_range=0.3,
    shear_range=0.4,
    zoom_range=0.4,
    horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode=None,
    shuffle=False)

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode=None,
    shuffle=False)

我的模型

input = Input(batch_shape=model.output_shape)
x = Flatten()(input)
x = Dense(256, activation='relu', name="new_block_1")(x)
x = Dropout(0.5)(x)
x = Dense(256, activation='relu', name="new_block_2")(x)
x = Dropout(0.5)(x)
x = Dense(5, activation='softmax', name="new_block_3")(x)
top_model = Model(input,x)

input = Input(shape=(img_width, img_height, 3))
x = model(input)
x = top_model(x)
final_model = Model(input, x)

final_model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy', metrics=['accuracy'])

适合与错误

final_model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

ValueError: output of generator should be a tuple `(x, y, sample_weight)` or `(x, y)`. Found: [[[[ 0.89411771  0.89019614  0.87450987]
   [ 0.89411771  0.89019614  0.87450987]
   [ 0.89411771  0.89019614  0.87450987]
   ..., 

更新 1: 根据@petezurich 的提示,将激活函数从“sigmoid”更改为“softmax”

【问题讨论】:

  • 这可能不是直接指您的问题,但是否有特定原因导致您在最后一个密集层上使用 sigmoid 而不是 softmax?
  • Softmax 是您的正确选择,因为它为您提供了 5 个类别中每一个类别的概率。 Sigmoid 对于二元分类是正确的。
  • 我明白了。谢谢你的提示 :) 无论如何,我把它改成了 softmax,但遗憾的是,问题仍然存在
  • 如何获得标签?最简单的方法是将图像放在每个类的子文件夹中,并将生成器中的class_mode 设置为True。生成器可以很好地从中派生类标签。
  • 没有 True,但有一个“分类”值,它确实有效。随时提交它作为答案,我会接受它。非常感谢:)

标签: python-3.x keras keras-2


【解决方案1】:

您的模型缺少用于训练的标签。

只需在您的生成器中将class_mode 设置为categorical,并将您的图像放在每个类的子文件夹中。生成器可以很好地从中派生类标签。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-07
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2020-09-12
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多