Streamlit 是一款专注于机器学习和数据分析团队的应用开发框架。它提供了一种快速构建自定义机器学习工具的方式,有望在某些方面取代 Flask 在机器学习项目中的作用。借助 Streamlit,机器学习工程师能够迅速开发出用户友好的交互工具。
1、Hello World 示例
Streamlit 应用程序本质上是 Python 脚本,无需复杂的设置过程。你可以通过简单的函数调用来实现应用的功能。比如,要展示 "Hello, world!" 的文本,只需要几行代码:
python
import streamlit as st
st.write("Hello, world!")
2、使用 UI 组件
Streamlit 将 UI 组件视为变量,每个交互都以简单的方式返回值,这样可以保持代码简洁明了:
python
import streamlit as st
x = st.slider("选择一个数字")
st.write(x, "的平方是", x * x)
3、数据重用与高效计算
当你需要处理大量数据或执行复杂计算时,如何高效地利用资源变得尤为重要。Streamlit 引入了缓存机制,可以安全且方便地重复使用数据。例如,从 Udacity 自动驾驶项目中下载数据仅需一次:
```python import streamlit as st import pandas as pd
@st.cache def loaddata(url): return pd.readcsv(url, nrows=1000)
BUCKET = "https://streamlit-self-driving.s3-us-west-2.amazonaws.com/" data = load_data(BUCKET + "labels.csv.gz")
labelchoice = st.selectbox("筛选:", ["car", "truck"]) filtereddata = data[data["label"] == labelchoice] st.write(filtereddata) ```
Streamlit 的工作原理大致如下: - 用户每次互动都会触发整个脚本的重新运行。 - UI 组件的当前状态被用来更新变量的值。 - 缓存机制避免了数据请求和计算过程的重复执行。
4、实例:自动驾驶数据集工具
这是一个使用 Streamlit 构建的小型应用程序,用户可以通过这个工具在 Udacity 提供的自动驾驶车辆图像数据集上执行语义搜索、查看人工标注结果,并实时运行 YOLO 目标检测算法:
```python import streamlit as st import cv2 import numpy as np import urllib.request
weightsurl = "https://pjreddie.com/media/files/yolov3.weights" configurl = "https://raw.githubusercontent.com/pjreddie/darknet/master/cfg/yolov3.cfg" classnamesurl = "https://raw.githubusercontent.com/pjreddie/darknet/master/data/coco.names"
weightspath = "yolov3.weights" configpath = "yolov3.cfg" classnamespath = "coco.names"
urllib.request.urlretrieve(weightsurl, weightspath) urllib.request.urlretrieve(configurl, configpath) urllib.request.urlretrieve(classnamesurl, classnamespath)
net = cv2.dnn.readNet(weightspath, configpath)
with open(classnamespath, "r") as f: classes = [line.strip() for line in f.readlines()]
imageurl = st.textinput("请输入图片URL:") if imageurl: imgarray = np.asarray(bytearray(urllib.request.urlopen(imageurl).read()), dtype=np.uint8) img = cv2.imdecode(imgarray, -1)
# 前向传播
blob = cv2.dnn.blobFromImage(img, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
outputs = net.forward(output_layers)
# 解析输出
boxes = []
confidences = []
class_ids = []
for output in outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
center_x = int(detection[0] * img.shape[1])
center_y = int(detection[1] * img.shape[0])
width = int(detection[2] * img.shape[1])
height = int(detection[3] * img.shape[0])
x = int(center_x - width / 2)
y = int(center_y - height / 2)
boxes.append([x, y, width, height])
confidences.append(float(confidence))
class_ids.append(class_id)
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 显示结果
for i in indices:
box = boxes[i]
x, y, w, h = box
label = str(classes[class_ids[i]])
st.image(img[y:y+h, x:x+w], caption=label)
```
如果你想体验 Streamlit,可以通过以下命令安装并启动它:
sh
pip install --upgrade streamlit
streamlit hello
安装完成后,你可以在浏览器中访问 http://localhost:8501
查看你的 Streamlit 应用程序。