【问题标题】:ValueError: Error when checking target: expected conv2d_21 to have 4 dimensions, but got array with shape (26, 1)ValueError:检查目标时出错:预期 conv2d_21 有 4 个维度,但得到了形状为 (26, 1) 的数组
【发布时间】:2019-03-02 11:29:29
【问题描述】:

我有形状为(3600, 3600, 3) 的图像。我想对它们使用自动编码器。我的代码是:

from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
from keras import backend as K
from keras.preprocessing.image import ImageDataGenerator


input_img = Input(shape=(3600, 3600, 3))  

x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)



x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')




batch_size=2


datagen = ImageDataGenerator(rescale=1. / 255)

# dimensions of our images.
img_width, img_height = 3600, 3600

train_data_dir = 'train'
validation_data_dir = validation




generator_train = datagen.flow_from_directory(
        train_data_dir,
        target_size=(img_width, img_height),
        )



generator_valid = datagen.flow_from_directory(
        validation_data_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode=None,
        shuffle=False)



autoencoder.fit_generator(generator=generator_train,
            validation_data = generator_valid,
            )

当我运行代码时,我收到以下错误消息:

ValueError: Error when checking target: expected conv2d_21 to have 4 dimensions, but got array with shape (26, 1)

我知道问题出在图层形状的某个地方,但我找不到。有人可以帮我解释一下解决方案吗?

【问题讨论】:

  • 我的猜测是您的数据生成器正在为典型的分类问题提供数据集; IE。 X 用于图像数组,y 用于类。但是您的自动编码器也需要 y 的图像数组。
  • 这可能是问题所在。你能提供一个解决它的代码示例吗?
  • 可惜没时间,不过可以参考github.com/keras-team/keras/issues/3923。 robertomest 在 2016 年 10 月 3 日发表的评论看起来很有希望。

标签: python machine-learning keras conv-neural-network autoencoder


【解决方案1】:

您的代码存在以下问题:

  1. 将class_mode='input' 传递给flow_from_directory 方法以将输入图像也作为标签(因为您正在创建自动编码器)。

  2. 将padding='same' 传递给解码器中的第三个 Conv2D 层:

    x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)
    
  3. 在最后一层使用三个过滤器,因为您的图像是 RGB:

    decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)
    

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 2019-11-13
  • 2020-02-07
  • 2019-09-11
  • 1970-01-01
相关资源
最近更新 更多