神经网络的输入大小不匹配

时间:2019-04-15 14:27:51

标签: python tensorflow machine-learning keras

我是机器学习的新手,并试图为mnist时尚数据集构建CNN,并且该程序中出现了一些错误

  

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

我尝试了很多解决方案,但实际上都没有。

(x_train,y_train),(x_test,y_test) = mnist_fashion.load_data()
mnist_fashion = tf.keras.datasets.fashion_mnist
x_train,x_test = x_train/255,x_test/255

model = Sequential([

    Conv2D(64,(4,4),activation='relu',input_shape = (28,28,1), padding='same'),
    MaxPooling2D(pool_size=(2,2)),
    Dropout(0.1),

    Conv2D(64,(4,4),activation='relu'),
    MaxPooling2D(pool_size=(2,2)),
    Dropout(0.3),

    Flatten(),

    Dense(256,activation='relu'),
    Dropout(0.5),

    Dense(64,activation='relu'),

    Dense(10,activation='softmax')
])

model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])

model.fit(x_train,y_train,epochs=5)

1 个答案:

答案 0 :(得分:2)

将数据从(60000, 28, 28)重塑到(60000, 28, 28, 1)

x_train, x_test = np.expand_dims(x_train, -1), np.expand_dims(x_test, -1)

您可能还希望提供一键编码的标签。要转换为一键编码标签,请执行以下操作:

from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(n_values=10)
y_train = encoder.fit_transform(np.expand_dims(y_train, -1))
y_test = encoder.transform(np.expand_dims(y_test, -1))