ValueError:层顺序的输入0与层不兼容::预期的min_ndim = 4,找到的ndim = 3.收到的完整形状:[8、28、28] [英] ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [8, 28, 28]

查看:1794
本文介绍了ValueError:层顺序的输入0与层不兼容::预期的min_ndim = 4,找到的ndim = 3.收到的完整形状:[8、28、28]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不断遇到与输入形状有关的错误.任何帮助将不胜感激.谢谢!

I keep on getting this error related to input shape. Any help would be highly appreciated. Thanks!

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]

ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [8, 28, 28]

推荐答案

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

The input layers of the model you created needs a 4 dimension tensor to work with but the x_train tensor you are passing to it has only 3 dimensions

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

This means that you have to reshape your training set with .reshape(n_images, 286, 384, 1). Now you have added an extra dimension without changing the data and your model is ready to run.

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

you need to reshape your x_train tensor to a 4 dimension before training your model. for example:

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

有关keras输入的更多信息检查此答案

for more info on keras inputs Check this answer

这篇关于ValueError:层顺序的输入0与层不兼容::预期的min_ndim = 4,找到的ndim = 3.收到的完整形状:[8、28、28]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