python - Keras CNN 自动编码器输入形状错误

标签 python opencv keras deep-learning conv-neural-network

我已经使用 keras 构建了一个 CNN 自动编码器,它对 MNIST 测试数据集运行良好。我现在正在尝试使用从另一个来源收集的不同数据集。有纯图像,我必须使用 cv2 阅读它们,效果很好。然后我将这些图像转换成一个 numpy 数组,我认为它再次工作正常。但是当我尝试执行 .fit 方法时,它给了我这个错误。

Error when checking target: expected conv2d_39 to have shape (100, 100, 1) but got array with shape (100, 100, 3)

我尝试将图像转换为灰度,但它们随后得到的是模型想要的形状 (100,100) 而不是 (100,100,1)。我在这里做错了什么?

这是我使用的代码:

def read_in_images(path):
    images = []
    for files in os.listdir(path):
        img = cv2.imread(os.path.join(path, files))
        if img is not None:
            images.append(img)
    return images

train_images = read_in_images(train_path)
test_images = read_in_images(test_path)
x_train = np.array(train_images)
x_test = np.array(test_images) # (36, 100, 100, 3)

input_img = Input(shape=(100,100,3))
x = Conv2D(32, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)
encoded = MaxPooling2D((2, 2), padding='same')(x)


x = Conv2D(16, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(168, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(32, (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')


autoencoder.fit(x_train, x_train,
            epochs=25,
            batch_size=128,
            shuffle=True,
            validation_data=(x_test, x_test),
            callbacks=[TensorBoard(log_dir='/tmp/autoencoder')])

该模型适用于 MNIST 数据集,但不适用于我自己的数据集。任何帮助将不胜感激。

最佳答案

您的输入和输出形状不同。这会触发错误(我认为)。

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

应该是

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

关于python - Keras CNN 自动编码器输入形状错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56438374/

相关文章:

map 检测上的Python OpenCV纬度曲线

python - 在 HSV 颜色空间(Python、OpenCV、图像分析)中定义组织学图像掩码的颜色范围 :

神经网络的 Matlab 实现大大优于 Keras 变体

python - Keras多实例分类问题

python - 字符串作为关键字参数,并将来自 str.partition() 输出的多个字典合并为一个字典

python - 绘图轴上不重叠的数字

python - 在 matplotlib 中绘制方形等高线图

Python 网络/cidr 计算

opencv - 使用Tesseract OCR读取错误

python - 无法在仅 tensorflow CPU 安装上加载动态库 'cudart64_101.dll'