本人在写Django RESful API时,碰到一个难题,老出现,整合Keras,报如下错误;很纠结,探索找资料近一个星期,皇天不负有心人,解决了

Internal Server Error: /pic/analysis/
Traceback (most recent call last):
File "D:\AI\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1064, in _run
allow_operation=False)
File "D:\AI\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 3035, in as_graph_element
return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
File "D:\AI\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 3114, in _as_graph_element_locked
raise ValueError("Tensor %s is not an element of this graph." % obj)
ValueError: Tensor Tensor("Placeholder:0", shape=(3, 3, 1, 32), dtype=float32) is not an element of this graph. During handling of the above exception, another exception occurred: Traceback (most recent call last):
File "D:\AI\Python35\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "D:\AI\Python35\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\AI\Python35\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\AI\Python35\lib\site-packages\django\test\utils.py", line 371, in inner
return func(*args, **kwargs)
File "E:\PyCharmWork\PythonWebApp\ApiPicDjangoSite\PicWeb\views.py", line 25, in picAnalysis
predictBank(im, name) #对图片进行预测,并返回预测结果
File "E:\PyCharmWork\PythonWebApp\ApiPicDjangoSite\PicWeb\PreDictBankFunc.py", line 42, in predictBank
model = load_model('static\CnnBankUp.h5', compile=False)
File "D:\AI\Python35\lib\site-packages\keras\models.py", line 243, in load_model
topology.load_weights_from_hdf5_group(f['model_weights'], model.layers)
File "D:\AI\Python35\lib\site-packages\keras\engine\topology.py", line 3142, in load_weights_from_hdf5_group
K.batch_set_value(weight_value_tuples)
File "D:\AI\Python35\lib\site-packages\keras\backend\tensorflow_backend.py", line 2247, in batch_set_value
get_session().run(assign_ops, feed_dict=feed_dict)
File "D:\AI\Python35\lib\site-packages\tensorflow\python\client\session.py", line 889, in run
run_metadata_ptr)
File "D:\AI\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1067, in _run
+ e.args[0])
TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(3, 3, 1, 32), dtype=float32) is not an element of t
his graph.
[08/Jan/2018 08:53:15] "POST /pic/analysis/ HTTP/1.1" 500 159200

个人理解:在初始化Django时,把keras中 model先初始化,免得后面不断调用,产生莫名其妙的问题

Django初始化代码写在__init__.py中:

from keras.models import load_model
import numpy as np #参考:https://zhuanlan.zhihu.com/p/27101000 print('load model...')
model = load_model('static\\CnnBankUp.h5', compile=False)
print('load done.') #一定要添加这段代码,先测试一下,可以避免ValueError: Tensor Tensor("Placeholder:0", shape=(3, 3, 1, 32), dtype=float32)
#is not an element of this graph.的错误
print('test model...')
#根据自己传入图片格式定义np.zeros()
print(model.predict(np.zeros((2, 200,200,1))))
print('test done.') # 使用模型,在得到用户输入时会调用以下两个函数进行实时文本分类
# 输入参数 comment 为经过了分词与向量化处理后的模型输入
def picType_class(comment):
global model
result_vec=None
result_vec = model.predict(comment)
return result_vec

很有用的参考,非常感谢

参考:https://zhuanlan.zhihu.com/p/27101000

Django整合Keras报错:ValueError: Tensor Tensor("Placeholder:0", shape=(3, 3, 1, 32), dtype=float32) is not an element of this graph.解决方法的更多相关文章

  1. 将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模型在django中应用时出现的小问题 王岳王院长 10 个月前 keras 一个做 ...

  2. keras 报错 ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: 'Tensor("embedding_1/random_uniform:0", shape=(5001, 128), dtype=float32)'

    在服务器上训练并保存模型,复制到本地之后load_model()报错: ValueError: Tensor conversion requested dtype int32 for Tensor w ...

  3. memcached解压报错gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now的解决方法

    最近在部署环境,在安装memcached的过程中解压时, 解压命令:tar -zvxf memcached-1.4.34.tar.gz 遇到了一个问题, gzip: stdin: not in gzi ...

  4. 解压报错gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now的解决方法

    在部署tomcat的环境搞JDK的时候出现这个问题.分享一下. 解压命令:tar -zvxf memcached-1.4.34.tar.gz 遇到了一个问题, gzip: stdin: not in ...

  5. Django序列化时间报错

    一.前言 当利用models模块从数据库获取数据时,当获的取数据序列化时,如果获取的数据中有关于时间类型的字段,则会报错,错误如下: TypeError: datetime.datetime(2018 ...

  6. spring+hibernate整合:报错org.hibernate.HibernateException: No Session found for current thread

    spring+hibernate整合:报错信息如下 org.hibernate.HibernateException: No Session found for current thread at o ...

  7. weblogic 整合cxf 报错:cannot create a secure XmlInputFactory

    weblogic 整合cxf 报错:cannot create a secure XmlInputFactory ================================ ©Copyright ...

  8. django startproject xxx:报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 13: ordinal not in range(128)

    django startproject xxx:报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 13: o ...

  9. matplotlib.pyplot import报错: ValueError: _getfullpathname: embedded null character in path

    Environment: Windows 10, Anaconda 3.6 matplotlib 2.0 import matplotlib.pyplot 报错: ValueError: _getfu ...

随机推荐

  1. 跨iOS SDK版本编译问题

    iOS开发时会考虑两种SDK版本兼容性:一个是运行时SDK版本的兼容,即已构建/已发布的APP能在不同系统版本的用户手机上正常运行:一个是编译时SDK版本的兼容,即使用不同版本的SDK编译项目都能正常 ...

  2. mysql用户权限分配专栏

    00x1创建新用户 通过root用户登录之后创建 创建新用户,用户名为testuser,密码为123456 : 1 grant all privileges on *.* to testuser@lo ...

  3. HDU - 3002 King of Destruction(最小割)

    http://acm.hdu.edu.cn/showproblem.php?pid=3002   最小割模板 #include<iostream> #include<cmath> ...

  4. JavaScript 无刷新修改浏览器URL地址栏

    //发现地址栏已改为:newUrlvar stateObject = {}; var title = "Wow Title"; var newUrl = "/my/awe ...

  5. Syncfusion HTMLUI研究一

    HTMLUI可以加载HTML页面,并且相比WebKit等占用资源特别少 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitiona ...

  6. 解决virtualbox与mac文件拖拽问题

    apt-get purge virtualbox-guest-x11apt-get autoremove --purgerebootapt-get updateapt-get dist-upgrade ...

  7. Tukey‘s test方法 异常值

    如何计算异常值 异常值就是和其他样本数据有显著差异的值.这个词在统计学中经常用到,可以表示数据异常或测量错误.明白算异常值的方法,对于正确理解数据非常有用,而且会引出更精确的结论.以下介绍一个很简单的 ...

  8. Linux - find 查找

    # linux文件无创建时间 # Access 使用时间 # Modify 内容修改时间 # Change 状态改变时间(权限.属主) # 时间默认以24小时为单位,当前时间到向前24小时为0天,向前 ...

  9. Java SE之正则表达式Demo

    @Test public void regex() {//匹配教务系统课程 // String content = "公共机座 (1-10)".replaceAll(" ...

  10. JavaSE之Math类

    下列哪个选项是正确计算42度(角度)的余弦值? double d=Math.cos(42) double d=Math.cosine(42) double d=Math.cos(Math.toRadi ...