搜索
首页后端开发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脚本可能无法在UNIX上执行的一些常见原因是什么?Python脚本可能无法在UNIX上执行的一些常见原因是什么?Apr 28, 2025 am 12:18 AM

Python脚本在Unix系统上无法运行的原因包括:1)权限不足,使用chmod xyour_script.py赋予执行权限;2)Shebang行错误或缺失,应使用#!/usr/bin/envpython;3)环境变量设置不当,可打印os.environ调试;4)使用错误的Python版本,可在Shebang行或命令行指定版本;5)依赖问题,使用虚拟环境隔离依赖;6)语法错误,使用python-mpy_compileyour_script.py检测。

举一个场景的示例,其中使用Python数组比使用列表更合适。举一个场景的示例,其中使用Python数组比使用列表更合适。Apr 28, 2025 am 12:15 AM

使用Python数组比列表更适合处理大量数值数据。1)数组更节省内存,2)数组对数值运算更快,3)数组强制类型一致性,4)数组与C语言数组兼容,但在灵活性和便捷性上不如列表。

在Python中使用列表与数组的性能含义是什么?在Python中使用列表与数组的性能含义是什么?Apr 28, 2025 am 12:10 AM

列表列表更好的forflexibility andmixDatatatypes,何时出色的Sumerical Computitation sand larged数据集。1)不可使用的列表xbilese xibility xibility xibility xibility xibility xibility xibility xibility xibility xibility xibles and comply offrequent elementChanges.2)

Numpy如何处理大型数组的内存管理?Numpy如何处理大型数组的内存管理?Apr 28, 2025 am 12:07 AM

numpymanagesmemoryforlargearraysefefticefticefipedlyuseviews,副本和内存模拟文件.1)viewsAllowSinglicingWithOutCopying,直接modifytheoriginalArray.2)copiesCanbecopy canbecreatedwitheDedwithTheceDwithThecevithThece()methodervingdata.3)metservingdata.3)memore memore-mappingfileShessandAstaStaStstbassbassbassbassbassbassbassbassbassbassbb

哪个需要导入模块:列表或数组?哪个需要导入模块:列表或数组?Apr 28, 2025 am 12:06 AM

Listsinpythondonotrequireimportingamodule,helilearraysfomthearraymoduledoneedanimport.1)列表列表,列表,多功能和canholdMixedDatatatepes.2)arraysaremoremoremoremoremoremoremoremoremoremoremoremoremoremoremoremoremeremeremeremericdatabuteffeftlessdatabutlessdatabutlessfiblesible suriplyElsilesteletselementEltecteSemeTemeSemeSemeSemeTypysemeTypysemeTysemeTypysemeTypepe。

可以在Python数组中存储哪些数据类型?可以在Python数组中存储哪些数据类型?Apr 27, 2025 am 12:11 AM

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

如果您尝试将错误的数据类型的值存储在Python数组中,该怎么办?如果您尝试将错误的数据类型的值存储在Python数组中,该怎么办?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Python标准库的哪一部分是:列表或数组?Python标准库的哪一部分是:列表或数组?Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

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

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器