在Django中加载机器学习项目时遇到Value Error Tensorflow

在将我们的机器学习项目加载到Django服务器时,我们遇到了以下错误:

Traceback (most recent call last): File “/home/akhil/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py”, line 34, in inner response = get_response(request) File “/home/akhil/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py”, line 126, in _get_response response = self.process_exception_by_middleware(e, request) File “/home/akhil/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py”, line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File “/home/akhil/tocoblo/msg/views.py”, line 6, in index a=fuctioncall.show() File “/home/akhil/tocoblo/msg/fuctioncall.py”, line 6, in show a=Loadmodel.predict_string() File “/home/akhil/tocoblo/msg/Loadmodel.py”, line 69, in predict_string b=loaded_model.predict(y) File “/home/akhil/anaconda3/lib/python3.6/site-packages/keras/engine/training.py”, line 1164, in predict self._make_predict_function() File “/home/akhil/anaconda3/lib/python3.6/site-packages/keras/engine/training.py”, line 554, in _make_predict_function **kwargs) File “/home/akhil/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py”, line 2744, in function return Function(inputs, outputs, updates=updates, **kwargs) File “/home/akhil/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py”, line 2546, in init with tf.control_dependencies(self.outputs): File “/home/akhil/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py”, line 5002, in control_dependencies return get_default_graph().control_dependencies(control_inputs) File “/home/akhil/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py”, line 4541, in control_dependencies c = self.as_graph_element(c) File “/home/akhil/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py”, line 3488, in as_graph_element return self._as_graph_element_locked(obj, allow_tensor, allow_operation) File “/home/akhil/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py”, line 3567, in _as_graph_element_locked raise ValueError(“Tensor %s is not an element of this graph.” % obj) ValueError: Tensor Tensor(“dense_4/Sigmoid:0”, shape=(?, 6), dtype=float32) is not an element of this graph.

加载的代码是Loadmodel.py:

import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport osimport sys  import gzipimport kerasimport sysimport picklefrom sklearn.model_selection import train_test_splitfrom keras.preprocessing.text import Tokenizerfrom keras.preprocessing.sequence import pad_sequencesfrom keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activationfrom keras.layers import Bidirectional, GlobalMaxPool1Dfrom keras.models import Model, Sequentialfrom keras import initializers, regularizers, constraints, optimizers, layersfrom keras.callbacks import ModelCheckpointfrom keras.models import Sequentialfrom keras.layers import Densefrom keras.models import model_from_jsonimport numpyimport osos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'import jsonfrom pprint import pprintjson_file = open('msg/model.json', 'r')loaded_model_json = json_file.read()json_file.close()loaded_model = model_from_json(loaded_model_json)loaded_model.load_weights("msg/model.h5")print("Loaded model from disk")pickle_in = open("msg/dict.pickle","rb")#pickle_in.encoding = 'latin1'tokenizer = pickle.load(pickle_in, encoding='latin1') #tokenizer = pickle.load(pickle_in)with open('msg/data.json') as f:    data = json.load(f)def predict_string():        maxlen=200    string=""    for j in range(0,120):        flag=0        s=(data["maps"][j]["comment"],)        x=tokenizer.texts_to_sequences(s)        y=pad_sequences(x,maxlen=maxlen)        b=loaded_model.predict(y)        for i in range(0,6):            if(b[0][i]>=0.3):                flag=1        cnt=0        if(flag==1):            for i in range(0,6):                if(b[0][i]>0.3):                    cnt=cnt+1        flag=cnt        string=string+str(flag)    return string`fuctioncall.py    from . import Loadmodelfrom django.http import HttpResponse, JsonResponsedef show():    a=Loadmodel.predict_string()    return ("GOT"+a);

urls.py:

from django.urls import pathfrom . import viewsfrom . import fuctioncallurlpatterns = [    path('', views.index, name='index'),    path('<str:com>', views.com, name='com'),]

如何解决这个错误?我还想知道如何在Django服务器中加载机器学习项目并调用它?


回答:

在导入语句之后,添加以下两行代码:

global graphgraph = tf.get_default_graph()

然后,每次你试图在模型上运行推理时,使用以下代码:

with graph.as_default():        prediction = mode.predict(...)

希望这对你有帮助 🙂

Related Posts

如何对SVC进行超参数调优?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

如何在初始训练后向模型添加训练数据?

我想在我的scikit-learn模型已经训练完成后再…

使用Google Cloud Function并行运行带有不同用户参数的相同训练作业

我正在寻找一种方法来并行运行带有不同用户参数的相同训练…

加载Keras模型,TypeError: ‘module’ object is not callable

我已经在StackOverflow上搜索并阅读了文档,…

在计算KNN填补方法中特定列中NaN值的”距离平均值”时

当我从头开始实现KNN填补方法来处理缺失数据时,我遇到…

使用巨大的S3 CSV文件或直接从预处理的关系型或NoSQL数据库获取数据的机器学习训练/测试工作

已关闭。此问题需要更多细节或更清晰的说明。目前不接受回…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注