在将我们的机器学习项目加载到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(...)
希望这对你有帮助 🙂