搜尋
首頁後端開發Python教學Streamlit:ML 應用程式建立的魔杖

Streamlit 是一個強大的開源框架,允許您為資料科學機器學習建立網路應用程式,隻隻只需幾行Python程式碼。

它簡單、直觀,並且不需要前端經驗,這使其成為初學者和想要快速部署機器學習模型的經驗豐富的開發人員的絕佳工具。

在本部落格中,我將指導您逐步使用 Iris 資料集 和 RandomForestClassifier 建立基本的 Streamlit 應用程式和 機器學習專案 .

Streamlit 入門

在進入專案之前,讓我們先了解一些基本的 Streamlit 功能,以熟悉該框架。您可以使用以下命令安裝 Streamlit:


pip install streamlit


安裝後,您可以透過建立一個 Python 檔案(例如 app.py)來啟動您的第一個 Streamlit 應用程序,並使用以下命令運行它:


streamlit run app.py


現在,讓我們來探討一下 Streamlit 的核心功能:

1。寫標題並顯示文字


import streamlit as st

# Writing a title
st.title("Hello World")

# Display simple text
st.write("Displaying a simple text")


Streamlit: The Magic Wand for ML App Creation

2。顯示資料框


import pandas as pd

# Creating a DataFrame
df = pd.DataFrame({
    "first column": [1, 2, 3, 4],
    "second column": [5, 6, 7, 8]
})

# Display the DataFrame
st.write("Displaying a DataFrame")
st.write(df)


Streamlit: The Magic Wand for ML App Creation

3。用圖表視覺化數據


import numpy as np

# Generating random data
chart_data = pd.DataFrame(
    np.random.randn(20, 4), columns=['a', 'b', 'c', 'd']
)

# Display the line chart
st.line_chart(chart_data)


Streamlit: The Magic Wand for ML App Creation

4。使用者互動:文字輸入、滑桿和選擇框
Streamlit 支援互動式小工具,例如文字輸入、滑桿和根據使用者輸入動態更新的選擇框。


# Text input
name = st.text_input("Your Name Is:")
if name:
    st.write(f'Hello, {name}')

# Slider
age = st.slider("Select Your Age:", 0, 100, 25)
if age:
    st.write(f'Your Age Is: {age}')

# Select Box
choices = ["Python", "Java", "Javascript"]
lang = st.selectbox('Favorite Programming Language', choices)
if lang:
    st.write(f'Favorite Programming Language is {lang}')


Streamlit: The Magic Wand for ML App Creation

5。文件上傳
您可以允許使用者上傳檔案並在您的 Streamlit 應用程式中動態顯示其內容:


# File uploader for CSV files
file = st.file_uploader('Choose a CSV file', 'csv')

if file:
    data = pd.read_csv(file)
    st.write(data)


Streamlit: The Magic Wand for ML App Creation

使用 Streamlit 建構機器學習專案

現在您已經熟悉了基礎知識,讓我們深入創建一個機器學習專案。我們將使用著名的 Iris 資料集,並使用 scikit-learn 中的 RandomForestClassifier 建立一個簡單的分類 模型

專案結構:

  • 載入資料集。
  • 訓練隨機森林分類器。
  • 允許使用者使用滑桿輸入功能。
  • 根據輸入特徵預測物種。

1。安裝必要的依賴項
首先,讓我們安裝必要的函式庫:


pip install streamlit scikit-learn numpy pandas


2。導入庫並載入資料
讓我們導入必要的庫並載入 Iris 資料集:


import streamlit as st
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier

# Cache data for efficient loading
@st.cache_data
def load_data():
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df["species"] = iris.target
    return df, iris.target_names

df, target_name = load_data()


3。訓練機器學習模型
獲得資料後,我們將訓練隨機森林分類器以根據花的特徵來預測花的種類:


# Train RandomForestClassifier
model = RandomForestClassifier()
model.fit(df.iloc[:, :-1], df["species"])


4。建立輸入介面
現在,我們將在側邊欄中建立滑桿,以允許使用者輸入用於進行預測的特徵:


# Sidebar for user input
st.sidebar.title("Input Features")
sepal_length = st.sidebar.slider("Sepal length", float(df['sepal length (cm)'].min()), float(df['sepal length (cm)'].max()))
sepal_width = st.sidebar.slider("Sepal width", float(df['sepal width (cm)'].min()), float(df['sepal width (cm)'].max()))
petal_length = st.sidebar.slider("Petal length", float(df['petal length (cm)'].min()), float(df['petal length (cm)'].max()))
petal_width = st.sidebar.slider("Petal width", float(df['petal width (cm)'].min()), float(df['petal width (cm)'].max()))


5。預測物種
獲得使用者輸入後,我們將使用經過訓練的模型進行預測:


# Prepare the input data
input_data = [[sepal_length, sepal_width, petal_length, petal_width]]

# Prediction
prediction = model.predict(input_data)
prediction_species = target_name[prediction[0]]

# Display the prediction
st.write("Prediction:")
st.write(f'Predicted species is {prediction_species}')


這看起來像:

Streamlit: The Magic Wand for ML App Creation

Streamlit: The Magic Wand for ML App Creation

最後,Streamlit 讓建立和部署機器學習 Web 介面變得非常容易,並且花費最少的精力。 ?只需幾行程式碼,我們就建立了一個互動式應用程式?允許使用者輸入特徵並預測花的種類?使用機器學習模型。 ??

編碼愉快! ?

以上是Streamlit:ML 應用程式建立的魔杖的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python的混合方法:編譯和解釋合併Python的混合方法:編譯和解釋合併May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。

了解python的' for”和' then”循環之間的差異了解python的' for”和' then”循環之間的差異May 08, 2025 am 12:11 AM

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

Python串聯列表與重複Python串聯列表與重複May 08, 2025 am 12:09 AM

在Python中,可以通過多種方法連接列表並管理重複元素:1)使用 運算符或extend()方法可以保留所有重複元素;2)轉換為集合再轉回列表可以去除所有重複元素,但會丟失原有順序;3)使用循環或列表推導式結合集合可以去除重複元素並保持原有順序。

Python列表串聯性能:速度比較Python列表串聯性能:速度比較May 08, 2025 am 12:09 AM

fasteStmethodMethodMethodConcatenationInpythondependersonListsize:1)forsmalllists,operatorseffited.2)forlargerlists,list.extend.extend()orlistComprechensionfaster,withextendEffaster,withExtendEffers,withextend()withextend()是extextend()asmoremory-ememory-emmoremory-emmoremory-emmodifyinginglistsin-place-place-place。

您如何將元素插入python列表中?您如何將元素插入python列表中?May 08, 2025 am 12:07 AM

toInSerteLementIntoApythonList,useAppend()toaddtotheend,insert()foreSpificPosition,andextend()formultiplelements.1)useappend()foraddingsingleitemstotheend.2)useAddingsingLeitemStotheend.2)useeapecificindex,toadapecificindex,toadaSpecificIndex,toadaSpecificIndex,blyit'ssssssslorist.3 toaddextext.3

Python是否列表動態陣列或引擎蓋下的鏈接列表?Python是否列表動態陣列或引擎蓋下的鏈接列表?May 07, 2025 am 12:16 AM

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他們areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

如何從python列表中刪除元素?如何從python列表中刪除元素?May 07, 2025 am 12:15 AM

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)刪除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

試圖運行腳本時,應該檢查是否會遇到'權限拒絕”錯誤?試圖運行腳本時,應該檢查是否會遇到'權限拒絕”錯誤?May 07, 2025 am 12:12 AM

toresolvea“ dermissionded”錯誤Whenrunningascript,跟隨台詞:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器