赞
踩
今天详解一个 Python 库 Streamlit,它可以为机器学习和数据分析构建 web app。它的优势是入门容易、纯 Python 编码、开发效率高、UI精美。
上图是用 Streamlit 构建自动驾驶模型效果的 demo,左侧是模型的参数,右侧是模型的效果。通过调整左侧参数,右边的模型会实时地响应。
由此可以看出,对于交互式的数据可视化需求,完全可以考虑用 Streamlit 实现。特别是在学习、工作汇报的时候,用它的效果远好于 PPT。
因为 Streamlit 提供了很多前端交互的组件,所以也可以用它来做一些简单的web 应用。今天我们也会用它来做个垃圾分类的 web app。
我使用的是 Python 3.8 环境,执行 pip install streamlit 安装。安装后执行 streamlit hello 检查是否安装成功。
先来了解下 Streamlit 最基础的文本组件。
文本组件是用来在网页展示各种类型的文本内容。Streamlit 可以展示纯文本、Markdown、标题、代码和LaTeX公式。
- import streamlit as st
-
- # markdown
- st.markdown('Streamlit is **_really_ cool**.')
-
- # 设置网页标题
- st.title('This is a title')
-
- # 展示一级标题
- st.header('This is a header')
-
- # 展示二级标题
- st.subheader('This is a subheader')
-
- # 展示代码,有高亮效果
- code = '''def hello():
- print("Hello, Streamlit!")'''
- st.code(code, language='python')
-
- # 纯文本
- st.text('This is some text.')
-
- # LaTeX 公式
- st.latex(r'''
- a + ar + a r^2 + a r^3 + \cdots + a r^{n-1} =
- \sum_{k=0}^{n-1} ar^k =
- a \left(\frac{1-r^{n}}{1-r}\right)
- ''')

上述是 Streamlit 支持的文本展示组件,代码存放 my_code.py 文件中。编码完成后,执行 streamlit run my_code.py ,streamlit 会启动 web 服务,加载指定的源文件。
启动后,可以看到命令行打印以下信息
- streamlit run garbage_classifier.py
-
- You can now view your Streamlit app in your browser.
-
- Local URL: http://localhost:8501
- Network URL: http://192.168.10.141:8501
在浏览器访问 http://localhost:8501/ 即可。
当源代码被修改,无需重启服务,在页面上点击刷新按钮就可加载最新的代码,运行和调试都非常方便。
dataframe 和 table 组件可以展示表格。
- import streamlit as st
- import pandas as pd
- import numpy as np
- df = pd.DataFrame(
- np.random.randn(50, 5),
- columns=('col %d' % i for i in range(5)))
-
- # 交互式表格
- st.dataframe(df)
- # 静态表格
- st.table(df)
dateframe 和 table 的区别是,前者可以在表格上做交互(如:排序),后者只是静态的展示。它们支持展示的数据类型包括 pandas.DataFrame、pandas.Styler、pyarrow.Table、numpy.ndarray、Iterable、dict。
metric 组件用来展
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。