ValueError:检查输入时出错:预期density_1_input具有2维,但数组的形状为(60000,28,28)

时间:2019-08-09 11:15:54

标签: python keras

我正在尝试训练我的深度神经网络来识别手写数字,但是我不断收到标题中先前提到的错误,我不知道为什么。

我尝试重塑“ x_train”和“ y_train”,但未更改结果。 model.add(Flatten())也不起作用。

import matplotlib.pyplot as plt
import keras
from keras import optimizers
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten
from keras.datasets import mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()

train_images = x_train.reshape(60000, 784)
test_images = x_test.reshape(10000, 784)
train_images = train_images.astype('float32')
test_images = test_images.astype('float32')
train_images /= 255
test_images /= 255

train_labels = keras.utils.to_categorical(y_train, 10)
test_labels = keras.utils.to_categorical(y_test, 10)

model = Sequential()

model.add(Dense(512, activation="relu", input_shape=(784,)))

for x in range (0, 10):
    model.add(Dense(512, activation="relu"))

model.add(Dense(10, activation="softmax"))
model.summary()

model.compile(optimizer="rmsprop", loss="binary_crossentropy", metrics=['accuracy'])

model.fit(x_train, y_train, epochs=100, verbose=2, validation_split=0.0, shuffle=True, initial_epoch=0, validation_data=(train_images, train_labels), steps_per_epoch=10, validation_steps=10, validation_freq=1)

我希望培训开始,但是我得到了这个错误:ValueError:检查输入时出错:预期density_1_input具有2维,但是数组的形状为(60000,28,28)。

2 个答案:

答案 0 :(得分:0)

您需要将数据集从形状(n,宽度,高度)转换为(n,深度,宽度,高度)。

X_train = X_train.reshape(X_train.shape[0], 1, 28, 28) X_test = X_test.reshape(X_test.shape[0], 1, 28, 28)

答案 1 :(得分:0)

您正在传递训练数据集而没有对其进行重塑。

代替此行:

model.fit(x_train, y_train, epochs=100, verbose=2, validation_split=0.0, shuffle=True, initial_epoch=0, validation_data=(train_images, train_labels), steps_per_epoch=10, validation_steps=10, validation_freq=1)

使用此:

model.fit(train_images, train_labels, epochs=100, verbose=2, validation_split=0.0, shuffle=True, initial_epoch=0, validation_data=(train_images, train_labels), steps_per_epoch=10, validation_steps=10)