Flask应用程序提供的Tensorflow.keras.Model + uwsgi被卡在model.predict中

时间:2019-11-18 17:21:41

标签: python tensorflow flask uwsgi

我正在尝试使用Tensorflow v1.14在Flask + nginx + uwsgi应用程序中提供 tensorflow.keras.Model

我在Flask的应用程序工厂函数中将模型加载到名为 Prediction 的类的构造函数中,并将图形另存为 建议here使用Flask应用。

然后我通过在我的名为 _process 的路由中调用方法 Prediction.process 来运行预测Flask应用程序,但在调用 tf.keras.Model.predict predict.py 中的self.model.summary()是执行,即显示摘要,但不显示print("Never gets here :("))。

如果我在 _process 中初始化类 Prediction (我希望避免不必加载该类)每个预测的模型),一切正常。

如果我使用Flask服务器,它也可以正常工作。因此,似乎与uwsgi config有关。

有什么建议吗?

初始 .py

def create_app():
    app = Flask(__name__)
    #(...)
    app.register_blueprint(bp)
    load_tf_model(app)
    return app


def load_tf_model(app):

    sess = tf.Session(graph=tf.Graph())
    app.sess = sess

    with sess.graph.as_default():
        weights =  os.path.join(app.static_folder, 'weights/model.32-0.81.h5')
        app.prediction = Prediction(weights)

predict.py

class Prediction:

    def __init__(self,  weights):

        # build model and set weights
        inputs = tf.keras.Input(shape=SHAPE, batch_size=1)
        outputs = simple_cnn.build_model(inputs, N_CLASSES)
        self.model = tf.keras.Model(inputs=inputs, outputs=outputs)
        self.model.load_weights(weights)
        self.model._make_predict_function()

        # create TF mel extractor
        self.melspec_ex = tf_feature_utils.MelSpectrogram()


    def process(self, audio, sr):

        # compute features (in NCHW format) and labels
        data = audio2data(
            audio,
            sr,
            class_list=np.arange(N_CLASSES))
        features = np.asarray([d[0] for d in data])
        features = tf.reshape(features, (features.shape[0], 1, features.shape[1], features.shape[2]))
        labels = np.asarray([d[1] for d in data])

        # make tf.data.Dataset
        dataset = tf.data.Dataset.from_tensor_slices((features, labels))
        dataset = dataset.batch(1)
        dataset = dataset.map(lambda data, labels: (
            tf.expand_dims(self.melspec_ex.process(tf.squeeze(data, axis=[1,2])), 1)))

        # show model (debug)
        self.model.summary()

        # run prediction
        predictions = self.model.predict(dataset)

        print("Never gets here :(")

        # integrate predictions over time
        return np.mean(predictions, axis=0)

routes.py

@bp.route('/_process', methods=['POST'])
def _process():

    with current_app.graph.as_default():

        # load audio
        filepath = session['filepath']
        audio, sr = librosa.load(filepath)

        # predict
        predictions =  current_app.prediction.process(audio, sr)

        # delete file
        os.remove(filepath)

        return jsonify(prob=predictions.tolist())

1 个答案:

答案 0 :(得分:0)

这是一个线程问题。我必须使用以下选项添加configure uwsgi:

master = false 
processes = 1
cheaper = 0