[英]ValueError: Error when checking input: expected dense_1_input to have shape (24,) but got array with shape (1,)
[英]Error when checking input: expected dense_1_input to have shape (784,) but got array with shape (10,)
我正在通過一本書學習 Keras。
我執行了書中的代碼,但出現錯誤。
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')
錯誤信息:
ValueError: Error when checking input: expected dense_1_input to have shape (784,) but got array with shape (10,)
我發現了其他相關問題。 它是由尺寸問題引起的,但我認為我的不是這個原因。
我該怎么辦?
MNIST 只有 10 個類別,因為它們是從 0 到 9 的數字,但是在您的代碼中,您有一行:
model.add(Dense(units=64, input_dim=28*28, activation='relu'))
其中說, input_dim=768
- 你可能想要擺脫:
x_train = np_utils.to_categorical(y_train)
x_test = np_utils.to_categorical(y_test)
因為:
>>> x_test = np_utils.to_categorical(y_test)
>>> x_test.shape
(10000, 10)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.