📓
Study
  • README
  • Application
    • Contest
      • 竞赛trick
  • Basic Know
    • 半监督学习
    • 贝叶斯
      • 朴素贝叶斯分类器
    • 对抗训练
    • 概率图模型
      • CRF
      • HMM
      • 概率图模型
    • 关联分析
    • 归纳偏置
      • [什么是 Inductive bias(归纳偏置)?](BasicKnow/归纳偏置/什么是 Inductive bias(归纳偏置)?.md)
    • 聚类
    • 决策树
    • 绿色深度学习
    • 树模型&集成学习
      • 提升树
      • Ada Boost
      • [集成学习]
    • 特征工程
      • 数据分桶
      • 特征工程概述
      • 特征选择
      • LDA
      • PCA
    • 线性模型
      • 感知机
      • 最大熵模型
      • SVM
        • SVM支持向量机
      • 逻辑回归
      • 线性回归
    • 优化算法
      • 拉格朗日对偶性
      • 牛顿法
        • 牛顿法&拟牛顿法
      • 梯度下降法
        • 梯度下降算法
      • 优化算法
    • 预处理
      • [1-1]正则表达式
      • [1-2]文本预处理
      • [1-3]词性
      • [1-4]语法分析
      • [1-6]文本分类
      • [1-7]网络爬取
      • 【备用】正则表达式
      • 7.re模块
      • 词典匹配
      • 分词
      • 子表达式
      • Todo
    • 主题模型
      • LDA
    • Deep Learning
      • 反向传播
      • 梯度消失&梯度爆炸
      • Batch Size
      • 1.DLbasis
      • 小概念
      • MLstrategy
      • CNN
      • RNN及其应用
      • 关于深度学习实践
      • 神经网络概述
      • Batch Normalization
      • Program CNN
      • Program D Lbasis
      • Program DN Nimprove
      • Program Neural Style Transfer
      • Summer DL
    • EM算法
    • GAN
      • Gans In Action Master
    • GNN
      • 搜广推之GNN
      • Representation Learning
        • Anomalydetection
        • Conclusion
        • Others
        • Papernotes
        • Recommadation
    • k近邻法
      • K近邻
    • Language Model
      • 语言模型解码采样策略
      • [1-1][语言模型]从N-gram模型讲起
      • [1-2][语言模型]NNLM(神经网络语言模型)
      • [1-3][语言模型]基于RNN的语言模型
      • [1-4][语言模型]用N-gram来做完形填空
      • [1-5][语言模型]用KenLM来做完形填空
    • Loss Function
      • 常用损失函数
      • Focal Loss
      • softmax+交叉熵
    • Machine Learning
      • [基础]概念
      • 待整合
      • 交叉验证
      • 无监督学习
      • 优缺点
      • ML Yearning
      • SVD
    • Statistics Math
      • 程序员的数学基础课
      • 数学基础
      • 统计&高数
      • 统计题目
      • 线性代数
      • 组合数学
      • Discrete Choice Model
      • Nested Choice Model
  • Course Note
    • 基于TensorFlow的机器学习速成课程
      • [Key ML Terminology](CourseNote/基于TensorFlow的机器学习速成课程/Key ML Terminology.md)
    • 集训营
      • 任务说明
      • 算法实践1.1模型构建
      • 算法实践1.2模型构建之集成模型
      • 算法实践2.1数据预处理
    • 李宏毅机器学习
      • 10DNN训练Tips
        • Chapter 18
      • 16无监督学习
        • Chapter 25
    • 贪心NLP
      • 贪心NLP笔记
    • Cs 224 N 2019
      • [A Simple But Tough To Beat Baseline For Sentence Embeddings](CourseNote/cs224n2019/A Simple but Tough-to-beat Baseline for Sentence Embeddings.md)
      • [Lecture 01 Introduction And Word Vectors](CourseNote/cs224n2019/Lecture 01 Introduction and Word Vectors.md)
      • [Lecture 02 Word Vectors 2 And Word Senses](CourseNote/cs224n2019/Lecture 02 Word Vectors 2 and Word Senses.md)
      • [Lecture 03 Word Window Classification Neural Networks And Matrix Calculus](CourseNote/cs224n2019/Lecture 03 Word Window Classification, Neural Networks, and Matrix Calculus.md)
      • [Lecture 04 Backpropagation And Computation Graphs](CourseNote/cs224n2019/Lecture 04 Backpropagation and Computation Graphs.md)
      • [Lecture 05 Linguistic Structure Dependency Parsing](CourseNote/cs224n2019/Lecture 05 Linguistic Structure Dependency Parsing.md)
      • [Lecture 06 The Probability Of A Sentence Recurrent Neural Networks And Language Models](CourseNote/cs224n2019/Lecture 06 The probability of a sentence Recurrent Neural Networks and Language Models.md)
      • Stanford NLP
    • Deep Learning Book Goodfellow
      • Books
        • Deep Learning Book Chapter Summaries Master
      • 提纲
      • C 5
      • C 6
      • [Part I Applied Math And Machine Learning Basics](CourseNote/Deep-Learning-Book-Goodfellow/Part I - Applied Math and Machine Learning basics.md)
    • Lihang
    • NLP实战高手课
      • 极客时间_NLP实战高手课
    • 工具&资料
    • 机器学习、深度学习面试知识点汇总
    • 七月kaggle课程
    • 算法工程师
    • 贪心科技机器学习必修知识点特训营
    • 唐宇迪机器学习
    • 语言及工具
    • AI技术内参
    • Suggestions
  • Data Related
    • 数据质量
      • 置信学习
    • 自然语言处理中的数据增广_车万翔
      • 自然语言处理中的数据增广
    • Mixup
    • 数据不均衡问题
    • 数据增强的方法
  • Knowledge Graph
    • Information Extraction
      • 联合抽取
        • PRGC
      • Code
        • BERT微调
      • NER
        • 阅读理解做NER
          • MRC
        • FLAT
        • Global Pointer
        • 命名实体识别NER
    • Keyword Extraction
      • 关键词抽取
    • 小米在知识表示学习的探索与实践
    • KG
  • Multi Task
    • EXT 5
      • Ex T 5
  • NLG
    • Dailogue
      • 比赛
        • 对话评估比赛
          • [simpread-DSTC10 开放领域对话评估比赛冠军方法总结](NLG/Dailogue/比赛/对话评估比赛/simpread-DSTC10 开放领域对话评估比赛冠军方法总结.md)
      • 任务型对话
        • DST
          • DST概述
        • NLG
          • NLG概述
        • NLU
          • NLU概述
        • 任务型对话概述
        • simpread-任务型对话系统预训练最新研究进展
      • 问答型对话
        • 检索式问答
          • 基于预训练模型的检索式对话系统
          • 检索式文本问答
        • 业界分享
          • 低资源场景下的知识图谱表示学习和问答_阿里_李杨
          • QQ浏览器搜索智能问答
        • 问答型对话系统概述
      • 闲聊型对话
        • 闲聊型对话系统概述
      • 业界分享
        • 人工智能与心理咨询
        • 腾讯多轮对话机器人
        • 微软小冰
        • 小布助手闲聊生成式算法
        • 美团智能客服实践_江会星
        • 去哪儿智能客服探索和实践
        • 实时语音对话场景下的算法实践_阿里_陈克寒
        • 智能语音交互中的无效query识别_小米_崔世起
        • UNIT智能对话
      • 主动对话
      • EVA
        • EVA分享
        • EVA模型
      • PLATO
      • RASA
    • Machine Translation
      • 业界分享
        • 爱奇艺台词翻译分享
      • Paper
        • Deep Encoder Shallow Decoder
    • RAGRelated
    • Text 2 SQL
      • M SQL
        • [M SQL 2](NLG/Text2SQL/M-SQL/M-SQL (2).md)
      • [Text2SQL Baseline解析](NLG/Text2SQL/Text2SQL Baseline解析.md)
      • Text 2 SQL
    • Text Summarization
      • [文本摘要][paper]CTRLSUM
      • 文本摘要
  • Pre Training
    • 业界分享
      • 超大语言模型与语言理解_黄民烈
        • 超大语言模型与语言理解
      • 大模型的加速算法_腾讯微信
        • 大模型的加速算法
      • 孟子轻量化预训练模型
      • 悟道文汇文图生成模型
      • 悟道文澜图文多模态大模型
      • 语义驱动可视化内容创造_微软
        • 语义驱动可视化内容创造
    • Base
      • Attention
      • Mask
        • NLP中的Mask
      • Position Encoding
        • 位置编码
    • BERT
      • ALBERT
      • Bert
        • Venv
          • Lib
            • Site Packages
              • idna-3.2.dist-info
                • LICENSE
              • Markdown-3.3.4.dist-info
                • LICENSE
              • Tensorflow
                • Include
                  • External
                    • Libjpeg Turbo
                      • LICENSE
                  • Unsupported
                    • Eigen
                      • CXX 11
                        • Src
                          • Tensor
              • Werkzeug
                • Debug
                  • Shared
                    • ICON LICENSE
        • CONTRIBUTING
        • Multilingual
      • Ro BER Ta
      • BERT
      • BERT面试问答
      • BERT源码解析
      • NSP BERT
    • BERT Flow
    • BERT Zip
      • Distilling The Knowledge In A Neural Network
      • TINYBERT
      • 模型压缩
    • CPM
    • CPT
      • 兼顾理解和生成的中文预训练模型CPT
    • ELECTRA
    • EL Mo
    • ERNIE系列语言模型
    • GPT
    • MBART
    • NEZHA
    • NLG Sum
      • [simpread-预训练时代下的文本生成|模型 & 技巧](Pre-training/NLGSum/simpread-预训练时代下的文本生成|模型 & 技巧.md)
    • Prompt
      • 预训练模型的提示学习方法_刘知远
        • 预训练模型的提示学习方法
    • T 5
      • Unified SKG
      • T 5
    • Transformer
    • Uni LM
    • XL Net
    • 预训练语言模型
    • BERT变种
  • Recsys
    • 多任务Multi-task&推荐
    • 推荐介绍
    • 推荐系统之召回与精排
      • 代码
        • Python
          • Recall
            • Deep Match Master
              • Docs
                • Source
                  • Examples
                  • FAQ
                  • Features
                  • History
                  • Model Methods
                  • Quick Start
    • 业界分享
      • 腾讯基于知识图谱长视频推荐
    • 召回
    • Sparrow Rec Sys
    • 深度学习推荐系统实战
    • 推荐模型
    • Deep FM
  • Search
    • 搜索
    • 业界分享
      • 爱奇艺搜索排序算法实践
      • 语义搜索技术和应用
    • 查询关键字理解
    • 搜索排序
    • BM 25
    • KDD21-淘宝搜索中语义向量检索技术
    • query理解
    • TFIDF
  • Self Supervised Learning
    • Contrastive Learning
      • 业界分享
        • 对比学习在微博内容表示的应用_张俊林
      • Paper
      • R Drop
      • Sim CSE
    • 自监督学习
  • Text Classification
    • [多标签分类(Multi-label Classification)](TextClassification/多标签分类(Multi-label Classification)/多标签分类(Multi-label Classification).md)
    • Fast Text
    • Text CNN
    • 文本分类
  • Text Matching
    • 文本匹配和多轮检索
    • CNN SIM
    • Word Embedding
      • Skip Gram
      • Glove
      • Word 2 Vec
    • 文本匹配概述
  • Tool
    • 埋点
    • 向量检索(Faiss等)
    • Bigdata
      • 大数据基础task1_创建虚拟机+熟悉linux
      • 任务链接
      • Mr
      • Task1参考答案
      • Task2参考答案
      • Task3参考答案
      • Task4参考答案
      • Task5参考答案
    • Docker
    • Elasticsearch
    • Keras
    • Numpy
    • Python
      • 可视化
        • Interactivegraphics
        • Matplotlib
        • Tkinter
        • Turtle
      • 数据类型
        • Datatype
      • python爬虫
        • Python Scraping Master
          • phantomjs-2.1.1-windows
        • Regularexp
        • Scrapying
        • Selenium
      • 代码优化
      • 一行代码
      • 用python进行语言检测
      • Debug
      • Exception
      • [Features Tricks](Tool/python/Features & Tricks.md)
      • Fileprocess
      • Format
      • Functional Programming
      • I Python
      • Magic
      • Math
      • Os
      • Others
      • Pandas
      • Python Datastructure
      • Python操作数据库
      • Streamlit
      • Time
    • Pytorch
      • Dive Into DL Py Torch
        • 02 Softmax And Classification
        • 03 Mlp
        • 04 Underfit Overfit
        • 05 Gradient Vanishing Exploding
        • 06 Text Preprocess
        • 07 Language Model
        • 08 Rnn Basics
        • 09 Machine Translation
        • 10 Attention Seq 2 Seq
        • 11 Transformer
        • 12 Cnn
        • 14 Batchnorm Resnet
        • 15 Convexoptim
        • 16 Gradientdescent
        • 17 Optim Advance
    • Spark
      • Pyspark
        • pyspark之填充缺失的时间数据
      • Spark
    • SQL
      • 数据库
      • Hive Sql
      • MySQL实战45讲
    • Tensor Flow
      • TensorFlow入门
  • Common
  • NLP知识体系
