ValueError: Error when checking input: expected input_1 to have 2 dimensions, but got array with sha

在使用全连接层进行对mnist数据进行分类识别时,爆了这个错:

ValueError: Error when checking input: expected input_1 to have 2 dimensions, but got array with shape (60000, 28, 28)

意思也很明白,就是模型希望输入一个2维的tensor进来,结果输入进来了(60000,28,28)这个三维变量。

明显是代码中没有对输入数据进行由2维变1维的操作,对于全连接神经网络来说,所有输入都必须变成1维。

x_train = data.reshape(len(data),-1)
y_train = np_utils.to_categorical(labels, 10)
完整的mnist识别的代码:

from keras.layers import Input,Dense
from keras.models import Model
from keras.datasets import mnist
from keras.utils import np_utils
import numpy as np

(data,labels),(x_test,y_test) = mnist.load_data()

x_train = data.reshape(len(data),-1)
y_train = np_utils.to_categorical(labels, 10)

# This returns a tensor
inputs = Input(shape=(784,))

# a layer instance is callable on a tensor, and returns a tensor
x = Dense(64, activation='relu')(inputs)
x = Dense(64, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x)

# This creates a model that includes the Input layer and three Dense layers
model = Model(inputs=inputs, outputs=predictions)
model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
model.fit(x_train, y_train)  # starts training
model.summary()
其实这种尺寸报错在平时调整模型中很常见。

你可能感兴趣的:(报错集合)