【python Flask】使用 Flask 通过预先训练的深度学习模型来提供预测API

1、首先安装包


pip install  tensorflow
pip install  keras
pip install  pandas

2、keras 训练你的模型保存为一个文件。

# -*- coding:utf-8 -*-

# 导入panda,keras 和tensorflow
import pandas as pd
import tensorflow as tf
import keras
from keras import models, layers


# 加载样本数据集,划分为x和y DataFrame
df = pd.read_csv("https://github.com/bgweber/Twitch/raw/master/Recommendations/games-expand.csv")
x = df.drop(['label'], axis=1)
y = df['label']

print(x)

print(y)

# 定义Keras模型
model = models.Sequential()
model.add(layers.Dense(64, activation='relu', input_shape=(10,)))
model.add(layers.Dropout(0.1))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dropout(0.1))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

# 使用自定义度量函数
def auc(y_true, y_pred):
    auc = tf.metrics.auc(y_true, y_pred)[1]
    keras.backend.get_session().run(tf.local_variables_initializer())
    return auc


# 编译并拟合模型
model.compile(optimizer='rmsprop',loss='binary_crossentropy',
              metrics=[auc])
history = model.fit(x, y, epochs=100, batch_size=100,
                    validation_split = .2, verbose=0)

# 以H5格式保存模型
model.save("./static/games.h5")

3、数据形式如下:自变量是10个,G1~G10,目标变量是二分类0和1

E:\laidefa\python.exe "E:/Program Files/pycharmproject/深度学习api/model_keras_train.py"
Using TensorFlow backend.
       G1  G2  G3  G4  G5  G6  G7  G8  G9  G10
0       0   0   0   1   0   0   0   0   0    0
1       0   0   0   0   1   0   0   0   0    0
2       0   0   1   0   0   0   0   0   0    0
3       0   0   1   0   0   1   1   0   0    1
4       0   0   1   0   1   1   0   1   1    0
5       1   0   1   0   1   0   0   0   0    0
6       0   0   1   0   0   0   0   0   0    0
7       1   0   1   0   1   0   0   0   0    0
8       1   1   0   1   0   1   1   1   0    0
9       0   0   1   0   0   0   0   0   0    0
10      1   0   1   0   0   0   0   0   0    0
11      1   0   0   0   0   1   0   0   1    0
12      0   0   1   1   0   0   0   0   0    0
13      1   0   1   0   0   0   0   0   0    0
14      0   0   1   0   0   0   0   0   0    0
15      1   1   0   1   1   1   0   0   1    0
16      0   0   1   0   1   1   0   0   0    0
17      1   0   1   0   1   0   0   0   0    0
18      0   0   0   0   0   0   0   0   1    0
19      0   0   1   0   0   0   0   0   0    0
20      0   0   0   1   0   0   0   0   0    0
21      0   0   1   0   0   0   0   0   0    0
22      1   0   0   0   1   0   0   0   0    0
23      1   1   0   0   0   1   1   0   1    0
24      0   0   0   0   1   0   0   0   0    0
25      0   0   0   0   0   0   0   0   0    0
26      0   0   1   0   0   0   0   0   0    0
27      0   1   0   0   1   0   1   1   0    1
28      1   1   0   0   0   1   1   0   1    0
29      0   0   0   0   0   0   0   0   1    1
...    ..  ..  ..  ..  ..  ..  ..  ..  ..  ...




[22905 rows x 10 columns]
0        0
1        0
2        0
3        1
4        1
5        0
6        0
7        0
8        0
9        0
10       0
11       0
12       0
13       0
14       0
15       0
16       0
17       0
18       0
19       0
20       0
21       0
22       0
23       1
24       0
25       0
26       0

训练好之后,文件保存为games.h5

5、下面我们编写flask api 部署我们的深度学习模型

