无法加载keras训练模型

问题描述 投票:0回答:2

我正在使用以下代码来训练HAN网络。 Code Link

我成功地训练了模型,但是当我尝试使用keras load_model加载模型时,它会给出以下错误 - 未知层:AttentionWithContext

python keras deep-learning text-classification
2个回答
0
投票

在AttentionWithContext.py文件中添加以下函数:

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}

加载模型时:

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

0
投票

根据您共享的链接,您的模型已将明确定义的图层AttentionWithContext()添加到模型中。当您尝试使用keras的load_model加载模型时,该方法显示错误,因为此层不是内置于keras中并且要解决此问题,您可能必须在使用load_model加载模型之前在代码中再次定义该层。在尝试加载模型之前,请尝试在提供的链接(https://www.kaggle.com/hsankesara/news-classification-using-han/notebook)中编写类AttentionWithContext(图层)。

© www.soinside.com 2019 - 2024. All rights reserved.