I trained a Dense Neural Network with MNIST dataset in order to classify 28x28 images of numbers. Now I was trying to make it work with my own samples (I draw the image of a "7" in paint and I transformed it into an array) but the results are really poor.

from tensorflow.keras.datasets import mnist

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

from tensorflow.keras import models
from tensorflow.keras import layers

network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28*28,)))
network.add(layers.Dense(10, activation='softmax'))


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

from tensorflow.keras.utils import to_categorical

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)


from PIL import Image
import PIL.ImageOps
import os

direccio = 'C:/Users/marcc/OneDrive/Escritorio'

myImage = Image.open("Image.PNG").convert('L')
myImage = PIL.ImageOps.invert(myImage)
myImage = myImage.resize((28,28))

#transforming my image into an array (THE PROBLEM MUST BE HERE)
import numpy as np
myImage_array = np.array(myImage)
myImage_array = myImage_array.reshape((28*28))
myImage_array = myImage_array.astype('float32') / 255


The code until DEMO is made by François Chollet. I only made the last part which is the implementation of my own image.

The results that I get after testing it with the image of a seven are:

[[6.9165975e-03 3.0256975e-03 4.9591944e-01 4.8350231e-03 5.6093242e-03
  8.6059235e-03 4.5295963e-01 8.3720963e-04 2.1008164e-02 2.8301307e-04]]

As you can see this results are pretty bad because it should give the higher probability to the seventh position which is the one that corresponds to number seven. I don't know what I missed but I think that the way I normalize the vector must be the problem. The model works fine with the test data of MNIST so I think that the problem is that is not able to read my own data the same way.

If I plot an image of MNIST using the code:

digit = train_images[4]
import matplotlib.pyplot as plt
plt.imshow(digit, cmap=plt.cm.binary)

It looks like:

MNIST image of a 9

If I do the same with my image:  My Image of a 7 (after being transformed to an array)

  • $\begingroup$ Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. $\endgroup$
    – Community Bot
    Oct 19 at 7:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.