Powered by GitBook
On this page
  • 一、**Streamlit是什么?*
  • 二、如何开始一个Streamlit项目
  • 三、Streamlit架构与设计初探
  • 3.1 APP模型
  • 3.2 网页布局
  • 四、常用工具总结
  • 4.2 显示数据
  • 4.3 显示交互控件
  • 4.4 显示图表
  • 4.5 其他工具
  • 4.6 侧边栏
  • 五、重要功能
  • 5.1 缓存机制
  • 5.2 录屏功能
  • 六、近期重大**更新**
  • 七、优秀demo
  • 7.1 自动驾驶目标检测
  • 7.2 GAN面部生成项目

Was this helpful?

  1. Tool
  2. Python

Streamlit

一、**Streamlit是什么?*

Streamlit是一个强大的python开源工具包,可以用来快速搭建web app,以优雅地展示你的机器学习或数据科学项目。

二、如何开始一个Streamlit项目

在安装streamlit之前,需要注意python版本至少为3.6。使用pip安装streamlit库

$ pip install streamlit

在python脚本中导入包

import streamlit as st

启动一个streamlit app有两种方式(命令行)。

1)直接运行本地的python文件

$ streamlit run myapp.py

2)运行远程url,这个功能可以直接运行github中的链接

$ streamlit run https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/app.py

可以尝试运行以下命令启动官网提供的demo项目

$ streamlit hello

三、Streamlit架构与设计初探

在开始介绍streamlit提供的诸多小工具之前,需要简单介绍下streamlit的架构和布局设计思路。

3.1 APP模型

下图为官网展示的app模型架构图,一个streamlit app是这样工作的:

  • streamlit会将python脚本按顺序从上往下运行

  • 每次用户打开指向该app服务的网页时,整个脚本会被重新执行

  • 在脚本运行的过程中,streamlit会将数据表,图像,控件等实时地显示在网页上

  • 在运行过程中,streamlit会优先调用缓存(需要用户在程序中设置)避免高昂计算过程

  • 每次用户和控件进行交互时,脚本会被重新执行,图像,控件等被重新显示为新的值

3.2 网页布局

Streamlit的布局结构十分简单(这既是它的优点,也是它的缺点)。和bootstrap等前端框架中的复杂栅格布局不同,Streamlit只支持左侧边栏和右侧正文栏的布局,事实上由于上一节提到Streamlit特殊的从上往下执行程序的结构,用户也无需考虑到布局问题,控件会按照程序中的顺序从上往下自然排列。

这样的设计自然是极大程度上简化了用户在布局设计上所花的精力,可以将精力更多地用在项目展示上。

四、常用工具总结

4.1 显示文本

  • st.title

  • st.header

  • st.subheader

  • st.text

  • st.markdown

  • st.code

  • st.write

常用的显示文本命令包括大标题title, 正文标题header,正文副标题subheader,正文文本text,markdown格式(支持文字和emoji表情),代码code

st.title('Streamlit introduction')st.header('Build your first app')st.subheader('Text widgets are shown as below')st.text('I am the tool to display text')st.markdown('I am the *tool* to **display markdown**')st.markdown(':sunglasses:')st.code('''def hello():    print("Hello, Streamlit!")''', language='python')

在streamlit中还有一个万能显示工具st.write,该方法中可以接受多种格式的输入参数,如文本,markdown,数据框,图表,字典,函数,并且随着输入格式的不同,会以不同方式呈现。

4.2 显示数据

  • st.table

  • st.dataframe

  • st.json

streamlit支持数据框以及json的格式显示数据,其中table和dataframe的区别在于table为静态数据,dataframe为动态数据。

df = pd.DataFrame(    np.random.randn(10, 5),   columns=('col %d' % i for i in range(5)))st.table(df)st.dataframe(df)st.json({    'foo': 'bar',    'baz': 'boz',    'stuff': [         'stuff 1',        'stuff 2',        'stuff 3',         'stuff 5',    ], })

4.3 显示交互控件

  • st.checkbox

  • st.selectbox

  • st.multiselect

  • st.ratio

  • st.slider

这一组工具可以用于构建机器学习模型时用户参数的选择,如下拉单选,下拉多选,滑块选择等功能。

st.write('-----------------------------------------checkbox--------------------------------------------')agree = st.checkbox('I agree')if agree:    st.write('Great! You agreed!')st.write('-----------------------------------------selectbox-------------------------------------------')option = st.selectbox(    'Select your model',     ('decision tree', 'logistic regression', 'SVM'))st.write('You selected:', option)st.write('-----------------------------------------multiselect-------------------------------------------')options = st.multiselect( 'What are your favorite colors',    ['Green', 'Yellow', 'Red', 'Blue'],    ['Yellow', 'Red'])st.write('You selected:', options)st.write('-----------------------------------------ratio-------------------------------------------')genre = st.radio(    "What's your favorite model",    ('linear regression', 'neural network'))if genre == 'linear regression':    st.write('You like simple model')else:    st.write("You like complex model")st.write('-----------------------------------------slider-------------------------------------------')st.slider('How old are you?', min_value=0, max_value=100, value=20, step=5)
  • st.text_input

  • st.number_input

  • st.text_area

  • st.date_input

  • st.file_uploader

这一组工具可用于构建机器学习模型时的不同格式的用户输入以及数据上传。其中file_uploader默认支持的文件上传大小上限为200MB。

st.write('-----------------------------------------text_input--------------------------------------------')st.text_input('Movie title', 'Life of Brian')st.write('-----------------------------------------number_input-------------------------------------------')st.number_input('Insert a number')st.write('-----------------------------------------text_area-------------------------------------------')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.write('-----------------------------------------date_input-------------------------------------------')st.date_input(    "When's your birthday",    datetime.date(2019, 7, 6))st.write('-----------------------------------------file_uploader-------------------------------------------')uploaded_file = st.file_uploader("Choose a CSV file", type="csv")

4.4 显示图表

  • st.line_chart

  • st.bar_chart

  • st.area_chart

streamlit本身支持原生的三种图表形式,折线图,柱状图和面积图,不过一般不太会用到,因为streamlit还支持大量的第三方可视化图表接口。

