Keras多线程机制与flask多线程冲突的解决方案


Posted in Python onMay 28, 2021

在使用flask部署Keras,tensorflow等框架时候,经常出现

FailedPreconditionError: Attempting to use uninitialized value batchnormalization_

或者

Tensor Tensor("crf_1/cond/Merge:0", shape=(?, ?, 260), dtype=float32) is not an element of this graph.

使用keras.backend.clear_session()可能会导致前后两处预测结果不一样,因为图发生了变化。以下是解决方案。

graph = tf.get_default_graph()
sess = tf.Session(graph=graph) 
 
def modelpredict(content):
    #keras.backend.clear_session()
    global graph
    global sess
    with sess.as_default():
        with graph.as_default():
            keras.model.predict()

补充:Flask与keras结合的几个常见错误

1、 ValueError: Tensor Tensor(“dense_1/Sigmoid:0”, shape=(?, 1), dtype=float32) is not an element of this graph.

在Flask中使用tensorflow的model,一在界面中调用 model.predict() 就报下面这个错误,不过在单独的 .py 文件中使用却不报错。

ValueError: Tensor Tensor("dense_1/Sigmoid:0", shape=(?, 1), dtype=float32) is not an element of this graph.

添加如下代码可以解决:

import tensorflow as tf
graph = tf.get_default_graph()
model = models.load_model(…………)

# 使用处添加:
global graph
global model
with graph.as_default():
    model.predict()
    # 执行预测函数

但是我当时测试时又报了另一个bug,但是这个bug也不好解决,试了很多方法也没解决,当然最终还是可以解决的,具体解决方式参考第三点。

tensorflow.python.framework.errors_impl.FailedPreconditionError: Error while reading resource variable dense_1/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource localhost/dense_1/bias/class tensorflow::Var does not exist.
[[{{node dense_1/BiasAdd/ReadVariableOp}}]]

后来经过N遍测试后找到了以下两种解决方式,仅供参考:

方法一:

在调用前加载model和graph,但是这样会导致程序每次调用都需要重新加载model,然后运行速度就会很慢,不过这种修改方式是最简单的。

graph = tf.get_default_graph()
    model = models.load_model('./static/my_model2.h5')
    with graph.as_default():
        result = model.predict(tokens_pad)

方法二:

在创建model后,先使用一遍 model.predict(),参数的大小和真实大小一致,这个是真正解决之道,同时不影响使用速率。

# 使用前:
model = models.load_model('./static/my_model2.h5')
# a 矩阵大小和 tokens_pad 一致
a = np.ones((1, 220))
model.predict(a)

# 使用时:
global model
result = model.predict(tokens_pad)

但是在使用后又遇到了 The Session graph is empty…… 的错误即第二点,不过估摸着这个是个例,应该是程序问题。

2、RuntimeError: The Session graph is empty. Add operations to the graph before calling run().

graph = tf.get_default_graph()
    with graph.as_default():
        # 相关代码
        # 本次测试中是需要把调用包含model.predict()方法的方法的代码放到这里

3、tensorflow.python.framework.errors_impl.FailedPreconditionError: Error while reading resource variable dense_1/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource localhost/dense_1/bias/class tensorflow::Var does not exist.[[{{node dense_1/BiasAdd/ReadVariableOp}}]]

这个错误呢,也是TensorFlow和Flask结合使用时的常见错误,解决方式如下:

from tensorflow.python.keras.backend import set_session
# 程序开始时声明
sess = tf.Session()
graph = tf.get_default_graph()

# 在model加载前添加set_session
set_session(sess)
model = models.load_model(…………)

# 每次使用有关TensorFlow的请求时
# in each request (i.e. in each thread):
global sess
global graph
with graph.as_default():
    set_session(sess)
    model.predict(...)
————————————————

4、 Can't find libdevice directory ${CUDA_DIR}/nvvm/libdevice. This may result in compilation or runtime failures, if the program we try to run uses routines from libdevice

设置一下XLA_FLAGS指向你的cuda安装目录即可

