跳至主要内容

Streamlit Python:教程

本 Python Streamlit 教程专为数据科学家和机器学习工程师打造,帮助您在不具备大量 Web 开发知识的情况下,快速构建 Web 应用。
· 15分钟 阅读

使用 AI 探索

什么是 Streamlit? 

Streamlit 是一个免费开源框架,可用于快速构建和分享漂亮的机器学习与数据科学 Web 应用。

它是一个专为机器学习工程师设计的 Python 库。数据科学家或机器学习工程师并非 Web 开发人员,他们也不想花上数周时间学习这些框架来构建 Web 应用。他们需要的是一种更易学、易用的工具,只要它能展示数据并收集建模所需的参数即可。

借助 Streamlit,您只需几行代码就能创建外观出色的应用。

Streamlit

数据科学家为何应使用 Streamlit?

Streamlit 最棒的一点在于,您甚至不需要掌握 Web 开发基础就能上手并创建您的第一个 Web 应用。因此,如果您从事数据科学并希望以极少代码、快速而轻松地部署模型,Streamlit 非常适合您。

应用成功的关键之一是交付一个高效且直观的用户界面。许多现代数据密集型应用都面临如何在不走复杂流程的前提下,快速构建有效用户界面的挑战。Streamlit 是一个很有前景的开源 Python 库,使开发者能够在极短时间内构建吸引人的用户界面。

对不懂前端的人来说,Streamlit 是将代码放到 Web 应用中的最简方式:

  • 无需前端(HTML、JS、CSS)经验或知识。
  • 无需花费数天甚至数月来创建 Web 应用,您只需几小时甚至几分钟就能做出非常漂亮的机器学习或数据科学应用。
  • 与大多数 Python 库兼容(如 pandas、matplotlib、seaborn、plotly、Keras、PyTorch、SymPy(latex))。
  • 用更少的代码即可创建惊艳的 Web 应用。
  • 数据缓存可简化并加速计算管道。

如何使用 Streamlit

安装 Streamlit

首先进行安装:

在 Windows 上:

1. 安装 Anaconda 并创建您的环境

2. 打开终端

Install Streamlit 1

3. 在终端中输入以下命令安装 Streamlit:

pip install streamlit

4. 测试安装是否成功:

streamlit hello
Install Streamlit 2

当您在终端中输入该命令时,下方页面应会自动打开:

Install Streamlit 3

在 macOS 上:

1. 安装 pip:

python3 -m ensurepip --upgrade

2. 安装 pipenv:

pip3 install pipenv

3. 创建您的环境。打开项目文件夹:

cd project_folder_name

4. 创建一个 pipenv 环境:

pipenv shell

5. 输入以下命令安装 Streamlit:

pip install streamlit

测试安装是否成功:

streamlit hello

在 Linux 上:

1. 安装 pip:

sudo apt-get install python3-pip

2. 安装 pipenv:

pip3 install pipenv

3. 创建您的环境。打开项目文件夹:

cd project_folder_name

4. 创建一个 pipenv 环境:

pipenv shell

5. 输入以下命令安装 Streamlit

pip install streamlit

6. 测试安装是否成功:

streamlit hello

如何运行您的 Streamlit 代码

streamlit run file_name.py
How to run your Streamlit code

Streamlit 命令易写易懂。只需一个简单命令,您就能显示文本、媒体、控件、小部件、图表等。

使用 Streamlit 显示文本

这里我将向您展示如何在 Streamlit 应用中添加文本,以及可用的不同命令。

st.write():用于向 Web 应用添加任何内容,从格式化字符串到 matplotlib 图表、Altair 图表、plotly 图形、数据框、Keras 模型等。

import streamlit as stst.write("Hello ,let's learn how to build a streamlit app together")
Display texts with Streamlit

st.title():用于添加应用标题。st.header():用于设置分区的标题。st.markdown():用于设置分区的 Markdown。st.subheader():用于设置分区的小标题。st.caption():用于编写说明文字。st.code():用于展示代码。st.latex():用于显示按 LaTeX 格式排版的数学表达式。

