2

I have trained my model and it works fine. Then I went on to predict single images (jpg). This also works, but I don't get the exact probabilities now.

This is my model:

def train():
mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()
#nomalize data
x_train = tf.keras.utils.normalize(x_train, axis=1)
x_test = tf.keras.utils.normalize(x_test, axis=1)
#train model
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=3)

model.save('Mnist')
print("Done with training :)")

And this is how I predict my single image:

def predict(testImg):
    import numpy as np
    model = load_model('Mnist')
    img = testImg.convert('L').resize((28,28), Image.ANTIALIAS)
    img = np.array(img)
    predictions = model.predict(img[None,:,:])

I am suspecting it has something to do with the img[None,:,:] reshaping because the predict function was giving back the probabilities with my test set.

Now I am just getting back an array like [0,0,0,0,0,1,0,0,0] and not actual probabilities.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
PhilipAllStar
  • 120
  • 1
  • 9
  • 2
    The length of `predictions` should be 10 ie. `len(predictions) == 10`. Please check it and correct the question. – mujjiga Jul 01 '21 at 18:12

1 Answers1

1

It turned out I was missing these lines before I made my prediction to normalize my array.

        img = img.astype('float32')
        img /= 255

As also discribed here: Returning probabilities in a classification prediction in Keras?

PhilipAllStar
  • 120
  • 1
  • 9