You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask项目加载Keras模型遇Lambda层反序列化错误,safe_mode设置无效

解决Keras model_from_json加载含Lambda层模型时的safe_mode无效问题

你遇到的问题核心是把safe_mode=False放错了位置——它不是custom_objects字典里的键,而是model_from_json函数的独立参数。原来的写法里Keras根本没读到这个配置,所以还是会触发安全校验错误。

修正后的代码

把safe_mode=False从custom_objects里拿出来,作为model_from_json的直接参数传入:

class ImagenetClassifier(object):
    def __init__(self):
        print('LOAD MODEL ...')
        with open('../Resource/line_model_predict.json', 'r') as f:
            # 把safe_mode作为独立参数传入,而非custom_objects的键
            self.l_model_predict = model_from_json(f.read(), safe_mode=False)
        self.l_model_predict.load_weights('../Resource/iam_lines--12--17.373.h5')
        with open('../Resource/word_model_predict.json', 'r') as f:
            self.w_model_predict = model_from_json(f.read(), safe_mode=False)
        self.w_model_predict.load_weights('../Resource/iam_words--15--1.791.h5')
    def predict_image(self, image_filename):
        try:
            with graph.as_default():
                pred_text_model_word, pred_text_model_line = predict(self.w_model_predict, self.l_model_predict, image_filename)
            return pred_text_model_word, pred_text_model_line
        except Exception as err:
            print('Prediction error: ', err)
            return (False, 'Something went wrong when predict the '
                           'image. Maybe try another one?')

为什么原来的写法没用?

Keras的model_from_json函数定义中,safe_mode是单独的关键字参数,专门用来控制是否允许反序列化包含lambda表达式的Lambda层。而custom_objects是用来注册自定义层、损失函数等自定义组件的,两者完全是不同的参数,不能混在一起传。

内容的提问来源于stack exchange,提问作者SAli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:45:03