在将机器学习项目加载到Django服务器中时,出现以下错误:
回溯(最近通话最近):文件 “ /home/akhil/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py”, 第34行,在内部 response = get_response(request)文件“ /home/akhil/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py”, _get_response中的第126行 响应= self.process_exception_by_middleware(e,request)文件“ /home/akhil/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py”, _get_response中的第124行 响应= wraped_callback(request,* callback_args,** callback_kwargs)文件“ /home/akhil/tocoblo/msg/views.py”,索引中的第6行 a = fuctioncall.show()显示文件“ /home/akhil/tocoblo/msg/fuctioncall.py”,第6行 a = Loadmodel.predict_string()文件“ /home/akhil/tocoblo/msg/Loadmodel.py”,行69,在predict_string中 b = loaded_model.predict(y)文件“ /home/akhil/anaconda3/lib/python3.6/site-packages/keras/engine/training.py”, 行1164,在预测中 self._make_predict_function()文件“ /home/akhil/anaconda3/lib/python3.6/site-packages/keras/engine/training.py”, _make_predict_function中的第554行 ** kwargs)文件“ /home/akhil/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py”, 2744行,功能正常 返回函数(输入,输出,更新=更新,** kwargs)文件“ /home/akhil/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py”, 第2546行,在 init 中 与tf.control_dependencies(self.outputs):文件“ /home/akhil/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py”, 第5002行,在control_dependencies中 返回get_default_graph()。control_dependencies(control_inputs)文件 “ /home/akhil/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py”, 行4541,在control_dependencies中 c = self.as_graph_element(c)文件“ /home/akhil/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py”, 第3488行,位于as_graph_element中 返回self._as_graph_element_locked(obj,allow_tensor,allow_operation)文件 “ /home/akhil/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py”, 第3567行,在_as_graph_element_locked中 引发ValueError(“ Tensor%s不是此图的元素。”%obj)ValueError:张量Tensor(“ dense_4 / Sigmoid:0”,shape =(?, 6), dtype = float32)不是该图的元素。
已加载的代码为Loadmodel.py:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import sys
import gzip
import keras
import sys
import pickle
from sklearn.model_selection import train_test_split
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation
from keras.layers import Bidirectional, GlobalMaxPool1D
from keras.models import Model, Sequential
from keras import initializers, regularizers, constraints, optimizers, layers
from keras.callbacks import ModelCheckpoint
from keras.models import Sequential
from keras.layers import Dense
from keras.models import model_from_json
import numpy
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import json
from pprint import pprint
json_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 Loadmodel
from django.http import HttpResponse, JsonResponse
def show():
a=Loadmodel.predict_string()
return ("GOT"+a);
urls.py:
from django.urls import path
from . import views
from . import fuctioncall
urlpatterns = [
path('', views.index, name='index'),
path('<str:com>', views.com, name='com'),
]
如何解决此错误?另外,如何在Django服务器中加载机器学习项目并调用它?
答案 0 :(得分:0)
在导入之后,添加以下两行:
global graph
graph = tf.get_default_graph()
然后,每当您尝试对模型进行推理时,请使用:
with graph.as_default():
prediction = mode.predict(...)
希望它会有所帮助:)