Tensorflow ValueError:Tensor Tensor(“激活”11/Softmax:0),shape=(?,5),dtype=float32)不是此图的元素

Tensorflow ValueError:Tensor Tensor(“激活”11/Softmax:0),shape=(?,5),dtype=float32)不是此图的元素,tensorflow,machine-learning,flask,keras,deep-learning,Tensorflow,Machine Learning,Flask,Keras,Deep Learning,当我在一个单独的文件中运行我的模型时,它运行得很好,但是当我使用flask代码运行我的模型时,它会给我一个错误,我不知道为什么我会面临这个问题。我尝试了StackOverflow本身的一些解决方案,即在分别加载模型和预测之后尝试添加这些行 graph=tf.get\u default\u graph() 及 全局图 使用graph.as_default(): 但是,我还是像这样tensorflow.python.framework.errors\u impl.failedPremissionEr

当我在一个单独的文件中运行我的模型时,它运行得很好,但是当我使用flask代码运行我的模型时,它会给我一个错误,我不知道为什么我会面临这个问题。我尝试了StackOverflow本身的一些解决方案,即在分别加载模型和预测之后尝试添加这些行

graph=tf.get\u default\u graph()

全局图
使用graph.as_default():

但是,我还是像这样
tensorflow.python.framework.errors\u impl.failedPremissionError

这是我的app.py文件

# Importing ML libs
from keras.models import load_model
from time import sleep
import tensorflow as tf
from keras.preprocessing.image import img_to_array
from keras.preprocessing import image
import cv2
import numpy as np

# ML Initializations
face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
classifier =load_model('Emotion_little_vgg.h5')
global graph
graph = tf.get_default_graph() 
class_labels = ['Angry','Happy','Neutral','Sad','Surprise']

# Emotion Detection Function
def get_emotion():
    with graph.as_default():
        cap = cv2.VideoCapture(0)
        ret, frame = cap.read()
        labels = []
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        faces = face_classifier.detectMultiScale(gray,1.3,5)

        for (x,y,w,h) in faces:
            # cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
            roi_gray = gray[y:y+h,x:x+w]
            roi_gray = cv2.resize(roi_gray,(48,48),interpolation=cv2.INTER_AREA)
        # rect,face,image = face_detector(frame)


            if np.sum([roi_gray])!=0:
                roi = roi_gray.astype('float')/255.0
                roi = img_to_array(roi)
                roi = np.expand_dims(roi,axis=0)
                preds = classifier.predict(roi)[0]
                label=class_labels[preds.argmax()]
                labels.append(label)
                print(label)
                return label
                # label_position = (x,y)
                # cv2.putText(frame,label,label_position,cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)
            else:
                # cv2.putText(frame,'No Face Found',(20,60),cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)
                label = 404
                return label
        # cv2.imshow('Emotion Detector',frame)

# Flask Initializations
app = Flask(__name__)

@app.route('/', methods=['POST','GET'])
def index():
    labels = get_emotion()
    return labels[0]


if __name__== "__main__":
    app.run(debug=True)
这是我单独的机器学习文件,单独使用效果很好,但与flask结合使用时会出现问题

from keras.models import load_model
from time import sleep
from keras.preprocessing.image import img_to_array
from keras.preprocessing import image
import cv2
import numpy as np

face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
classifier =load_model('Emotion_little_vgg.h5')

class_labels = ['Angry','Happy','Neutral','Sad','Surprise']

cap = cv2.VideoCapture(0)



while True:
    # Grab a single frame of video
    ret, frame = cap.read()
    labels = []
    gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    faces = face_classifier.detectMultiScale(gray,1.3,5)

    for (x,y,w,h) in faces:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h,x:x+w]
        roi_gray = cv2.resize(roi_gray,(48,48),interpolation=cv2.INTER_AREA)
    # rect,face,image = face_detector(frame)


        if np.sum([roi_gray])!=0:
            roi = roi_gray.astype('float')/255.0
            roi = img_to_array(roi)
            roi = np.expand_dims(roi,axis=0)

        # make a prediction on the ROI, then lookup the class

            preds = classifier.predict(roi)[0]
            label=class_labels[preds.argmax()]
            label_position = (x,y)
            print(label)
            cv2.putText(frame,label,label_position,cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)
        else:
            print("No faces found")
            cv2.putText(frame,'No Face Found',(20,60),cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)

    cv2.imshow('Emotion Detector',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
这是我的全部错误信息

Traceback (most recent call last)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\MAULI\Desktop\MOM\app.py", line 55, in index
labels = get_emotion()
File "C:\Users\MAULI\Desktop\MOM\app.py", line 38, in get_emotion
preds = classifier.predict(roi)[0]
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\keras\engine\training.py", line 1456, in predict
self._make_predict_function()
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\keras\engine\training.py", line 378, in _make_predict_function
**kwargs)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\keras\backend\tensorflow_backend.py", line 3009, in function
**kwargs)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\tensorflow\python\keras\backend.py", line 3201, in function
return GraphExecutionFunction(inputs, outputs, updates=updates, **kwargs)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\tensorflow\python\keras\backend.py", line 2939, in __init__
with ops.control_dependencies(self.outputs):
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\tensorflow\python\framework\ops.py", line 5028, in control_dependencies
return get_default_graph().control_dependencies(control_inputs)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\tensorflow\python\framework\ops.py", line 4528, in control_dependencies
c = self.as_graph_element(c)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\tensorflow\python\framework\ops.py", line 3478, in as_graph_element
return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
File "C:\Users\MAULI\Miniconda3\envs\my_flask_env\lib\site-packages\tensorflow\python\framework\ops.py", line 3557, in _as_graph_element_locked
raise ValueError("Tensor %s is not an element of this graph." % obj)
ValueError: Tensor Tensor("activation_11/Softmax:0", shape=(?, 5), dtype=float32) is not an element of this graph.

对于这个问题,有几种替代方案。有一个解决方案可能会有所帮助。
我收集到的是flask对每个请求都使用线程,因此您的模型在该特定线程中未初始化。要解决此问题,您需要创建一个TensorFlow会话,该会话可以按照链接中的建议在多个线程之间共享。

此问题有一些替代方案。有一个解决方案可能会有所帮助。 我收集到的是flask对每个请求都使用线程,因此您的模型在该特定线程中未初始化。要解决这个问题,您需要创建一个TensorFlow会话,该会话可以按照链接中的建议跨线程共享