【问题标题】:ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [8, 28, 28]ValueError:层顺序的输入 0 与层不兼容::预期 min_ndim=4,发现 ndim=3。收到的完整形状:[8, 28, 28]
【发布时间】:2020-11-26 10:56:05
【问题描述】:

我不断收到与输入形状相关的错误。任何帮助将不胜感激。谢谢!

import tensorflow as tf

(xtrain, ytrain), (xtest, ytest) = tf.keras.datasets.mnist.load_data()

model = tf.keras.Sequential([
    tf.keras.layers.Conv2D(16, kernel_size=3, activation='relu'),
    tf.keras.layers.MaxPooling2D(pool_size=2),
    tf.keras.layers.Conv2D(32, kernel_size=3, activation='relu'),
    tf.keras.layers.MaxPooling2D(pool_size=2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
    ])

model.compile(loss='categorical_crossentropy', 
              optimizer='adam',
              metrics='accuracy')

history = model.fit(xtrain, ytrain,
                    validation_data=(xtest, ytest),
                    epochs=10, batch_size=8)

ValueError:层顺序的输入 0 与层不兼容::预期 min_ndim=4,发现 ndim=3。收到的完整形状:[8, 28, 28]

【问题讨论】:

    标签: python tensorflow keras deep-learning


    【解决方案1】:

    您创建的模型的输入层需要使用 4 维张量,但您传递给它的 x_train 张量只有 3 维

    这意味着您必须使用 .reshape(n_images, 286, 384, 1) 重塑您的训练集。现在您已经添加了一个额外的维度而不更改数据,并且您的模型已准备好运行。

    在训练模型之前,您需要将 x_train 张量重塑为 4 维。 例如:

    x_train = x_train.reshape(-1, 28, 28, 1)
    

    有关 keras 输入的更多信息Check this answer

    【讨论】:

      【解决方案2】:

      您需要添加渠道维度。 Keras 需要这种数据格式:

      (n_samples, height, width, channels)
      

      例如,如果您的图像是灰度图像,它们有 1 个通道,因此需要以这种格式将它们提供给 Keras:

      (60000, 28, 28, 1)
      

      不幸的是,灰度图片通常会在没有通道维度的情况下给出/下载,例如在tf.keras.datasets.mnist.load_data,这将是(60000, 28, 28),这是有问题的。

      解决方案:

      您可以使用tf.expand_dims添加维度

      xtrain = tf.expand_dims(xtrain, axis=-1)
      

      现在您的输入形状将是:

      (60000, 28, 28, 1)
      

      还有其他替代方法可以做到这一点:

      xtrain = xtrain[..., np.newaxis]
      xtrain = xtrain[..., None]
      xtrain = xtrain.reshape(-1, 28, 28, 1)
      xtrain = tf.reshape(xtrain, (-1, 28, 28, 1))
      xtrain = np.expand_dims(xtrain, axis=-1)
      

      【讨论】:

      • 你能解释一下(60000, 28, 28, 1)中的60000是什么
      • 样本数
      • 谢谢一件事。我有形状张量 (170, 64, 64) 但是当我增加它的维度时它变成 (170, 4096, 1) 但我想要的是: (170, 64, 64, 1) 我该怎么做???
      • np.expand_dims(your_array, axis=-1)
      猜你喜欢
      • 2020-11-16
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 2020-03-20
      相关资源
      最近更新 更多