Streamlit を使用した Web アプリとしての機械学習モデルのデプロイメント

WBOY
リリース: 2024-08-28 18:31:21
オリジナル
370 人が閲覧しました

導入

機械学習モデルは本質的に、予測を行ったり、データ内のパターンを見つけたりするために使用される一連のルールまたはメカニズムです。非常に簡単に言うと (単純化しすぎることを恐れずに)、Excel の最小二乗法を使用して計算された傾向線もモデルです。ただし、実際のアプリケーションで使用されるモデルはそれほど単純ではありません。多くの場合、単純な方程式だけでなく、より複雑な方程式やアルゴリズムが含まれます。

この投稿では、プロセスの雰囲気をつかむために、非常に単純な機械学習モデルを構築し、それを非常に単純な Web アプリとしてリリースすることから始めます。

ここでは、ML モデル自体ではなく、プロセスのみに焦点を当てます。また、Streamlit と Streamlit Community Cloud を使用して、Python Web アプリケーションを簡単にリリースします。

TL;DR:

機械学習用の人気のある Python ライブラリである scikit-learn を使用すると、データを迅速にトレーニングし、単純なタスク用のわずか数行のコードでモデルを作成できます。その後、モデルは joblib を使用して再利用可能なファイルとして保存できます。この保存されたモデルは、Web アプリケーションの通常の Python ライブラリと同様にインポート/ロードできるため、アプリはトレーニングされたモデルを使用して予測を行うことができます!

アプリの URL: https://yh-machine-learning.streamlit.app/
GitHub: https://github.com/yoshan0921/yh-machine-learning.git

テクノロジースタック

  • パイソン
  • Streamlit: Web アプリケーション インターフェイスの作成用。
  • scikit-learn: 事前トレーニングされたランダム フォレスト モデルをロードして使用します。
  • NumPy と Pandas: データの操作と処理用。
  • Matplotlib と Seaborn: 視覚化の生成用。

私が作ったもの

このアプリを使用すると、パーマー ペンギン データセットでトレーニングされたランダム フォレスト モデルによって行われた予測を調べることができます。 (トレーニング データの詳細については、この記事の最後を参照してください。)

具体的には、このモデルは、種、島、くちばしの長さ、足ひれの長さ、体の大きさ、性別などのさまざまな特徴に基づいてペンギンの種を予測します。ユーザーはアプリを操作して、さまざまな特徴がモデルの予測にどのような影響を与えるかを確認できます。

  • 予測画面
    Machine Learning Model Deployment as a Web App using Streamlit

  • 学習データ・可視化画面
    Machine Learning Model Deployment as a Web App using Streamlit

開発ステップ 1 - モデルの作成

ステップ1.1 ライブラリをインポートする

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import joblib
ログイン後にコピー

pandas は、データ操作と分析に特化した Python ライブラリです。 DataFrame を使用したデータの読み込み、前処理、構造化をサポートし、機械学習モデル用のデータを準備します。
sklearn は、トレーニングと評価のためのツールを提供する機械学習用の包括的な Python ライブラリです。この投稿では、ランダム フォレストと呼ばれる学習手法を使用してモデルを構築します。
joblib は、機械学習モデルなどの Python オブジェクトを非常に効率的な方法で保存およびロードするのに役立つ Python ライブラリです。

Step1.2 データの読み込み

df = pd.read_csv("./dataset/penguins_cleaned.csv")
X_raw = df.drop("species", axis=1)
y_raw = df.species
ログイン後にコピー

データセット (トレーニング データ) をロードし、それを特徴 (X) とターゲット変数 (y) に分離します。

Step1.3 カテゴリ変数をエンコードする

encode = ["island", "sex"]
X_encoded = pd.get_dummies(X_raw, columns=encode)

target_mapper = {"Adelie": 0, "Chinstrap": 1, "Gentoo": 2}
y_encoded = y_raw.apply(lambda x: target_mapper[x])
ログイン後にコピー

カテゴリ変数は、ワンホット エンコード (X_encoded) を使用して数値形式に変換されます。たとえば、「island」にカテゴリ「Biscoe」、「Dream」、および「Torgersen」が含まれている場合、それぞれに新しい列が作成されます (island_Biscoe、island_Dream、island_Torgersen)。セックスでも同じことが行われます。元のデータが「Biscoe」の場合、island_Biscoe 列は 1 に設定され、その他の列は 0 に設定されます。
ターゲット変数の種は数値 (y_encoded) にマッピングされます。

