0
votes

While loading our machine learning project into a Django server we got following error:

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.

The Loaded code is 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'),
]

How do I solve this error? Also how do I load the machine learning project in the Django server and call it?

1

1 Answers

0
votes

Just after the imports, add the following 2 lines:

global graph
graph = tf.get_default_graph()

Then whenever you try to run inference on the model, use:

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

Hope it helps :)