LoginSignup
16
14

More than 1 year has passed since last update.

Gradioとは? Pythonで機械学習Webアプリケーションをサクッと作ろう!

Last updated at Posted at 2022-10-03

Gradioとは

スクリーンショット-2022-10-03-13.37.09-2048x996.png

Gradioとは、機械学習モデルのデモを行うWebアプリケーションを簡単に作ることができるPythonのライブラリーです。
この記事では解説致しませんが、Gradioで作成したWebアプリケーションは、HuggingFaceSpacesでアプリを公開することができます。(現時点では、Gradio以外にも、Streamlitをサポートしています。

Gradioの公式ページより、デモアプリケーションを確認できます。
スクリーンショット-2022-10-03-13.55.51-2048x971.png

Gradioをインストールする

Gradioをインストールは以下のコマンドをpipコマンドでインストールするだけです。
Macですとターミナル、Windowsですとコマンドプロンプトを起動し、次のコマンドを入力し実行(Enter)してください)

pip install gradio

おみくじアプリケーションを作ろう

今回2つのアプリケーションを作成します。
1つ目に作成するアプリケーションは今日の運勢が表示されるシンプルなおみくじWebアプリケーションを作ります。
実行環境はGradioがインストールされたGoogle Colabを利用します。
以下がコード全体です。

import random
import gradio as gr

def get_foturne(your_name):
    fortune_lists = ['大吉', '吉', '小吉', '凶', '末吉']
    fortune_result = random.choice(fortune_lists)
    return your_name + "さんの今日の運勢は・・・" + fortune_result + "です"


demo = gr.Interface(fn=get_foturne,
                    inputs="text",
                    outputs="text")
demo.launch()

アプリケーションを実行すると、URLが発行されますが、Colab内にアプリケーションが表示されますので、そこから動作の確認ができます。名前を入力し送信ボタンを押すと、運勢が表示されます。
スクリーンショット-2022-10-03-14.23.31.png

送信ボタンを押すたびに、出力結果が変わります。

花の種類を判定するWebアプリケーションを作ろう

次は機械学習を用いた花の種類を判定するアプリケーションを作ります。
今回はscikit-learnでニューラルネットワークを用いて花を判定するモデルを作成し、学習済みモデルをGradio内から読み込み動作させます。
(以下のプログラムの解説は割愛いたします)

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
import joblib
from sklearn.metrics import classification_report, accuracy_score

# データ取得
iris = load_iris()
x, y = iris.data, iris.target

# 訓練データとテストデータに分割
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5, random_state=0)

# solverには確率的勾配降下法(sgd)やadamなどが利用可能です。
model = MLPClassifier(solver="sgd", random_state=0, max_iter=3000)

# 学習
model.fit(x_train, y_train)
pred = model.predict(x_test)

# 学習済みモデルの保存
joblib.dump(model, "nn.pkl", compress=True)


# 精度と近藤行列の出力
print("result: ", model.score(x_test, y_test))
print(classification_report(y_test, pred))
上記のプログラムを実行すると、花の判別する学習済みモデル(nn.pkl)が作成されます。
これをGradio内で呼び出し、花の判定を行います。

from flask import Flask, render_template, request, flash
from wtforms import Form, FloatField, SubmitField, validators, ValidationError
import numpy as np
import gradio as gr
import joblib

# 学習済みモデルを読み込み利用します
def predict(parameters):
    # ニューラルネットワークのモデルを読み込み
    model = joblib.load('./nn.pkl')
    params = parameters.reshape(1, -1)
    pred = model.predict(params)
    return pred

# ラベルからIrisの名前を取得します
def getName(label):
    print(label)
    if label == 0:
        return "Iris Setosa"
    elif label == 1: 
        return "Iris Versicolor"
    elif label == 2: 
        return "Iris Virginica"
    else: 
        return "Error"

def recognition_flower(sepal_length, sepal_width, petal_length, petal_width):
    x = np.array([int(sepal_length), int(sepal_width), int(petal_length), int(petal_width)])
    pred = predict(x)
    irisName = getName(pred)
    return irisName


demo = gr.Interface(fn=recognition_flower,
                    inputs=[gr.Textbox(label="SepalLength"),
                            gr.Textbox(label="SepalWidth"),
                            gr.Textbox(label="PetalLength"),
                            gr.Textbox(label="PetalWidth")
                    ],
                    outputs="text")
demo.launch()

それぞれ4つの入力フォームに萼(がく)の長さや、花びらの長さなどを数値を入れてボタンを押すことで、花の種類が表示されます。
スクリーンショット-2022-10-03-14.35.08-2048x947.png

今回のようにサクッと機械学習を組み込んだWebアプリケーションを作ることが出来ます。

短期間で、AIアプリケーションのプロトタイプを作りたい方にはGradioはオススメです。是非オリジナルのAIアプリケーションを作ってみてください。

Python・AI Webアプリ開発スキルを効率よく身につけるには

AI Academy Bootcampでは、6ヶ月35,000円にてチャットで質問し放題の環境で、機械学習やデータ分析が学べます。
データサイエンティストや機械学習エンジニアに質問し放題の環境でデータ分析、統計、機械学習、SQL等が学べます。AI人材に必要なスキルを効率よく体系的に身に付けたい方は是非ご検討ください。

bootcamp_ad_72ppi.png

16
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
14