[Keras] ValueError: Tensor Tensor is not an element of this graph.[Solved]

本文介绍了解决在使用Flask部署Keras模型时遇到的ValueError问题的方法,该问题出现在尝试加载模型权重时。通过使用gevent启动服务可以有效避免此错误。

自己使用load_weights函数加载预测时正常,但利用用flask使用model.load_weights函数加载keras模型进行预测时,出现的ValueError: Tensor Tensor(“loss/mul:0”, shape=(), dtype=float32) is not an element of this graph.的错误。

采用gevent启动服务:

from gevent.pywsgi import WSGIServer
    ## flask server
    # app.debug=True
    # app.run(host='0.0.0.0')
    ## Serve the app with gevent
    http_server = WSGIServer(('',5000),app)
    http_server.serve_forever()

即可解决!

参考
在使用 Keras 进行模型反序列化时,如果遇到 `ValueError: Could not deserialize 'keras.metrics.mse' because it is not a KerasSaveable subclass` 错误,通常是因为尝试从模型配置中反序列化一个未被正确注册的自定义对象(如自定义指标或损失函数)。Keras 在反序列化过程中需要明确知道如何重建这些对象。 在 Keras 中,自定义的损失函数、指标或层在保存模型后,若要成功反序列化,必须通过 `custom_objects` 参数注册。例如,如果你在模型中使用了自定义的均方误差(MSE)指标,但在加载模型时没有提供相应的定义,就会触发该错误。解决方法是在调用 `keras.models.load_model` 时,提供一个包含自定义对象的字典,如下所示: ```python from tensorflow.keras.models import load_model from tensorflow.keras import metrics # 假设你使用了自定义的 MSE 指标 custom_metrics = {'mse': metrics.mse} # 加载模型时指定 custom_objects model = load_model('your_model.h5', custom_objects=custom_metrics) ``` 如果你在模型中使用了更复杂的自定义指标或损失函数,确保它们被正确地定义为可序列化的 Keras 对象。例如,定义一个自定义指标类并继承 `tf.keras.metrics.Metric`,然后在反序列化时注册它: ```python from tensorflow.keras import metrics class CustomMSE(metrics.Metric): def __init__(self, name='custom_mse', **kwargs): super(CustomMSE, self).__init__(name=name, **kwargs) self.total = self.add_weight(name='total', initializer='zeros') self.count = self.add_weight(name='count', initializer='zeros') def update_state(self, y_true, y_pred, sample_weight=None): values = tf.reduce_mean(tf.square(y_true - y_pred), axis=-1) self.total.assign_add(tf.reduce_sum(values)) self.count.assign_add(tf.cast(tf.size(values), tf.float32)) def result(self): return tf.math.divide_no_nan(self.total, self.count) def reset_states(self): self.total.assign(0.0) self.count.assign(0.0) # 注册自定义指标 custom_metrics = {'CustomMSE': CustomMSE} # 加载模型时指定 custom_objects model = load_model('your_model.h5', custom_objects=custom_metrics) ``` 此外,如果你在模型中使用了自定义的损失函数或层,也需要以类似的方式进行注册。Keras 要求这些对象必须是 `tf.keras.layers.Layer` 或 `tf.keras.metrics.Metric` 的子类,并且实现 `get_config()` 方法,以便能够正确地序列化和反序列化[^4]。 ### 总结 - **问题原因**:Keras 无法反序列化未注册的自定义对象。 - **解决方案**:在加载模型时,通过 `custom_objects` 参数提供自定义指标、损失函数或层的定义。 - **最佳实践**:确保所有自定义对象都继承自 `tf.keras.metrics.Metric` 或 `tf.keras.layers.Layer`,并实现 `get_config()` 方法。 ---
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值