Issue
I've written so simple handwritten classifier example. It works great, it has %98 accuracy on test samples. However, when I have given an sample input to it, np.argmax gives wrong index (even the ones larger than the size of the classes). Could you help me?
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from keras import layers,datasets,models
os.environ['TFF_CPP_MIN_LOG_LEVEL'] = '2'
(training_images,training_labels),(testing_images,testing_labels)= datasets.mnist.load_data()
training_images,testing_images = training_images/255.0,testing_images/255.0
class_names = [0,1,2,3,4,5,6,7,8,9]
model = keras.Sequential(
[
layers.Flatten(input_shape=(28,28)),
layers.Dense(512,activation="relu"),
layers.Dense(256,activation="relu"),
layers.Dense(10),
]
)
model.compile(
optimizer=keras.optimizers.Adam(lr=0.001),
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=["accuracy"]
)
model.fit(training_images,training_labels,epochs=5,batch_size=32,verbose=2)
loss,accuracy=model.evaluate(testing_images,testing_labels)
print(f"Loss: {loss}")
print(f"Accuracy: {accuracy}")
model.save("handwritten_classifier.model")
model = models.load_model("handwritten_classifier.model")
img = cv.imread("seven.png")
img = cv.cvtColor(img,cv.COLOR_BGR2RGB)
print(np.array(img).shape)
plt.imshow(img,cmap=plt.cm.binary)
prediction = model.predict(img.reshape(-1,28,28)/255.0)
plt.show()
print(prediction)
index = np.argmax(prediction)
print(index)
print(f"Prediction is {class_names[index]}")```
I've tried reshaping the input matrix but it did not work..
Solution
I ran this code, and looked at the predictions. They seem to mostly work for me as well as make the right predictions. The cv2 function failed for me, so I used PIL for image processing instead. One reason there could be more classes predicted is if you don't successfully convert to grayscale. In that case the shape could become (4, 28, 28) instead of (1, 28, 28). So, the model will think there is a batch size of 4 and make 4 predictions.
from PIL import Image
image_name = "five.png"
image = Image.open(image_name)
img = image.resize((28, 28), Image.Resampling.LANCZOS)
img = img.convert("L")
print(np.array(img).shape)
plt.imshow(img, cmap=plt.cm.binary)
prediction = model.predict(np.array(img).reshape(-1,28,28)/255.0)
plt.show()
print(prediction)
index = np.argmax(prediction)
print(index)
print(f"Prediction is {class_names[index]}")
See Colab here - https://colab.research.google.com/drive/1GsScScPgFdhT5y8RNU1owZaZwzAF0Hjc?usp=sharing
Answered By - Peter Chatain
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.