0
votes

I'm trying to train my Deep Neural Network to recognizing handwritten numbers but I keep getting the error stated previously in the title and I don't know why.

I tried reshaping "x_train" and "y_train", didn't change the result. model.add(Flatten()) did not work aswell.

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)

I'm expecting the training to start but I get this errror instead: ValueError: Error when checking input: expected dense_1_input to have 2 dimensions, but got array with shape (60000, 28, 28).

2

2 Answers

0
votes

You're passing training dataset without reshaping it.

Instead of this line:

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)

Use this:

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)
0
votes

You need to transform the dataset from having shape (n, width, height) to (n, depth, width, height).

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