'Wrong prediction results from keras saved model

I trained a model using the cars196 dataset. I achieved a 98 % training accuracy and 94% validation accuracy. This was done using Transfer Learning with the MobileNet Pretrained Model. The model correctly predicts classes before it is saved. Once the model is saved, i am unable to get accurate results.

My code below

model = tf.keras.models.load_model(
  'tdf_cars.h5',
  # `custom_objects` tells keras how to load a `hub.KerasLayer`
  custom_objects={'KerasLayer': hub.KerasLayer},
)

model.compile(loss='sparse_categorical_crossentropy',
              optimizer='adam',
              metrics=['sparse_categorical_accuracy'])

URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"

IMAGE_RES = 224

model = tf.keras.models.load_model(
  'tdf_cars.h5',
  # `custom_objects` tells keras how to load a `hub.KerasLayer`
  custom_objects={'KerasLayer': hub.KerasLayer(URL,
                                   input_shape=(IMAGE_RES, IMAGE_RES, 3))}
)"""

img_size = (224,224)

# model.build([None, 224, 224, 3])

image1 = '00126.jpg'

image_batch = ['00008.jpg', '00009.jpg']


image = keras_preprocessing.image.load_img(image1, target_size=img_size)
x = keras_preprocessing.image.img_to_array(image)

x = np.expand_dims(x, axis=0)

#images = np.vstack([x])


classes = model.predict(x)
predicted_ids = np.argmax(classes, axis=-1)

print(labels[predicted_ids[0]])```


Solution 1:[1]

first of all do you have any errors when loading the model and save for next time using?

[ Sample ]:

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: DataSets
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
ds = tfds.load('cars196', split='train', shuffle_files=True)
ds = ds.shuffle(1024).batch(64).prefetch(tf.data.experimental.AUTOTUNE)
assert isinstance(ds, tf.data.Dataset)
options = tf.saved_model.LoadOptions(
    allow_partial_checkpoint=False,
    experimental_io_device="/physical_device:GPU:0",
    experimental_skip_checkpoint=True
)
encoder = hub.KerasLayer( model_path, trainable=False, load_options=options)
model = tf.keras.models.Sequential([ 
    tf.keras.layers.InputLayer(input_shape=( 224, 224, 3 )),
    encoder
])

model.save_weights(checkpoint_path)

...Sample

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martijn Pieters