はじめに
ディープラーニングの基本は大体わかってきたので、Flaskでそれを用いたウェブアプリを作ってみたくなった。Flaskを使うのも初めてなので、動いてくれればよしとする。
分類器
どんな分類器を作るかだが、ディープラーニングを勉強しているときにMNIST-fashionという画像データを学習させたモデルがあったので、それを再利用することにした。このモデルは白黒の画像データ(Tシャツや靴など)を渡すとその衣服の名を返す。精度は微妙。
open('mnist_fashion_model.json',"w").write(model.to_json())
model.save_weights('mnist_fashion.h5')
こんな感じでmodelを保存しておく。
Flaskで実装
フォルダ
ディレクトリツリーはこんな感じ。かなりシンプル。
mnist_fashion_app/
|---app.py
|---mnist_fashion_model.json
|---mnist_fashion.h5
|---templates/
| |---first_page.html
| |---result.html
|---static/
| |---style.css
保存したモデルのファイルをくっつけておく。
app.py
いらないライブラリもインポートしてるかも。
index()でfirst_page.htmlにとばし、result()でfirst_page.htmlから得た画像データをモデルにいれて、その出力をresult.htmlで表示させている。
from flask import Flask, render_template, request
import numpy as np
import io
from keras.models import Sequential, model_from_json
from PIL import Image
from keras.layers.core import Dense
from keras.optimizers import RMSprop
app = Flask(__name__)
@app.route("/")
def index():
return render_template("first_page.html")
@app.route("/result", methods=["POST"])
def result():
image = request.files["image"]
img = Image.open(image)
img_resize = img.resize((28,28))
img_resize = np.asarray(img_resize)
im_gray = 0.299 * img_resize[:, :, 0] + 0.587 * img_resize[:, :, 1] + 0.114 * img_resize[:, :, 2]
im_gray = im_gray.astype('float32')/255.0
im_gray = im_gray.reshape(-1, 784)
model = model_from_json(open('mnist_fashion_model.json').read())
model.load_weights('mnist_fashion.h5')
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
answer_bin = model.predict(im_gray)
num = np.argmax(answer_bin)
dic = {0 : 'T-shirt',
1 : "Trouser",
2 : "Pullover",
6 : "Shirt",
7 : "Sneaker",
8 : "Bag",
9 : "Ankle boot"}
answer = dic[num]
return render_template("result.html", answer=answer)
if __name__ == "__main__":
app.run(debug=True)
first_page.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>first_page</title>
</head>
<body>
<h1>Fashion Discriminator</h1>
<h2>Upload your fashion picture</h2>
<form action="/result" method="post" enctype="multipart/form-data">
<input type="file" name="image" accept="image/png, image/jpeg">
<button type="submit">submit</button>
</form>
</body>
</html>
result.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Result</title>
</head>
<body>
<h1>This is a {{ answer }}</h1>
</body>
</html>
style.cssはフォントサイズだけ。
動かしてみる
この画像を入れてみる。This is a Sneaker とでれば成功である(スニーカーではないが)。
結果、This is a Bag とでた。
振り返り
FlaskでCNNのモデルを用いたウェブアプリを作るという最低限の目標は達成したが、精度の悪さや、入れる画像によってはエラーがでるなど、改善点も多く見つかった。
参考文献
この本を参考にした。
「Python機械学習プログラミング達人データサイエンティストによる理論と実践」
著者Sebastian Raschka, Vahid Mirijalili
発行所 株式会社インプレス