使用 Streamlit 將機器學習模型部署為 Web 應用程式

WBOY
發布: 2024-08-28 18:31:21
原創
370 人瀏覽過

介紹

機器學習模型本質上是一組用於進行預測或尋找資料模式的規則或機制。簡單來說(不用擔心過度簡化),在 Excel 中使用最小平方法計算的趨勢線也是模型。然而,實際應用中使用的模型並不那麼簡單——它們往往涉及更複雜的方程式和演算法,而不僅僅是簡單的方程式。

在這篇文章中,我將首先建立一個非常簡單的機器學習模型,並將其作為一個非常簡單的 Web 應用程式發布,以體驗整個過程。

在這裡,我將只專注於流程,而不是 ML 模型本身。 Alsom 我將使用 Streamlit 和 Streamlit Community Cloud 輕鬆發布 Python Web 應用程式。

長話短說:

使用 scikit-learn(一種流行的機器學習 Python 庫),您可以快速訓練資料並建立模型,只需幾行程式碼即可完成簡單任務。然後可以使用 joblib 將模型儲存為可重複使用檔案。這個已儲存的模型可以像 Web 應用程式中的常規 Python 庫一樣導入/加載,從而允許應用程式使用經過訓練的模型進行預測!

應用程式網址:https://yh-machine-learning.streamlit.app/
GitHub:https://github.com/yoshan0921/yh-machine-learning.git

技術堆疊

  • Python
  • 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 - 建立模型

Step1.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])
登入後複製

使用 one-hot 編碼(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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!