Keras 深層学習 AppEngine Python gcp

# これは何?
- [前回](https://qiita.com/yoko8ma/items/0068f7ef1a1b03c5f46d)で公開したAPIをブラウザから利用する
- ソースコード: [GitHub](https://github.com/yoko8ma/gcp-tutorial/tree/master/appengine/standard_python37/iris)

# 環境
- Keras
- Python3系のスタンダード環境のAppEngine
- APIサーバーのウェブフレームワークとしてresponder

# 構成
![Iris.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2137/fbb43d95-deec-c5fe-1067-4d1a1784351d.png)

- ブラウザから特徴量を入力して送信すると予測結果が表示される

# 準備
- [前回](https://qiita.com/yoko8ma/items/0068f7ef1a1b03c5f46d)で公開したモデルはpickle形式だったがKerasの形式に変更する
- 具体的はJupyter Notebookで保存する形式を変更する

```python
# 学習済みモデルの保存
model.save('model.h5', include_optimizer=False)

# with open("./model.pkl", 'wb') as f:
# pickle.dump(model, f)
```

- 作成したモデルをAppEngineフォルダのstaticへコピーする

# 実装
- 以下は要所のみ

```
.
├── app.yaml
├── gunicorn_conf.py
├── index.yaml
├── main.py
├── requirements.txt
├── static
│ ├── index.html
│ ├── model.h5
│ └── scaler.pkl
└── templates
└── index.html
```

- `main.py`にフォームのルーティングを追加する

```python:main.py
@api.route('/')
def index(req, resp):
resp.html = api.template("index.html")
```

- APIのエンドポイントも追加する

```python:main.py
@api.route('/api/v1/predict')
def predict(req, resp):
```

- `templates/index.html`にフォームを作成する
- 今回はBootstrapを使用する

```html:index.html
<div class="container">
<div class="row">
<div class="col">
<form class="form-horizontal" style="margin-top: 50px;" id="predictionForm" action="/api/v1/predict" method="get" >
<div class="form-group">
<label>がく片の長さ (cm)</label>
<input type="text" name="sepal_length" class="form-control">
</div>
<div class="form-group">
<label>がく片の幅 (cm)</label>
<input type="text" name="sepal_width" class="form-control">
</div>
<div class="form-group">
<label>花びらの長さ (cm)</label>
<input type="text" name="petal_length" class="form-control">
</div>
<div class="form-group">
<label>花びらの幅 (cm)</label>
<input type="text" name="petal_width" class="form-control">
</div>
<button type="submit" class="onSubmit">予測</button>
</form>
</div>
</div>
```

- 実際のフォームはこんな感じ

![スクリーンショット 2019-08-12 22.58.23.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2137/4bd57945-9eb6-3ac3-2c34-0f11d3c54545.png)

- フォームからの入力値を取得する処理を追加する

```python:main.py
# 予測データ
sepal_length = req.params.get("sepal_length")
sepal_width = req.params.get("sepal_width")
petal_length = req.params.get("petal_length")
petal_width = req.params.get("petal_width")
```

- Kerasの学習済みモデルの読込

```python:main.py
# 学習済みモデルの読込
model = keras.models.load_model("./static/model.h5", compile=False)
```

# 実行
- AppEngineにデプロイ後、フォームから入力し送信すると予測結果が表示される

![スクリーンショット 2019-08-12 23.03.17.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2137/b3873d66-dc1f-50b2-8d13-dce218bad822.png)

この記事が気に入ったらサポートをしてみませんか?