[英]Error when checking input: expected dense_1_input to have shape (784,) but got array with shape (10,)
I'm studying Keras by a book.我正在通过一本书学习 Keras。
And I executed a code in the book, but I got error.我执行了书中的代码,但出现错误。
from keras.utils import np_utils
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np
from numpy import argmax
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784).astype('float32') / 255.0
x_test = x_test.reshape(10000, 784).astype('float32') / 255.0
x_train = np_utils.to_categorical(y_train)
x_test = np_utils.to_categorical(y_test)
x_val = x_train[:42000]
x_train = x_train[42000:]
y_val = y_train[:42000]
y_train = y_train[42000:]
model = Sequential()
model.add(Dense(units=64, input_dim=28*28, activation='relu'))
model.add(Dense(units=10, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5, batch_size=32, validation_data=(x_val, y_val))
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=32)
print('')
print('loss_and_metrics : ' + str(loss_and_metrics))
from keras.models import load_model
model.save('mnist_mlp_model.h5')
Error message:错误信息:
ValueError: Error when checking input: expected dense_1_input to have shape (784,) but got array with shape (10,)
I found other relative question .我发现了其他相关问题。 It was caused by a dimension problem, but I think mine was not by the reason.
它是由尺寸问题引起的,但我认为我的不是这个原因。
What should I do?我该怎么办?
MNIST has only 10 categories, because these are numbers from 0 to 9, but in your code you have a line: MNIST 只有 10 个类别,因为它们是从 0 到 9 的数字,但是在您的代码中,您有一行:
model.add(Dense(units=64, input_dim=28*28, activation='relu'))
which says, input_dim=768
-- you may want to get rid of:其中说,
input_dim=768
- 你可能想要摆脱:
x_train = np_utils.to_categorical(y_train)
x_test = np_utils.to_categorical(y_test)
because:因为:
>>> x_test = np_utils.to_categorical(y_test)
>>> x_test.shape
(10000, 10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.