Step1.4 データセットを分割する

x_train, x_test, y_train, y_test = train_test_split(
    X_encoded, y_encoded, test_size=0.3, random_state=1
)
ログイン後にコピー

モデルを評価するには、トレーニングに使用されていないデータに対するモデルのパフォーマンスを測定する必要があります。 7:3 は、機械学習の一般的な手法として広く使用されています。

Step1.5 ランダムフォレストモデルをトレーニングする

clf = RandomForestClassifier()
clf.fit(x_train, y_train)
ログイン後にコピー

モデルのトレーニングには Fit メソッドが使用されます。
x_train は説明変数の学習データを表し、y_train はターゲット変数を表します。
このメソッドを呼び出すと、学習データに基づいて学習されたモデルが clf.

に保存されます。

Step1.6 モデルを保存する

joblib.dump(clf, "penguin_classifier_model.pkl")
ログイン後にコピー

joblib.dump() は、Python オブジェクトをバイナリ形式で保存する関数です。モデルをこの形式で保存すると、モデルをファイルからロードして、再度トレーニングすることなくそのまま使用できます。

サンプルコード

Development Step2 - Building the Web App and Integrating the Model

Step2.1 Import Libraries

import streamlit as st
import numpy as np
import pandas as pd
import joblib
ログイン後にコピー

stremlit is a Python library that makes it easy to create and share custom web applications for machine learning and data science projects.
numpy is a fundamental Python library for numerical computing. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays efficiently.

Step2.2 Retrieve and encode input data

data = {
    "island": island,
    "bill_length_mm": bill_length_mm,
    "bill_depth_mm": bill_depth_mm,
    "flipper_length_mm": flipper_length_mm,
    "body_mass_g": body_mass_g,
    "sex": sex,
}
input_df = pd.DataFrame(data, index=[0])

encode = ["island", "sex"]
input_encoded_df = pd.get_dummies(input_df, prefix=encode)
ログイン後にコピー

Input values are retrieved from the input form created by Stremlit, and categorical variables are encoded using the same rules as when the model was created. Note that the order of each data must also be the same as when the model was created. If the order is different, an error will occur when executing a forecast using the model.

Step2.3 Load the Model

clf = joblib.load("penguin_classifier_model.pkl")
ログイン後にコピー

"penguin_classifier_model.pkl" is the file where the previously saved model is stored. This file contains a trained RandomForestClassifier in binary format. Running this code loads the model into clf, allowing you to use it for predictions and evaluations on new data.

Step2.4 Perform prediction

prediction = clf.predict(input_encoded_df)
prediction_proba = clf.predict_proba(input_encoded_df)
ログイン後にコピー

clf.predict(input_encoded_df): Uses the trained model to predict the class for the new encoded input data, storing the result in prediction.
clf.predict_proba(input_encoded_df): Calculates the probability for each class, storing the results in prediction_proba.

Sample Code

Step3. Deploy

Machine Learning Model Deployment as a Web App using Streamlit

You can publish your developed application on the Internet by accessing the Stremlit Community Cloud (https://streamlit.io/cloud) and specifying the URL of the GitHub repository.

About Data Set

Machine Learning Model Deployment as a Web App using Streamlit

Artwork by @allison_horst (https://github.com/allisonhorst)

The model is trained using the Palmer Penguins dataset, a widely recognized dataset for practicing machine learning techniques. This dataset provides information on three penguin species (Adelie, Chinstrap, and Gentoo) from the Palmer Archipelago in Antarctica. Key features include:

  • Species: The species of the penguin (Adelie, Chinstrap, Gentoo).
  • Island: The specific island where the penguin was observed (Biscoe, Dream, Torgersen).
  • Bill Length: The length of the penguin's bill (mm).
  • Bill Depth: The depth of the penguin's bill (mm).
  • Flipper Length: The length of the penguin's flipper (mm).
  • Body Mass: The mass of the penguin (g).
  • Sex: The sex of the penguin (male or female).

This dataset is sourced from Kaggle, and it can be accessed here. The diversity in features makes it an excellent choice for building a classification model and understanding the importance of each feature in species prediction.

以上がStreamlit を使用した Web アプリとしての機械学習モデルのデプロイメントの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!