问题
I am using following code to train HAN Network. Code Link
I have trained the model successfully but when I tried to load the model using keras load_model it gives me following error- Unknown layer: AttentionWithContext
回答1:
Add the following function in the AttentionWithContext.py file:
def create_custom_objects():
instance_holder = {"instance": None}
class ClassWrapper(AttentionWithContext):
def __init__(self, *args, **kwargs):
instance_holder["instance"] = self
super(ClassWrapper, self).__init__(*args, **kwargs)
def loss(*args):
method = getattr(instance_holder["instance"], "loss_function")
return method(*args)
def accuracy(*args):
method = getattr(instance_holder["instance"], "accuracy")
return method(*args)
return {"ClassWrapper": ClassWrapper ,"AttentionWithContext": ClassWrapper, "loss": loss,
"accuracy":accuracy}
When loading the model:
from AttentionWithContext import create_custom_objects
model = keras.models.load_model(model_path, custom_objects=create_custom_objects())
model.evaluate(X_test, y_test) # or model.predict
回答2:
According to the link that you have shared, your model has an explicitly defined layer AttentionWithContext() added to the model. When you are trying to load the model using keras' load_model, the method shows error because this layer is not in-built in keras and to solve this you might have to define that layer again in your code before loading the model using load_model. Please try to write the class AttentionWithContext(layer) as it is in your provided link (https://www.kaggle.com/hsankesara/news-classification-using-han/notebook) before trying to load the model.
来源:https://stackoverflow.com/questions/55218234/not-able-to-load-keras-trained-model