import streamlit as stst.title("This is the app title")st.header("This is the header")st.markdown("This is the markdown")st.subheader("This is the subheader")st.caption("This is the caption")st.code("x = 2021")st.latex(r''' a+a r^1+a r^2+a r^3 ''')
Display texts with Streamlit 2

使用 Streamlit 显示图像、视频或音频文件

很难找到像 Streamlit 这样简单的函数来显示图像、视频和音频文件。让我们看看如何用 Streamlit 展示媒体!

st.image():用于显示图像。st.audio():用于显示音频。st.video():用于显示视频。

st.image("kid.jpg", caption="A kid playing")st.audio("audio.mp3")st.video("video.mp4")
Display an image, video or audio file with Streamlit

输入小部件

小部件是最重要的用户界面组件。Streamlit 提供多种小部件,允许您通过按钮、滑块、文本输入等将交互直接嵌入到应用中。

st.checkbox():返回布尔值。勾选时返回 True,否则返回 False。st.button():用于显示按钮小部件。st.radio():用于显示单选按钮小部件。st.selectbox():用于显示选择框小部件。st.multiselect():用于显示多选小部件。st.select_slider():用于显示选择滑块小部件。st.slider():用于显示滑块小部件。

st.checkbox('Yes')st.button('Click Me')st.radio('Pick your gender', ['Male', 'Female'])st.selectbox('Pick a fruit', ['Apple', 'Banana', 'Orange'])st.multiselect('Choose a planet', ['Jupiter', 'Mars', 'Neptune'])st.select_slider('Pick a mark', ['Bad', 'Good', 'Excellent'])st.slider('Pick a number', 0, 50)

st.number_input():用于显示数值输入小部件。st.text_input():用于显示文本输入小部件。st.date_input():用于显示日期输入小部件以选择日期。st.time_input():用于显示时间输入小部件以选择时间。st.text_area():用于显示可输入多行文本的文本输入小部件。st.file_uploader():用于显示文件上传小部件。st.color_picker():用于显示颜色选择器小部件以选择颜色。

st.number_input('Pick a number', 0, 10)st.text_input('Email address')st.date_input('Traveling date')st.time_input('School time')st.text_area('Description')st.file_uploader('Upload a photo')st.color_picker('Choose your favorite color')
t

使用 Streamlit 显示进度与状态

现在我们来看看如何在应用中添加进度条和状态消息(如错误与成功)。

st.balloons():用于显示庆祝气球。st.progress():用于显示进度条。st.spinner():用于在执行期间显示临时等待消息。

st.balloons()  # Celebration balloonsst.progress(10)  # Progress barwith st.spinner('Wait for it...'):    time.sleep(10)  # Simulating a process delay
Display progress and status with Streamlit 1

st.success():用于显示成功消息。st.error():用于显示错误消息。st.warning():用于显示警告消息。st.info():用于显示信息消息。st.exception():用于显示异常消息。

st.success("You did it!")st.error("Error occurred")st.warning("This is a warning")st.info("It's easy to build a Streamlit app")st.exception(RuntimeError("RuntimeError exception"))
Display progress and status with Streamlit 2

您还可以在页面上创建侧边栏或容器来组织应用。应用中的页面层级与布局会对用户体验产生很大影响。通过组织内容,您能帮助访问者理解并导航站点,帮助他们找到所需内容,并提升未来回访的可能性。

将元素传给 st.sidebar() 会将该元素固定在左侧,使用户可以专注于应用主体内容。

但 st.spinner() 和 st.echo() 不支持与 st.sidebar 一起使用。

如您所见,您可以在应用界面中创建侧边栏,并将元素放入其中,使应用更有条理、更易理解。

st.sidebar.title("Sidebar Title")st.sidebar.markdown("This is the sidebar content")
Sidebar

容器

st.container() 用于创建一个不可见的容器,您可以将元素放入其中,以构建有用的布局与层级。

with st.container():    st.write("This is inside the container")
Container

使用 Streamlit 显示图表

Streamlit 可与流行的 Python 可视化库集成。以下是开箱即用的制图函数:

st.pyplot():用于显示 matplotlib.pyplot 图形。

import streamlit as stimport matplotlib.pyplot as pltimport numpy as nprand = np.random.normal(1, 2, size=20)fig, ax = plt.subplots()ax.hist(rand, bins=15)st.pyplot(fig)
This function is used to display a line chart.

st.line_chart():用于显示折线图。

import streamlit as stimport pandas as pdimport numpy as npdf = pd.DataFrame(np.random.randn(10, 2), columns=['x', 'y'])st.line_chart(df)
This function is used to display a bar chart.

st.bar_chart():用于显示条形图。

import streamlit as stimport pandas as pdimport numpy as npdf = pd.DataFrame(np.random.randn(10, 2), columns=['x', 'y'])st.bar_chart(df)
This function is used to display an area chart.

st.area_chart():用于显示面积图。

import streamlit as stimport pandas as pdimport numpy as npdf = pd.DataFrame(np.random.randn(10, 2), columns=['x', 'y'])st.area_chart(df)
This function is used to display an altair chart.

st.altair_chart():用于显示 Altair 图表。

import streamlit as stimport pandas as pdimport numpy as npimport altair as altdf = pd.DataFrame(np.random.randn(500, 3), columns=['x', 'y', 'z'])chart = alt.Chart(df).mark_circle().encode(    x='x', y='y', size='z', color='z', tooltip=['x', 'y', 'z'])st.altair_chart(chart, use_container_width=True)
This function is used to display graph objects, which can be completed using different nodes and edges.

st.graphviz_chart():用于显示图(graph)对象,可用不同节点和边进行构建。

import streamlit as stimport graphvizst.graphviz_chart('''    digraph {        Big_shark -> Tuna        Tuna -> Mackerel        Mackerel -> Small_fishes        Small_fishes -> Shrimp    }''')
This function is used to display maps in the app. However, it requires the values of latitude and longitude and these values should not be null/NA.

使用 Streamlit 显示地图

st.map():用于在应用中显示地图。但需要提供纬度与经度值,且这些值不能为 null/NA。

import pandas as pdimport numpy as npimport streamlit as stdf = pd.DataFrame(    np.random.randn(500, 2) / [50, 50] + [37.76, -122.4], columns=['lat', 'lon'])st.map(df)
Display maps with Streamlit 1

主题

您还可以选择符合您风格的主题。按照下方 GIF 的步骤操作:

Display maps with Streamlit 2

如果您想进一步了解样式与主题,请参阅 Theming。

现在,是时候一起构建一个应用了!

使用 Streamlit 构建机器学习应用

本节我将带您走一遍我做过的一个关于贷款预测的项目。

贷款的主要利润直接来自贷款利息。贷款公司在对借款人进行严格核验与验证流程后发放贷款。然而,他们仍无法确保申请人是否能毫无困难地偿还贷款。在本教程中,我们将构建一个预测模型(随机森林分类器)来预测申请人的贷款状态。我们的任务是准备一个 Web 应用,使其可用于生产环境。

首先导入我们应用所需的库:

import streamlit as stimport pandas as pdimport numpy as npimport pickle  # to load a saved modelimport base64  # to handle gif encoding

在这个应用中,我们将在侧边栏菜单中使用多个小部件,如滑块、选择框与单选按钮,并为此准备一些 Python 函数。该示例是一个包含两页的简单演示。在首页(Home)中,会展示我们选择的数据;而 Exploration 页面将允许您通过图表可视化变量;Prediction 页面包含变量与一个名为 Predict 的按钮,允许您估计贷款状态。下方代码会在侧边栏提供一个选择框,以选择页面。数据会被缓存,从而无需反复加载。

@st.cache_data 是推荐使用的缓存装饰器(替代已弃用的 @st.cache),可在从网络加载数据、处理大型数据集或执行高开销计算时保持应用性能。对可序列化数据(如 DataFrame 和字符串)使用 @st.cache_data,对全局资源(如数据库连接或 ML 模型)使用 @st.cache_resource。

@st.cache_datadef get_fvalue(val):    feature_dict = {"No": 1, "Yes": 2}    return feature_dict[val]def get_value(val, my_dict):    return my_dict[val]
Build a machine learning application

在 Home 页面,我们将可视化:展示图片 / 数据集 / 申请人收入与贷款金额的直方图。

注意:我们将使用 if/elif/else 在页面间切换。

我们会将 loan_dataset.csv 加载到变量 data 中,以便在 Home 页面展示其部分行。

if app_mode == 'Home':    st.title('Loan Prediction')    st.image('loan_image.jpg')    st.markdown('Dataset:')    data = pd.read_csv('loan_dataset.csv')    st.write(data.head())    st.bar_chart(data[['ApplicantIncome', 'LoanAmount']].head(20))
Build a machine learning application 2

接着在 Prediction 页面:

if app_mode == 'Prediction':    ApplicantIncome = st.sidebar.slider('ApplicantIncome', 0, 10000, 0)    LoanAmount = st.sidebar.slider('LoanAmount in K$', 9.0, 700.0, 200.0)    # Assuming additional input features here...    # Prediction Logic    if st.button("Predict"):        loaded_model = pickle.load(open('Random_Forest.sav', 'rb'))        prediction = loaded_model.predict(np.array([ApplicantIncome, LoanAmount]).reshape(1, -1))        if prediction[0] == 0:            st.error('According to our calculations, you will not get the loan.')        else:            st.success('Congratulations! You will get the loan.')

我们编写了两个函数 get_value(val,my_dict) 和 get_fvalue(val),以及字典 feature_dict,用于在 st.sidebar.radio() 中处理非数值变量。这是可选的,您也可以轻松地这样做:

Build a machine learning application 3

让我们看看这样做的原因。

注意:机器学习算法无法直接处理分类变量。在数据集中,我做了一些特征工程。比如列 Married 有两个取值 “Yes” 和 “No”,我做了标签编码(可参考以获得更好理解),令 "NO" 等于 1、"Yes" 等于 2。函数 get_fvalue(val) 将根据客户选择轻松返回相应取值(1/2)。函数 get_value(val,my_dict) 也是如此。两者的区别在于,前者用于是/否特征,后者用于一般情形(例如:Gender)。

如我们所见,变量 Dependents 有四个类别 '0'、'1'、'2' 和 '3+',我们无法将其直接转换为一个数值变量,并且 '+3' 表示 Dependents 可以取 3、4、5……我们进行了独热编码(可参考以获得更好理解)。因此,我们创建了一个包含这四个元素的侧边栏单选按钮,每个元素对应一个二元变量,若客户选择 '0',则 class_0 等于 1,其他等于 0。

Build a machine learning application 4

我们还对 Property_Area 进行了独热编码,因此创建了 3 个变量(Rural、Urban、Semiurban)。当 Rural 取 1 时,其他将取 0。

Build a machine learning application 4

因此我们已经了解了两种情况——当我们对特征进行标签编码或独热编码时,如何处理它们以成功创建可运行的 Streamlit 应用。

 data1={    'Gender':Gender,    'Married':Married,    'Dependents':[class_0,class_1,class_2,class_3],    'Education':Education,    'ApplicantIncome':ApplicantIncome,    'CoapplicantIncome':CoapplicantIncome,    'Self Employed':Self_Employed,    'LoanAmount':LoanAmount,    'Loan_Amount_Term':Loan_Amount_Term,    'Credit_History':Credit_History,    'Property_Area':[Rural,Urban,Semiurban],    }    feature_list=[ApplicantIncome,CoapplicantIncome,LoanAmount,Loan_Amount_Term,Credit_History,get_value(Gender,gender_dict),get_fvalue(Married),data1['Dependents'][0],data1['Dependents'][1],data1['Dependents'][2],data1['Dependents'][3],get_value(Education,edu),get_fvalue(Self_Employed),data1['Property_Area'][0],data1['Property_Area'][1],data1['Property_Area'][2]]    single_sample = np.array(feature_list).reshape(1,-1)

现在我们会将变量存入字典,因为我们编写了 get_value(val,my_dict) 与 get_fvalue(val) 来处理字典。之后,输入——也就是客户在我们的 Streamlit 应用中选择的内容——将被整理到名为 feature_list 的列表中,然后转换为名为 single_sample 的 numpy 变量。

注意:特征的输入顺序必须与数据集列的顺序一致(例如 Married 不能使用 Gender 的输入)。

 if st.button("Predict"):        file_ = open("6m-rain.gif", "rb")        contents = file_.read()        data_url = base64.b64encode(contents).decode("utf-8")        file_.close()        file = open("green-cola-no.gif", "rb")        contents = file.read()        data_url_no = base64.b64encode(contents).decode("utf-8")        file.close()        loaded_model = pickle.load(open('Random_Forest.sav', 'rb'))        prediction = loaded_model.predict(single_sample)        if prediction[0] == 0 :            st.error(    'According to our Calculations, you will not get the loan from Bank'    )            st.markdown(    f'<img src="data:image/gif;base64,{data_url_no}" alt="cat gif">',    unsafe_allow_html=True,)        elif prediction[0] == 1 :            st.success(    'Congratulations!! you will get the loan from Bank'    )            st.markdown(    f'<img src="data:image/gif;base64,{data_url}" alt="cat gif">',    unsafe_allow_html=True,    )

最后,我们会将已保存的 RandomForestClassifier 模型加载到 loaded_model,其预测(分类问题,取 0 或 1)存入 prediction。两个 .gif 文件将分别存入 file 与 file_。根据 prediction 的取值,我们将有两种情况:“成功”或“失败”的放贷结果。

以下是我们的 Prediction 页面:

Build a machine learning application 5

若为失败(FAILURE),输出如下所示:

Build a machine learning application 5

若为成功(SUCCESS),输出如下所示:

Build a machine learning application 6

如何部署 Streamlit 应用

部署是将应用从开发者交付给用户的机制。

部署应用是将特定应用复制、配置并启用到特定基础 URL 的过程。部署完成后,应用即可在该基础 URL 上公开访问。服务器通过两步来完成此过程:首先进行预备(staging),随后在预备成功后激活(activating)。

让我们来学习如何部署 Streamlit 应用!

在尝试部署应用之前,您需要在 GitHub 上创建一个新仓库,并将应用代码与依赖项放入其中。

How to deploy a Streamlit app 1
How to deploy a Streamlit app 2
How to deploy a Streamlit app 3
How to deploy a Streamlit app 4
How to deploy a Streamlit app 5

然后点击提交更改(commit changes)以保存:

How to deploy a Streamlit app 6

创建仓库并上传文件后,您需要创建一个名为 requirements 的新文件,并把应用使用到的库写入其中。

首先,点击创建新文件。

How to deploy a Streamlit app 6
How to deploy a Streamlit app 7

现在您距离部署应用只差一步,访问这个链接即可。

然后按照以下步骤进行:

How to deploy a Streamlit app 8
How to deploy a Streamlit app 9
How to deploy a Streamlit app 10

点击 Deploy,稍等片刻!

浏览器会自动打开一个页面!这个页面就是您用 Streamlit 实现的项目应用。

恭喜,您已成功部署应用!点击此处查看已部署的应用。

更多文档,请访问:docs.streamlit.io

Streamlit 常见问题

Streamlit 与 Django 或 Flask 等其他 Python Web 框架有何不同?

与 Flask 或 Django 等其他 Python Web 框架不同,Streamlit 专注于简洁与速度。您可以用最少的代码创建交互式应用,非常适合不想花时间学习 Web 开发、但仍需要功能完善且专业外观应用的用户。

使用 Streamlit 是否需要懂 HTML 或 CSS?

不需要,使用 Streamlit 无需掌握 HTML、CSS 或 JavaScript。您只用 Python 就能创建功能完整的应用。

哪些 Python 库与 Streamlit 兼容?

Streamlit 与许多流行的 Python 库兼容,如 Pandas、NumPy、Matplotlib、Plotly、Altair、Keras、TensorFlow 和 PyTorch。这使得将数据科学工作流集成到应用中变得非常容易。

Streamlit 2024 有哪些新功能?

Streamlit 2024 引入了多项新功能,包括增强的主题、新小部件(如表单)以及缓存改进。务必查阅文档以充分利用这些新特性。

主题