I am trying to load my saved keras model

model= tf.keras.models.load_model("my_model.h5",
custom_objects=None,
compile=True)
model.summary()

and getting the following error

Traceback (most recent call last):
File "C:\Users\admin\Desktop\phd python 

projects\tensorflow_img_class\src\tensorflow ui.py", line 45, in <module>
    compile=True
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\saving\save.py", line 146, in load_model
    return hdf5_format.load_model_from_hdf5(filepath, custom_objects, compile)
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\saving\hdf5_format.py", line 212, in load_model_from_hdf5
    custom_objects=custom_objects)
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\saving\model_config.py", line 55, in model_from_config
    return deserialize(config, custom_objects=custom_objects)
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\layers\serialization.py", line 89, in deserialize
    printable_module_name='layer')
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\utils\generic_utils.py", line 192, in deserialize_keras_object
    list(custom_objects.items())))
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\engine\sequential.py", line 353, in from_config
    model.add(layer)
  File "C:\Python37\lib\site-packages\tensorflow\python\training\tracking\base.py", line 460, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\engine\sequential.py", line 174, in add
    layer(x)
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 632, in __call__
    outputs = call_fn(inputs, *args, **kwargs)
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\layers\core.py", line 782, in call
    return self.function(inputs, **arguments)
  File "C:/Users/admin/Desktop/phd python projects/tensorflow_img_class/src/tensorflow_img_class.py", line 35, in feature_extractor
    feature_extractor_module = hub.Module(feature_extractor_url)
NameError: name 'feature_extractor_url' is not defined

More details are on this question. I have opened this post by following a suggestion from my previous linked post.

Code for this model is

image_generator = tf.compat.v1.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)
data_root = tf.compat.v1.keras.utils.get_file('Annotated_Image_Classes', 'https://github.com/PawanKaur/Viz-Image-Classification/tree/master/Annotated%20Image%20Classes.tqz',
                                              untar=True)  
feature_extractor_url = "https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/2" 

def feature_extractor(x):
  feature_extractor_module = hub.Module(feature_extractor_url)
  return feature_extractor_module(x)
IMAGE_SIZE = hub.get_expected_image_size(hub.Module(feature_extractor_url))

image_data = image_generator.flow_from_directory(str(data_root), target_size=IMAGE_SIZE)
for image_batch,label_batch in image_data:
  print("Image batch shape: ", image_batch.shape)
  print("Label batch shape: ", label_batch.shape)
  break

features_extractor_layer = layers.Lambda(feature_extractor, input_shape=IMAGE_SIZE+[3])
features_extractor_layer.trainable = False

model = tf.keras.Sequential([
  features_extractor_layer,
  layers.Dense(image_data.num_classes, activation='softmax')
])
model.summary()

sess = tf.compat.v1.keras.backend.get_session()
init = tf.compat.v1.global_variables_initializer()  
sess.run(init)

result = model.predict(image_batch)
result.shape
model.compile(
  optimizer=tf.train.AdamOptimizer(), 
  loss='categorical_crossentropy',
  metrics=['accuracy'])

class CollectBatchStats(tf.keras.callbacks.Callback):
  def __init__(self):
    self.batch_losses = []
    self.batch_acc = []

  def on_batch_end(self, batch, logs=None):
    self.batch_losses.append(logs['loss'])
    self.batch_acc.append(logs['acc'])

steps_per_epoch = image_data.samples//image_data.batch_size
batch_stats = CollectBatchStats()
model.fit((item for item in image_data), epochs=18, 
                    steps_per_epoch=steps_per_epoch,
                    callbacks = [batch_stats])    
model.save('my_model.h5')

Basically I have created this model by following transfer learning instructions from here. I am modelling this to run on my image data. After that I just need to open and view this pre-trained and saved model in another program but so far I am unable to do so. Any help will be appreciable.

0 Answers