ValueError:密集层的输入 0 与该层不兼容(新手问题)
我想用MNIST设置做点什么,但它不起作用,如果有人可以帮助我( https://www.youtube.com/watch?v=ZI4I7Q0ZRBS&lc;lc; lc; lc = ugxa2zg7_jxi7jj3pj3pj3pjl4aaaaaaaabag.9ogalubwzvo9_ztcihrygbbbbbbbb )
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
# load dataset of handwritten digits
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# normalise training data and cut down between 0 and 255 (greyscale)
x_train = tf.keras.utils.normalize(x_train, axis=1)
x_test = tf.keras.utils.normalize(x_test, axis=1)
# y_values already declared because they are from 0-9
model = tf.keras.models.Sequential()
# flatten layer
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
# all neurons are connected with the layers, units make neurons you wanna have in layer
# 2 dense hidden layers
model.add(tf.keras.layers.Dense(units=128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(units=128, activation=tf.nn.relu))
# output layer
model.add(tf.keras.layers.Dense(units=10, activation=tf.nn.softmax))
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(x_train, y_train, epochs=3)
loss, accuracy = model.evaluate(x_test, y_test)
print(accuracy)
print(loss)
model.save("digits.model")
for x in range(1,4):
img = cv.imread(f"{x}.png")[:,:,0]
# invert to make it black and white digits
img = np.invert(np.array([img]))
prediction = model.predict(img)
print(f"The result ist probably: {np.argmax(prediction)}")
plt.imshow(img[0], cmap=plt.cm.binary)
plt.show()
我得到这个错误:
ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape [None, 829440]
如何解决此问题?
谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您传递给模型的训练数据可能不在(28,28)形状中。如果它们处于(28,28)的形状,则其输入形状为(28*28)= 784。因此,请尝试调整输入图像并将其调整到(28,28)。
尽管我试图在Google Colab&中运行您的代码。训练零件对我来说没有任何错误。
Probably the training data you are passing to the model are not in (28,28) shape. If they are in (28,28) shape, then it would have an input shape of (28*28) = 784. So try to resize the input images and resize them to (28,28).
Though I tried to run your code in Google colab & the training part ran without any error for me.