无法加载keras训练的mod

2024-10-03 21:34:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我用下面的代码来训练汉网络。 Code Link

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


Tags: 代码模型网络错误linkcodeloadkeras
2条回答

在中添加以下函数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}

加载模型时:

^{pr2}$

根据您共享的链接,您的模型有一个显式定义的层AttentionWithContext()添加到模型中。当您尝试使用keras的load_模型加载模型时,该方法显示错误,因为此层不是内置于keras中的,要解决此问题,您可能需要在代码中重新定义该层,然后再使用load_model加载模型。在尝试加载模型之前,请尝试在您提供的链接(https://www.kaggle.com/hsankesara/news-classification-using-han/notebook)中编写类AttentionWithContext(层)。在

相关问题 更多 >