5

I would like to use the trained model described in Keras's Handwriting recognition Example, in another application and tried to load the model with the following;

from keras.models import load_model
from tensorflow import keras

model = keras.models.load_model("test4_20211113.h5", custom_objects={'CTCLayer': CTCLayer}) 

I received "ValueError: Unknown layer: Custom>CTCLayer. Please ensure this object is passed to the custom_objects argument."

I added the custom_objects argument and modified the CTCLayer class by adding **kwargs following this article, "ValueError: Unknown layer: CapsuleLayer".

class CTCLayer(keras.layers.Layer):
    def __init__(self, name=None, **kwargs):
        self.name = name
        super().__init__(**kwargs)
        self.loss_fn = keras.backend.ctc_batch_cost

    def call(self, y_true, y_pred):
        batch_len = tf.cast(tf.shape(y_true)[0], dtype="int64")
        input_length = tf.cast(tf.shape(y_pred)[1], dtype="int64")
        label_length = tf.cast(tf.shape(y_true)[1], dtype="int64")

        input_length = input_length * \
            tf.ones(shape=(batch_len, 1), dtype="int64")
        label_length = label_length * \
            tf.ones(shape=(batch_len, 1), dtype="int64")
        loss = self.loss_fn(y_true, y_pred, input_length, label_length)
        self.add_loss(loss)

        # At test time, just return the computed predictions.
        return y_pred

I'm a beginner in both Python and Keras, and greatly appreciate it if you let me know how to fix this.

Hiroji
  • 51
  • 2
  • Hi @Hiroji! Did you try with the custom_object_scope too? https://stackoverflow.com/a/50838031/11530462 –  Apr 13 '22 at 03:16

1 Answers1

1

In order to load, one needs first save a model (most likely after model.fit):

model.fit(args)

model.save(pathToYourFile, save_format="h5")

Then one is able to load the model with keras.models.load_model method. Usually it is not an issue. But if you develop a custom layer, you need to pass a specific reference to it/ them into custom_objects property, like this

keras.models.load_model(pathToModel, custom_objects={
  'CTCLayer': CTCLayer
})

My environment:

  • python: '3.10.8'
  • sys.version: '3.10.8 (main, Nov 24 2022, 08:09:04) [Clang 14.0.6 ]
  • tensorFlowVersion: '2.11.0'
Roman
  • 19,236
  • 15
  • 93
  • 97