I am running the following example:
https://keras.io/examples/nlp/text_classification_with_transformer/
I have created and trained a model as described, and it works nicely:
inputs = layers.Input(shape=(maxlen,))
embedding_layer = TokenAndPositionEmbedding(maxlen, vocab_size, embed_dim)
x = embedding_layer(inputs)
transformer_block = TransformerBlock(embed_dim, num_heads, ff_dim)
x = transformer_block(x,training=True)
x = layers.GlobalAveragePooling1D()(x)
x = layers.Dropout(0.1)(x)
x = layers.Dense(20, activation="relu")(x)
x = layers.Dropout(0.1)(x)
outputs = layers.Dense(2, activation="softmax")(x)
model = keras.Model(inputs=inputs, outputs=outputs)
"""
## Train and Evaluate
"""
model.compile("adam", "sparse_categorical_crossentropy", metrics=["accuracy"])
history = model.fit(
x_train, y_train, batch_size=1024, epochs=1, validation_data=(x_val, y_val)
)
model.save('SPAM.h5')
How to save and load such custom model correctly in Keras?
I have tried
best_model=tf.keras.models.load_model('SPAM.h5')
ValueError: Unknown layer: TokenAndPositionEmbedding
but the model seems to miss the custom Layers. However the following also does not work
best_model=tf.keras.models.load_model('SPAM.h5',custom_objects={"TokenAndPositionEmbedding": TokenAndPositionEmbedding()})
TypeError: __init__() missing 3 required positional arguments:
'maxlen', 'vocab_size', and 'embed_dim'
also passing the class does not solve.
best_model=tf.keras.models.load_model('SPAM.h5',
custom_objects={"TokenAndPositionEmbedding": TokenAndPositionEmbedding})
TypeError: __init__() got an unexpected keyword argument 'name'
best_model=tf.keras.models.load_model('SPAM.h5',
{"TokenAndPositionEmbedding":
TokenAndPositionEmbedding,'TransformerBlock':TransformerBlock,
'MultiHeadSelfAttention':MultiHeadSelfAttention})