将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的路由控制会简单很多,它的本质就 ...
随机推荐
- 单机器启动多个tomcat的配置修改
首先去apache下载一个tomcat,下载解压版的,比较方便 把这个tomcat(我下载的是tomcat7版本),解压两次,为了方便显示,我把解压出来的tomcat重命名成tomcat71和to ...
- JS拖拽事件
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- js 的正则表达式 部分展示test()方法的验证功能
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- 玩转JavaScript module pattern精髓
JavaScript module pattern是一种常见的javascript编码模式.这种模式本身很好理解,但是有很多高级用法还没有得到大家的注意.本文,我们将回顾这种设计模式,并且介绍一些高级 ...
- 热词统计以及Quartz.net的简单使用
一.热词统计 方案一: 设计一个表:ID KeyWord Count 当用户再输入框中查询的时候,我们就往表中插入数据,在插入之前首先判断是否已经存在keyword,存在的话,让C ...
- Eclipse Tomcat插件的使用
目录 Eclipse Tomcat插件的使用 Eclipse Tomcat插件的使用 我使用的Eclipse版本是:4.6.3 Eclipse已经自带Tomcat插件,不需要再自己进行安装 1.新建T ...
- pandas的replace方法
就是将一个值替换为另一个值,以前我用的是赋值方式,这里应该效率会高. 1.说明: 语法:replace(self, to_replace=None, value=None, inplace=False ...
- Android-aidl, binder,surfaceview
http://blog.csdn.net/stonecao/article/details/6425019 http://www.cnblogs.com/linucos/archive/2012/05 ...
- php引用(&)详解及注意事项——引用返回function &a();&a()
http://www.cnblogs.com/xiaochaohuashengmi/archive/2011/09/10/2173092.html 函数的引用返回 先看代码 <?php func ...
- 数据库们~MySQL~MongoDB~Redis
mysql基础 mysql进阶 python操作mysql MongoDB Redis

