简体   繁体   中英

How do I make predictions on the MNIST dataset with reshaping?

I'm working on a simple example of a ANN using the MNIST dataset. I think I understand the basic breakdown of the model, including reshaping the data, but I'm having trouble with the prediction aspect. 

model = keras.Sequential([
    layers.Dense(512, activation='relu'),
    layers.Dense(100, activation='relu'),
    layers.Dense(10, activation='softmax')
])

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

train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype("float32") / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype("float32") / 255

model.fit(train_images, train_labels, epochs=5, batch_size=128)
model.predict(test_images)

img = test_images[4].reshape(28, 28)
plt.imshow(img)

model.predict(test_images[4])

When I predict on "img," I get the following error: " ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape (None, 1)." However, I reshaped "IMG," so I'm not sure how to fix the error to test the model's prediction. I also tried model.predict(img). Please advise.

Change your code below:

train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype("float32") / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype("float32") / 255

Use this code: Your layers arent getting correct input shape

X_train, X_test = X_train / 255, X_test /255
X_train = np.expand_dims(X_train, -1)
X_test = np.expand_dims(X_test, -1)

X_train.shape    // Shape should be (60000,28,28,1)

//Before using labels do this
y_train = to_categorical(y_train, K)
y_test = to_categorical(y_test, K)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM