来源丨网络

作者丨wedo实验君

1. Streamlit

一句话,Streamlit是一个可以用python编写web app的库,可以方便的动态展示你的机器学习的项目。

优点

  • 你不需要懂html, css, js等,纯python语言编写web app

  • 包括web常用组件:文本框, 按钮,单选框,复选框, 下拉框,多媒体(图片,视频)和文件上传等

应用场景

  • 可以动态的探索数据

  • 可以方便动态展示你的机器学习成果(可以和jupyter notebook做个比较)

https://github.com/streamlit/streamlit

2. 安装

pip install streamlit
streamlit hello# 启动web app
# streamlit run [filename]
streamlit run app.py# You can now view your Streamlit app in your browser.
# Local URL: http://localhost:8501

3. 基本组件介绍

3.1 布局

web中通常有布局layout css, 如Bootstrap中的12列删格系统;streamlit最多只有左右两栏,通常是一栏。通过st.sidebar添加侧边栏,通常可作为菜单,选择控制操作。在上下结构上,streamlit按照代码顺序从上到下,依次布局。

import streamlit as st
import numpy as np
import time
import pandas as pd
import datetime
# 侧边栏
st.sidebar.title('菜单侧边栏')
add_selectbox = st.sidebar.selectbox("这个是下拉框,请选择?",("1", "Home 2", "Mobile 2")
)
# 主栏
st.title('Steamlit 机器学习web app')

3.2 text

streamlit提供了许多文本显示命令,还支持markdown语法

st.header('1. text文本显示')
st.markdown('Streamlit is **_really_ cool**.')
st.text('This is some text.')
st.subheader('This is a subheader')
st.write("st.write 可以写很多东西哦")
st.warning('This is a warning')

3.3 表单控件

streamlit提供丰富的表单控件,如按钮,单选框,复选框,下拉框,文本框和文件上传。用法提炼如下:

  • 函数调用为定义显示控件,返回值是表示是否触发,或者触发返回结果;比如按钮,st.button('Say hello')定义了一个按钮, 如果按下按钮返回True,否则为False

st.markdown('- 按钮')
if st.button('Say hello'):st.write('Why hello there')st.markdown('- 单选框')
genre = st.radio("选择你喜欢的?",('Comedy', 'Drama', 'Documentary'))st.write('你选择了:', genre)st.markdown('- 复选框')
agree = st.checkbox('I agree')
if agree:st.write('感谢你同意了')st.markdown('- 下拉框')
option = st.selectbox('你喜欢的联系方式?',('Email', 'Home phone', 'Mobile phone'))st.write('你选择了:', option)st.markdown('- 多选下拉框')
options = st.multiselect('What are your favorite colors',['Green', 'Yellow', 'Red', 'Blue'],['Yellow', 'Red'])st.write('你选择了:', options)st.markdown('- slider')
values = st.slider('Select a range of values',0.0, 100.0, (25.0, 75.0))
st.write('Values:', values)st.markdown('- 文本输入')
title = st.text_input('Movie title', 'Life of Brian')
st.write('The current movie title is', title)txt = st.text_area('Text to analyze', '''It was the best of times, it was the worst of times, it wasthe age of wisdom, it was the age of foolishness, it wasthe epoch of belief, it was the epoch of incredulity, itwas the season of Light, it was the season of Darkness, itwas the spring of hope, it was the winter of despair, (...)''')st.markdown('- 日期与时间')
d = st.date_input("生日",datetime.date(2019, 7, 6))
st.write('Your birthday is:', d)t = st.time_input('闹钟', datetime.time(8, 45))
st.write('闹钟为:', t)st.markdown('- 上传文件')
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:data = pd.read_csv(uploaded_file)st.write(data)

3.4 图像

常用的图像库都支持,通过st.image展示图片

import cv2
img = cv2.imread('sunrise.jpg')
st.image(img[...,::-1], caption='Sunrise by the mountains',use_column_width=True)

3.5 图表

  • 支持pandas中的dataframe展示图表(折线图,面积图和柱状图)

st.subheader('4.1 dataframe图表')
@st.cache(persist=True)
def get_data():df = pd.DataFrame(np.random.randn(200, 3),columns=['a', 'b', 'c'])return df
df = get_data()
# st.table(df)
st.dataframe(df)
st.line_chart(df)
st.area_chart(df)
st.bar_chart(df)
  • 还支持matplotlib的图表展示,这个你应该很熟悉

plt.plot(df.a, df.b)
st.pyplot()

3.6 缓存

streamlit中数据的缓存使用st.cache装饰器来修饰, 注意是作用于函数。缓存的好处顾名思义就是避免每次刷新的时候都要重新加载数据。

@st.cache(persist=True)
def get_data():df = pd.DataFrame(np.random.randn(200, 3),columns=['a', 'b', 'c'])return df

4. 动态数据demo

import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# 侧边栏
st.sidebar.title('请选择过滤条件')
time = st.sidebar.time_input('大于时间', datetime.time(1, 0))values = st.sidebar.slider('速度',0.0, 200.0, (25.0, 75.0))
# 主栏
st.title('数据探索')
@st.cache(persist=True)
def get_data():file = './7000.csv'return pd.read_csv(file, header=0)
data = get_data()
# print(values)
display_data = data[data['time'] > str(time)]
display_data = display_data[(display_data['速度'] > values[0]) & (display_data['速度'] < values[1])]
st.line_chart(display_data[['方向', '速度']])

5. 机器视觉项目demo

这个例子我们用人脸检测来说明下机器视觉项目的展示。

  • 功能:上传一张图片,检测出人脸框

  • 人脸检测算法来自facenet项目https://github.com/davidsandberg/facenet/tree/master/src/align中的MTCNN算法

  • 布局为左右布局,左边为上传空间, 右边是展示

import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import time
import pandas as pd
import datetime
import cv2
from PIL import Image
import io
from face_detect.mtcnn_tf import MTCNN# 侧边栏
st.sidebar.title('请上传一张照片,开始检测')
uploaded_file = st.sidebar.file_uploader("", type="jpg")# 主栏
st.title('人脸检测')
@st.cache()
def init_model():mtcnn = MTCNN()return mtcnndetect = init_model()
if uploaded_file is not None:# print(uploaded_file)data = np.array(Image.open(io.BytesIO(uploaded_file.read())))_, bboxs, _, _ = detect.run(data, detect_multiple_faces=True, margin=0)# display bbox and landmarksfor idx, landmark in enumerate(landmarks):bbox = bboxs[idx]cv2.rectangle(data, (bbox[1], bbox[0]),(bbox[3], bbox[2]), (0, 2255, 0), 2)st.image(data, caption='image', use_column_width=False)

6. 总结

是不是觉得很方便,分分钟就可以构建一个web app来展示你的项目。希望对你有帮助, 快动起手来吧! 摘要如下:

  • 数据记得要用缓存@st.cache()

  • streamlit可以支持matplotlib

  • streamlit有漂亮的表单控件,函数的返回值就是触发的值

  • streamlit支持markdown

官方提供了其他复杂的demo(官方推荐用函数的方式的封装业务,这里也推荐, 本文主要是为了说明功能,采用比较直观的方式来编写)

  • https://github.com/streamlit/demo-face-gan

  • https://github.com/streamlit/demo-self-driving

技术

Python多层级索引的数据分析

资讯

红帽、Docker、SUSE在俄停服

技术

太强了!Python开发桌面小工具

技术

一行Python代码能干嘛?来看!

分享

点收藏

点点赞

点在看

Python 快速生成 web 动态展示机器学习项目!相关推荐

  1. 快速生成 web app 动态展示机器学习项目

    1. Streamlit 一句话,Streamlit是一个可以用python编写web app的库,可以方便的动态展示你的机器学习的项目. 优点 你不需要懂html, css, js等,纯python ...

  2. 一个自动生成web和微服务项目代码工具sponge

    sponge 是一个快速生成web和微服务项目代码工具,也是一个基于gin和grpc封装的微服务框架.sponge拥有丰富的生成代码命令,一共生成12种不同功能代码,这些功能代码可以组合成完整的服务( ...

  3. python︱写markdown一样写网页,代码快速生成web工具:streamlit 展示组件(三)

    系列参考: python︱写markdown一样写网页,代码快速生成web工具:streamlit介绍(一) python︱写markdown一样写网页,代码快速生成web工具:streamlit 重 ...

  4. python︱写markdown一样写网页,代码快速生成web工具:streamlit 数据探索案例(六)

    系列参考: python︱写markdown一样写网页,代码快速生成web工具:streamlit介绍(一) python︱写markdown一样写网页,代码快速生成web工具:streamlit 重 ...

  5. python︱写markdown一样写网页,代码快速生成web工具:streamlit 缓存(五)

    系列参考: python︱写markdown一样写网页,代码快速生成web工具:streamlit介绍(一) python︱写markdown一样写网页,代码快速生成web工具:streamlit 重 ...

  6. python︱写markdown一样写网页,代码快速生成web工具:streamlit lay-out布局(四)

    文章目录 1 `streamlit.beta_container()` 2 分列展示 3 按照比例分列展示 4 折叠/展开 系列参考: python︱写markdown一样写网页,代码快速生成web工 ...

  7. python︱写markdown一样写网页,代码快速生成web工具:streamlit 重要组件介绍(二)

    python︱写markdown一样写网页,代码快速生成web工具:streamlit(一) 上篇主要是steamlit的介绍以及streamlit的一些初始化,这篇是一些组件的介绍,当然风格是直接上 ...

  8. 代码生成工具更新--快速生成Winform框架的界面项目

    在之前版本的代码生成工具Database2Sharp中,由于代码生成都是考虑Winform和Web通用的目的,因此Winform界面或者Web界面都是单独生成的,在工具中生成相应的界面后,复制到项目里 ...

  9. 除了 Python ,这些语言写的机器学习项目也很牛(二)

    2019独角兽企业重金招聘Python工程师标准>>> Python 由于本身的易用优势和强大的工具库储备,成为了在人工智能及其它相关科学领域中最常用的语言之一.尤其是在机器学习,已 ...

最新文章

  1. Python数据科学-技术详解与商业实践视频教程
  2. insightface mxnet训练 out of Memory
  3. shell中join链接多个域_shell 如何实现两个表的join操作
  4. php+icu+库是什么意思,如何从PHP Intl(ICU库)中的货币代码获取货币符号
  5. 编译程序提示配置PKG_CONFIG_PATH
  6. 怎么判断前轮左右的位置_新手开车技巧,确定前轮位置,准确判断与障碍物距离...
  7. WebPager For ASP.NET (基于ASP.NET的数据分页控件)
  8. 程序员为什么要写博客?怎么写博客?
  9. 多源数据融合算法综述
  10. sim868 建立tcp链接时的步骤所对应hex码
  11. 我是一个粉刷匠用计算机弹,《我是一个粉刷匠》,钢琴双手弹的谱子,,,急用,,,谢谢...
  12. android动态修改桌面图标,Android动态更换桌面图标
  13. Ubuntu18.04+TITAN XP+anaconda+cuda10+cudnn+pytorch
  14. 企业上云,安全合规如何进阶 ——一文拆解亚马逊云科技云安全理念与实践
  15. 联想i5无线网无法连接服务器,联想笔记本不能连接无线网的解决方法
  16. 实现用户注册功能的代码
  17. 不同计算机的操作码完全相同,2012年计算机一级考试B试题及答案二
  18. k8s学习笔记——ceph rbd本地手动挂载
  19. QQRobot一款基于Java的娱乐qq机器人
  20. Python库下载安装教程

热门文章

  1. 自动化测试selenium+java学习笔记
  2. RLCenter云平台配置中心
  3. ATLAS入门篇之CascadingDropDown控件编程
  4. ArcEngine的ToolbarControl解析
  5. sql server时间转换
  6. Python fabric实现远程操作和部署
  7. 谭浩强《C++程序设计》书后习题 第十三章-第十四章
  8. Linux supervisor守护进程的安装和使用
  9. linux+用户的shell,Linux用户管理(十)Linux Shell高级
  10. python 多级递归_Python文件目录和系统操作,os模块和os.path模块