chart_data = pd.DataFrame(     np.random.randn(20, 3),     columns=['a', 'b', 'c'])st.line_chart(chart_data)chart_data = pd.DataFrame(     np.random.randn(50, 3),    columns=["a", "b", "c"])st.bar_chart(chart_data)chart_data = pd.DataFrame(     np.random.randn(20, 3),     columns=['a', 'b', 'c'])st.area_chart(chart_data)
  • st.pyplot

  • st.altair_chart

  • st.plotly_chart

  • st.bokeh_chart

  • st.pydeck_chart

  • st.deck_gl_chart

  • st.graphviz_chart

streamlit的强大之处在于提供了大量第三方可视化接口, 以最普遍的matplotlib为例,只需在常规的代码基础上加上一句st.pyplot()即可显示在网页上显示图表

arr = np.random.normal(1, 1, size=100)plt.hist(arr, bins=20)st.pyplot()

4.5 其他工具

  • st.image

  • st.audio

  • st.video

这是一组用于展示图片,音频和视频的功能

  • st.progress

  • st.spinner

progress用于在循环中显示进度条,spinner用于提示代码正在运行

  • st.error

  • st.warning

  • st.info

  • st.success

这是一组用于显示不同状态的工具

st.error('This is an error')st.warning('This is a warning')st.info('This is a purely informational message')st.success('This is a success message!')

4.6 侧边栏

上述提到几乎所有工具均可放置在侧边栏,代码以st.sidebar.[element_name]的形式给出,以selectbox为例,st.sidebar.selectbox即表示该工具会出现在左侧。同样侧边栏的工具布局也是按照代码顺序从上往下显示。

add_selectbox = st.sidebar.selectbox(    "How would you like to be contacted?",    ("Email", "Home phone", "Mobile phone"))

五、重要功能

5.1 缓存机制

缓存机制是streamlit的一大重要功能,缓存功能使得用户在加载或处理大型数据时可以直接读取缓存,避免昂贵的计算过程。

streamlit的缓存机制是通过@st.cache的装饰器实现的。

@st.cache  def expensive_computation(a, b):    time.sleep(10)    return a * ba = 2b = 21res = expensive_computation(a, b)st.write("Result:", res)

每当程序运行至被cache装饰的函数时,当第一次运行时,会正常执行并将结果存入缓存,当函数被再次运行,首先会判断函数的输入参数,函数主体内容是否发生变化,如果发生变化,则重新运行函数,否则将跳过函数,直接读取缓存结果。

5.2 录屏功能

streamlit还提供了一个非常有用的录屏功能,在网页右上角的菜单栏,有一个Record a screencast功能,可以支持录制屏幕互动操作,非常适合团队协作和效果展示。

六、近期重大**更新**

streamlit虽然问世不久,已经拥有十分活跃的社区和用户群,并且官网也在不断丰富现有的功能中,以应对用户各种普遍的需求。

根据官网发布的2020路线图,今天预计会有一些重大的新功能推出,包括:

  • 定制化的组件(用户自定义Javascript/React)

  • 定制化布局结构(全新推出的网格和水平布局)

  • 更为丰富的缓存机制

七、优秀demo

官网收录了许多优秀的demo作品,充分展示出streamlit的强大之处和应用前景。

7.1 自动驾驶目标检测

这个项目使用不到300行代码,通过streamlit的交互界面展示了Udacity自动驾驶数据集和YOLO目标检测方法的应用。

$ streamlit run https://raw.githubusercontent.com/streamlit/demo-self-driving/master/app.py

7.2 GAN面部生成项目

这个项目使用仅仅150行代码,展示了tensorflow和Nvidia的Progressive Growing of GANs以及Shaobo Guan的Transparent Latent-space GAN方法在面部特征生成中的应用。

$ git clone https://github.com/streamlit/demo-face-gan.git$ cd demo-face-gan$ pip install -r requirements.txt$ streamlit run app.py
PreviousPython操作数据库NextTime

Last updated 4 years ago

Was this helpful?

img
img
img
img
img
img
img
img
img
img
img
img
img
img

原文链接:

https://mp.weixin.qq.com/s/YrFo_Sa7QSY2a2wgL3_9mw