首页 > 解决方案 > ValueError:TensorFlow2 Input 0 与层模型不兼容

问题描述

我正在尝试使用 Python3、TensorFlow2 和 CIFAR-10 数据集基于论文编写 ResNet CNN 架构。您可以在此处访问 Jupyter 笔记本。

在使用“model.fit()”训练模型期间,经过一个时期的训练,我收到以下错误:

ValueError:输入 0 与层模型不兼容:预期形状=(None, 32, 32, 3),找到形状=(32, 32, 3)

训练图像使用 batch_size = 128 进行批处理,因此训练循环给出了 TF Conv2D 期望的以下 4-d 张量 - (128, 32, 32, 3)。

这个错误的根源是什么?

标签: pythontensorflowconv-neural-networkresnet

解决方案


好的,我在您的代码中发现了一个小问题。问题出现在测试数据集中。您忘记正确转换它。所以目前你有这样的

images, labels = next(iter(test_dataset))
images.shape, labels.shape

(TensorShape([32, 32, 3]), TensorShape([10]))

您需要在测试中进行与在训练集上相同的转换。但当然,你考虑的事情:没有洗牌,没有增强。

def testaugmentation(x, y):
    x = tf.image.resize_with_crop_or_pad(x, HEIGHT + 8, WIDTH + 8)
    x = tf.image.random_crop(x, [HEIGHT, WIDTH, NUM_CHANNELS])
    return x, y

def normalize(x, y):
    x = tf.image.per_image_standardization(x)
    return x, y

test_dataset = (test_dataset
        .map(testaugmentation)
        .map(normalize)
        .batch(batch_size = batch_size, drop_remainder = True))

images, labels = next(iter(test_dataset))
images.shape, labels.shape
(TensorShape([128, 32, 32, 3]), TensorShape([128, 10]))

推荐阅读