I have a images of digits from electricity meter and I want to recognize it.
I’ve made a code to create the model with keras and it’s accuracy is about 0.999.
But when i use the saved model to recognize the digits, it some times is very close to 0.00 even using the train samples, so i can’t understand what i do wrong and why the accuracy in result is very poor?
Here is my dataset (about 25000 images): https://drive.google.com/file/d/1KN_g1ukX0TBIm_552Sqc3HjBXu1Z-A5l/view?usp=sharing
Here is the code:
import os
import numpy as np
from tensorflow import data as tf_data
import matplotlib.pyplot as plt
import PIL
import tensorflow as tf
from keras import layers
import keras
image_size = (42, 66)
img_height = image_size[0]
img_width = image_size[1]
batch_size = 32
train_ds, val_ds = keras.utils.image_dataset_from_directory(
"D:\Downloads\out",
validation_split=0.2,
subset="both",
color_mode="rgb",
seed=123,
image_size=image_size,
batch_size=batch_size,
)
class_names = train_ds.class_names
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
normalization_layer = layers.Rescaling(1./255)
normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
image_batch, labels_batch = next(iter(normalized_ds))
first_image = image_batch[0]
num_classes = len(class_names)
model = keras.Sequential([
layers.Rescaling(1./255, input_shape=(img_height, img_width, 3)),
layers.Conv2D(32, (3, 3), activation='relu'),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64, (3,3), activation='relu'),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(num_classes)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
epochs=15
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=epochs
)
model.save('D:\Downloads\model.keras')
################
#testing the model
################
digit = 3
directory = "D:\Downloads\out\" + str(digit) + "\"
images = []
images = os.listdir(directory)
model = keras.models.load_model('D:\Downloads\model.keras')
i = 0
acc = 0
for image in images:
i+=1
image_path = directory + image
image = keras.utils.load_img(image_path)
input_arr = keras.utils.img_to_array(image)
input_arr = np.array([input_arr]) # Convert single image to a batch.
predictions = model.predict(input_arr, verbose="0")
result = np.argmax(predictions)
acc+=1
if np.argmax(predictions) != digit:
acc-=1
print (acc*100/i)
print (acc)
print (len(images))
Валентин is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.