3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GradioとScikit-learnを使ってみたはなし

3
Posted at

はじめに

この記事は JSL (日本システム技研) Advent Calendar 2025 - Qiita 20日目の記事です。

毎年恒例、誕生日記念記事です:tada:。
早いもので今年48になりました。健康で無事迎えられたことに感謝:pray:。

現場を離れて久しいのですが、ずっとWeb一筋でやってきたのでずっと遠くから眺めていた機械学習に触れてみたくなりました。

Webで見える化をしつつ、初歩的な機械学習について学んでみたくGradioとScikit-learnを使用してみることにしました。

Gradioとは

機械学習モデルやPython関数を数行のコードで簡単にWebアプリ化(デモ・共有)できるPythonライブラリです

Webアプリ化するライブラリとして、Streamlitがありますが、MLモデルの検証や見える化する場合は、Gradioの方が優れているようです。

インストールとデモ実行

$ uv add gradio  
import gradio as gr

def greet(name, intensity):
    return "Hello, " + name + "!" * int(intensity)

demo = gr.Interface(
    fn=greet,
    inputs=["text", "slider"],
    outputs=["text"],
    api_name="predict"
)

demo.launch()
# 実行
$ python app.py

http://127.0.0.1:7860をブラウザで叩くと以下が表示されます。

gradiodemo.gif

Scikit-learnと使ってみる

irisデータを使用してモデルを作成します。
自分なりのメモを残しながら進めます。

基本的な流れ

  1. データ準備
  2. 学習用 / テスト用に分ける
  3. モデルを作る
  4. 学習する
  5. 予測する
  6. 評価する

以下、JupyterLabで試していきます。

1. データ準備

from sklearn.datasets import load_iris

iris = load_iris()
x = iris.data      # 入力データ(特徴量)
y = iris.target    # 正解

xは、特徴量が格納されています。

  • ガクの長さ
  • 幅
  • 花弁の長さ
  • 幅

yは、アイリスの種類が格納されています。

  • 0(=setosa),
  • 1(=versicolor)
  • 2(=virginica)

以下、30件のデータを参照してみます。

for data, target in zip(iris.data[:30], iris.target[:30]):
    print(data, target)
[5.1 3.5 1.4 0.2] 0
[4.9 3.  1.4 0.2] 0
[4.7 3.2 1.3 0.2] 0
[4.6 3.1 1.5 0.2] 0
[5.  3.6 1.4 0.2] 0
[5.4 3.9 1.7 0.4] 0
[4.6 3.4 1.4 0.3] 0
[5.  3.4 1.5 0.2] 0
[4.4 2.9 1.4 0.2] 0
[4.9 3.1 1.5 0.1] 0

2. 学習用 / テスト用に分ける

from sklearn.model_selection import train_test_split

x_train, x_test, y_train, y_test = train_test_split(
    x, y,
    test_size=0.2,
    random_state=42
)

test_sizeは、テストデータに使用するデータの割合を指定します。今回は、20%とします。random_stateはデータをランダムで取得するためのシード値になります。

x_train、y_trainは学習用、x_test、y_testはテスト用のデータです。

3. モデルを作る

from sklearn.ensemble import RandomForestClassifier

model = RandomForestClassifier()

今回は、RandomForestClassifierを指定します。
モデルの詳細については、今回は割愛します。
(今後の深堀り課題)

4. 学習する

model.fit(x_train, y_train)

5. 予測する

y_pred = model.predict(x_test)
print(y_pred)

テストデータで予測します。以下の結果となりました。

[1 0 2 1 1 0 1 2 1 1 2 0 0 0 0 1 2 1 1 2 0 2 0 2 2 2 2 2 0 0]

6. 評価する

from sklearn.metrics import accuracy_score

accuracy = accuracy_score(y_test, y_pred)
print(accuracy)

irisデータは0.9〜1.0の精度となるようです。

学習済モデルの保存

$ uv add scikit-learn joblib

JupyterLabで試したものを利用して、MLモデルをpklファイル形式で作成します。

学習したモデルをjoblibを使用して書き出します。

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import joblib

# 1. データ準備
iris = load_iris()
x = iris.data      # 入力データ(特徴量)
y = iris.target    # 正解

# 2. 学習用 / テスト用に分ける
x_train, x_test, y_train, y_test = train_test_split(
    x, y,
    test_size=0.2,
    random_state=42
)

# 3. モデルを作る
model = RandomForestClassifier()

# 4. 学習する
model.fit(x_train, y_train)

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

学習済モデルをGradioから呼び出す

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 get_name(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 = get_name(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()

qiita2.gif

まとめ

機械学習は以前より興味があり何度か学ぼうと座学から始めるものの、いつも途中で飽きてしまい長続きしなかったのですが最近は、生成AIが壁打ち相手や叩き台を生成してくれるので学習するハードルが以前より下がったように思えます。今後は、今回使用したモデル(RandomForestClassifier)の深堀りや、その他のモデルについても学んでいきたいと思います。

歳を重ねると新しいことにトライすることが面倒にもなってきてますが、生成AIの発展が良い手助けになってくれたと思います。

3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?