将keras模型在django中应用时出现的小问题——ValueError: Tensor Tensor("dense_2/Softmax:0", shape=(?, 8), dtype=float32) is not an element of this graph.
本文原出处(感谢作者提供):https://zhuanlan.zhihu.com/p/27101000
keras
一个做深度学习的框架,可以训练深度学习的模型,这里后端使用的是 tensorflow
django
一个 python 语言的 web 框架,可以做 web 应用
问题背景
项目需求是用深度学习训练一个文本分类的模型,然后在 web 应用中加载这个训练好的模型在利用模型对实时输入的文本进行分类,这样用户在浏览器页面中输入文本,就可以立刻得到模型返回的文本分类结果
问题描述
模型有两个,一个情感分类,一个内容类别分类,用 keras 训练好了模型,用 h5 格式进行保存。再在 django 中加载这个模型,模型文件分别为 cate_class_model.h5 与 emo_class_model.h5 ,加载与使用相关的代码如下
# 加载模型,django 会在 web 应用初始化时执行这段代码
from keras.models import load_model
print 'load model...'
model_COC = load_model(sys.path[0] + '/resource/cate_class_model.h5')
model_COE = load_model(sys.path[0] + '/resource/emo_class_model.h5')
print 'load done.'
# 使用模型,在得到用户输入时会调用以下两个函数进行实时文本分类
# 输入参数 comment 为经过了分词与向量化处理后的模型输入
def category_class(comment):
global model_COC
result_vec = model_COC.predict(comment)
return result_vec
def emotion_class(comment):
global model_COE
result_vec = model_COE.predict(comment)
return result_vec
django 初始化加载模型的过程没有问题,但是一旦调用函数使用模型时执行到 model.predict 就会报错
Traceback (most recent call last):
File "/media/wave/D/workspace/LinuxPyCharm/actauto/classification/comments_class.py", line 38, in category_class
result_vec = model_COC.predict(vecs)[0]
File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 902, in predict
return self.model.predict(x, batch_size=batch_size, verbose=verbose)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1582, in predict
self._make_predict_function()
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1049, in _make_predict_function
**kwargs)
File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 2251, in function
return Function(inputs, outputs, updates=updates)
File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 2205, in __init__
with tf.control_dependencies(self.outputs):
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 3595, in control_dependencies
return get_default_graph().control_dependencies(control_inputs)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 3324, in control_dependencies
c = self.as_graph_element(c)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2414, in as_graph_element
return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2493, in _as_graph_element_locked
raise ValueError("Tensor %s is not an element of this graph." % obj)
ValueError: Tensor Tensor("dense_2/Softmax:0", shape=(?, 8), dtype=float32) is not an element of this graph.
在正常的 python 程序里运行没有问题,在 django 里将模型加载与模型使用的代码放在一起也没有问题,但是一旦将加载与使用的过程分开就会出现这个问题
解决方法
在初始化加载模型之后,就随便生成一个向量让 model 执行一次 predict 函数,之后再使用就不会有问题了
# 加载模型,django 会在 web 应用初始化时执行这段代码
from keras.models import load_model
print 'load model...'
model_COC = load_model(sys.path[0] + '/resource/cate_class_model.h5')
model_COE = load_model(sys.path[0] + '/resource/emo_class_model.h5')
print 'load done.'
# load 进来模型紧接着就执行一次 predict 函数
print 'test model...'
print model_COC.predict(np.zeros((1, len(word_index)+1)))
print model_COE.predict(np.zeros((1, len(word_index)+1)))
print 'test done.'
# 使用模型,在得到用户输入时会调用以下两个函数进行实时文本分类
# 输入参数 comment 为经过了分词与向量化处理后的模型输入
def category_class(comment):
global model_COC
result_vec = model_COC.predict(comment)
return result_vec
def emotion_class(comment):
global model_COE
result_vec = model_COE.predict(comment)
return result_vec
问题原因
才疏学浅啊,原因不明,解决方法也甚是神奇,不愧机器玄学,醉了
将keras模型在django中应用时出现的小问题——ValueError: Tensor Tensor("dense_2/Softmax:0", shape=(?, 8), dtype=float32) is not an element of this graph.的更多相关文章
- Django整合Keras报错:ValueError: Tensor Tensor("Placeholder:0", shape=(3, 3, 1, 32), dtype=float32) is not an element of this graph.解决方法
本人在写Django RESful API时,碰到一个难题,老出现,整合Keras,报如下错误:很纠结,探索找资料近一个星期,皇天不负有心人,解决了 Internal Server Error: /p ...
- Django中的ORM框架使用小技巧
Django中的ORM框架使用小技巧 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. Django对各个数据提供了很好的支持,包括PostgreSQL,MySQL,SQLite ...
- 理解Django 中Call Stack 机制的小Demo
1.工作流程 request/response模式下,request并不是直接到达view方法,view方法也不是将返回的response直接发送给浏览器的,而是request由外到里的层层通过各种m ...
- 解决在django中应用keras模型时出现的ValueError("Tensor %s is not an element of this graph." % obj)问题
用keras训练好模型,再在django初始化加载模型,这个过程没有问题,但是在调用到模型执行model.predict()的时候就报错: raise ValueError("Tensor ...
- 使用Keras做OCR时报错:ValueError: Tensor Tensor is not an element of this graph
现象 项目使用 Flask + Keras + Tensorflow 同样的代码在机器A和B上都能正常运行,但在机器C上就会报如下异常.机器A和B的环境是先安装的,运行.调试成功后才尝试在C上跑. F ...
- memcached简单介绍及在django中的使用
什么是memcached? Memcached是一个高性能的分布式的内存对象缓存系统,全世界有不少公司采用这个缓存项目来构建大负载的网站,来分担数据库的压力.Memcached是通过在内存里维护一个统 ...
- celery介绍、架构、快速使用、包结构,celery执行异步、延迟、定时任务,django中使用celery,定时更新首页轮播图效果实现,数据加入redis缓存的坑及解决
今日内容概要 celery介绍,架构 celery 快速使用 celery包结构 celery执行异步任务 celery执行延迟任务 celery执行定时任务 django中使用celery 定时更新 ...
- 在django中使用Redis存取session
一.Redis的配置 1.django的缓存配置 # redis在django中的配置 CACHES = { "default": { "BACKEND": & ...
- Django中的路由配置简介
Django中的路由配置简介 路由配置(URLconf)就是Django所支撑网站的目录.其实,我们利用路由交换中的"寻址"的概念去理解Django的路由控制会简单很多,它的本质就 ...
随机推荐
- Dreamweaver 中CSS代码格式化
首先,用DW打开一个已经写好的css文件,看一下编辑好的,没有格式化之前的代码的样子. 然后,我们点击软件窗口上方的“命令”选项,在弹出的菜单中点击“应用源格式”选项,就可以将我们的代码格式化. ...
- javascript飞机大战-----006创建敌机
先写一个敌机类 /* 创建敌机: */ function Enemy(blood,speed,imgs){ //敌机left this.left = 0; //敌机top this.top = 0; ...
- CH5E07 划分大理石【多重背包】
5E07 划分大理石 0x5E「动态规划」练习描述有价值分别为1..6的大理石各a[1..6]块,现要将它们分成两部分,使得两部分价值之和相等,问是否可以实现.其中大理石的总数不超过20000. 输入 ...
- Oracle等待事件之db file sequential read/ db file parallel read
1.产生原因 db file sequential read这个是非常常见的I/O 相关的等待事件.表示发生了与索引扫描相关的等待.意味着I/O 出现了问题,通常表示I/O竞争或者I/O 需求太多. ...
- numpy基本方法总结 --good
https://www.cnblogs.com/xinchrome/p/5043480.html 一.数组方法 创建数组:arange()创建一维数组:array()创建一维或多维数组,其参数是类似于 ...
- 无题II---hdu2236(二分,匈牙利)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2236 要求最大值与最小值的差值最小,是通过枚举边的下限和上限来完成 只需要用二分找一个区间,然后不断枚 ...
- Python开发【项目】:博客后台
概述 通过自己写的博客后台代码.思路,来与武sir的代码进行一个差异化的比较,记录之间的差距,改善以后写代码的思路 博客后台这个项目,对之前Django学习的各个知识点都有涉及到,非常重要 用户登录验 ...
- Mybatis的WHERE和IF动态
mapper.xml: <!--查询套餐产品 --> <select id="queryComboProducts" resultType="com.r ...
- ubuntu update-alternatives
update-alternatives是ubuntu系统中专门维护系统命令链接符的工具,通过它可以很方便的设置系统默认使用哪个命令.哪个软件版本,比如,我们在系统中同时安装了open jdk和sun ...
- 多线程Java面试题总结
57.Thread类的sleep()方法和对象的wait()方法都可以让线程暂停执行,它们有什么区别?答:sleep()方法(休眠)是线程类(Thread)的静态方法,调用此方法会让当前线程暂停执行指 ...

