【问题标题】:Error when checking input: expected dense_1_input to have shape (784,) but got array with shape (10,)检查输入时出错:预期dense_1_input 的形状为(784,),但得到的数组的形状为(10,)
【发布时间】:2020-04-01 00:32:21
【问题描述】:

我正在通过一本书来研究 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,)

我找到了other relative question。这是由尺寸问题引起的,但我认为我的不是原因。

我该怎么办?

【问题讨论】:

    标签: python numpy tensorflow keras deep-learning


    【解决方案1】:

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-10-22
      • 1970-01-01
      • 2020-04-11
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 2018-09-30
      • 1970-01-01
      相关资源
      最近更新 更多