Not able to load keras trained model

余生长醉 提交于 2019-12-11 19:45:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!