训练了深度学习模型,接下来可以使用 Flask 来生产 Keras 模型。用于模型预测的完整代码如下所示。代码的整体结构与前面的代码示例相同,但主要区别在于定义预测函数之前先加载模型,并在预测函数中使用模型。要想重新加载模型,我们需要使用 custom_objects 参数将自定义度量函数作为输入参数传递给 load_model。

# -*- coding:utf-8 -*-


# 加载库
import flask
import pandas as pd
import tensorflow as tf
import keras
from keras.models import load_model

# 实例化 flask
app = flask.Flask(__name__)


# 我们需要重新定义我们的度量函数,从而在加载模型时使用它
def auc(y_true, y_pred):
    auc = tf.metrics.auc(y_true, y_pred)[1]
    keras.backend.get_session().run(tf.local_variables_initializer())
    return auc


# 加载模型,传入自定义度量函数
global graph
graph = tf.get_default_graph()
model = load_model('./static/games.h5', custom_objects={'auc': auc})

# 将预测函数定义为一个端点
@app.route("/predict", methods=["GET","POST"])
def predict():
    data = {"success": False}

    params = flask.request.json
    if (params == None):
        params = flask.request.args

    # 若发现参数,则返回预测值
    if (params != None):
        x=pd.DataFrame.from_dict(params, orient='index').transpose()
        with graph.as_default():
            data["prediction"] = str(model.predict(x)[0][0])
            data["success"] = True


    # 返回Jason格式的响应
    return flask.jsonify(data)

if __name__ == '__main__':

    # 启动Flask应用程序,允许远程连接
    app.run(host='0.0.0.0',port='5000')

6、启动你的程序:在浏览器输入:http://localhost:5000/predict?g1=1&g2=1&g3=0&g4=1&g5=1&g6=1&g7=1&g8=0&g9=1&g10=0

注意:需要指定属性 G1 到 G10 的值

服务请求成功:

 * Serving Flask app "keras_mode_api" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [15/Nov/2018 16:15:22] "GET /predict?g1=1&g2=0&g3=0&g4=0&g5=0&g6=0&g7=0&g8=0&g9=0&g10=0 HTTP/1.1" 200 -
127.0.0.1 - - [15/Nov/2018 16:15:22] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [15/Nov/2018 16:15:30] "GET /predict?g1=1&g2=0&g3=0&g4=0&g5=1&g6=0&g7=0&g8=0&g9=0&g10=0 HTTP/1.1" 200 -
127.0.0.1 - - [15/Nov/2018 16:15:35] "GET /predict?g1=1&g2=0&g3=0&g4=0&g5=1&g6=0&g7=1&g8=0&g9=0&g10=0 HTTP/1.1" 200 -
127.0.0.1 - - [15/Nov/2018 16:15:40] "GET /predict?g1=1&g2=0&g3=0&g4=0&g5=1&g6=0&g7=1&g8=0&g9=1&g10=0 HTTP/1.1" 200 -
127.0.0.1 - - [15/Nov/2018 16:15:44] "GET /predict?g1=1&g2=1&g3=0&g4=0&g5=1&g6=0&g7=1&g8=0&g9=1&g10=0 HTTP/1.1" 200 -
127.0.0.1 - - [15/Nov/2018 16:15:49] "GET /predict?g1=1&g2=1&g3=0&g4=1&g5=1&g6=0&g7=1&g8=0&g9=1&g10=0 HTTP/1.1" 200 -
127.0.0.1 - - [15/Nov/2018 16:15:55] "GET /predict?g1=1&g2=1&g3=0&g4=1&g5=1&g6=1&g7=1&g8=0&g9=1&g10=0 HTTP/1.1" 200 -
127.0.0.1 - - [15/Nov/2018 16:17:47] "GET /predict?g1=1&g2=1&g3=0&g4=1&g5=1&g6=1&g7=1&g8=0&g9=1&g10=0 HTTP/1.1" 200 -

查看结果:

【python Flask】使用 Flask 通过预先训练的深度学习模型来提供预测API_第1张图片

你可能感兴趣的:(数据科学--python)