MysteryCoder456
MysteryCoder456

Reputation: 469

Tensorflow gives error when predicting: expected axis -1 of input shape to have value 784 but received input with shape [None, 28]

When I make a prediction using a neural network in TensorFlow using Python, I get the following error: ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape [None, 28].

I am trying to follow the tutorial on Tensorflow's site to train a neural network to classify clothing items. I have written the following code:

import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
from skimage import color, io

print(tf.__version__)

data = keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = data.load_data()

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
train_images = train_images / 255
test_images = test_images / 255


model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation="relu"),
    keras.layers.Dense(10, activation="softmax")
])

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

model.fit(train_images, train_labels, epochs=20)

print(type(test_images))
images = [test_images[0]]

predictions = model.predict(images)

print(class_names[np.argmax(predictions[0])])

Any help is much appreciated, TIA.

Upvotes: 0

Views: 1445

Answers (1)

user11530462
user11530462

Reputation:

From the comment section for the benefit of the community.

By changing the model.predict(images) to below lines has solved the issue.

model.predict(np.expand_dims(test_images[0],0))

Upvotes: 1

Related Questions