os.environ["XLA_FLAGS"]="--xla_gpu_cuda_data_dir=/usr/local/cuda-10.0"

以上为个人经验,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
easy_install python包安装管理工具介绍
Feb 10 Python
Python中tell()方法的使用详解
May 24 Python
详解Django框架中的视图级缓存
Jul 23 Python
Python多进程同步简单实现代码
Apr 27 Python
Django中login_required装饰器的深入介绍
Nov 24 Python
python使用itchat库实现微信机器人(好友聊天、群聊天)
Jan 04 Python
解决安装tensorflow遇到无法卸载numpy 1.8.0rc1的问题
Jun 13 Python
python sort、sort_index方法代码实例
Mar 28 Python
python随机生成库faker库api实例详解
Nov 28 Python
python多进程下的生产者和消费者模型
May 07 Python
Python3爬虫关于识别点触点选验证码的实例讲解
Jul 30 Python
python 发送邮件的四种方法汇总
Dec 02 Python
pytorch 6 batch_train 批训练操作
May 28 #Python
pytorch 如何使用batch训练lstm网络
May 28 #Python
使用Pytorch训练two-head网络的操作
May 28 #Python
使用Python的开发框架Brownie部署以太坊智能合约
使用Pytorch实现two-head(多输出)模型的操作
8g内存用python读取10文件_面试题-python 如何读取一个大于 10G 的txt文件?
用python画城市轮播地图
You might like
PHP产生随机字符串函数
2006/12/06 PHP
PHP Directory 函数的详解
2013/03/07 PHP
PHP获取时间排除周六、周日的两个方法
2014/06/30 PHP
PHP中的traits实现代码复用使用实例
2015/05/13 PHP
php获取当前页面完整URL地址
2015/12/30 PHP
用showModalDialog弹出页面后,提交表单总是弹出一个新窗口
2009/07/18 Javascript
JQuery中根据属性或属性值获得元素(6种情况获取方法)
2013/01/17 Javascript
JavaScript中this的使用详解
2013/11/08 Javascript
javascript间隔刷新的简单实例
2013/11/14 Javascript
jquery删除指定的html标签并保留标签内文本内容的方法
2014/04/02 Javascript
AngularJs中route的使用方法和配置
2016/02/04 Javascript
关于RequireJS的简单介绍即使用方法
2016/10/20 Javascript
Bootstrap实现提示框和弹出框效果
2017/01/11 Javascript
AngularJS实时获取并显示密码的方法
2018/02/06 Javascript
js捆绑TypeScript声明文件的方法教程
2018/04/13 Javascript
Nuxt.js SSR与权限验证的实现
2018/11/21 Javascript
vue keep-alive列表页缓存 详情页返回上一页不刷新,定位到之前位置
2019/11/26 Javascript
koa-passport实现本地验证的方法示例
2020/02/20 Javascript
Python中的字典与成员运算符初步探究
2015/10/13 Python
tensorflow识别自己手写数字
2018/03/14 Python
python和shell获取文本内容的方法
2018/06/05 Python
Python使用一行代码获取上个月是几月
2018/08/30 Python
python 实现矩阵按对角线打印
2019/11/29 Python
python+appium+yaml移动端自动化测试框架实现详解
2020/11/24 Python
墨尔本照明批发商店:Mica Lighting
2017/12/28 全球购物
英国领先的互联网葡萄酒礼品商:Vintage Wine & Port
2019/05/24 全球购物
GAZMAN官网:澳大利亚领先的男装品牌
2019/12/19 全球购物
物业管理个人自我评价
2013/11/08 职场文书
教师民族团结演讲稿
2014/08/27 职场文书
受伤赔偿协议书
2014/09/24 职场文书
2014年流动人口工作总结
2014/11/26 职场文书
2014工程部年度工作总结
2014/12/17 职场文书
大学生学期个人总结
2015/02/12 职场文书
2019商业计划书格式、范文
2019/04/24 职场文书
员工工作失职检讨书范文!
2019/07/03 职场文书
php去除数组中为0的元素的实例分析
2021/11/17 PHP