如何優雅地展現機器學習項目!

不少數據科學工做者都存在這樣一個痛點,因爲沒有能點亮網頁前端的技能樹,致使在項目展現或項目合做時,沒法快速開發出這樣一套用戶界面以供使用。而今天要介紹的Streamlit正是爲了應對這一痛點而生的。Streamlit是一個機器學習工程師專用的,專門針對機器學習和數據科學團隊的應用開發框架,是目前開發自定義機器學習工具的最快的方法。能夠認爲它的目標是取代Flask在機器學習項目中的地位,能夠幫助機器學習工程師快速開發用戶交互工具。

本文目錄:
前端

     1. Streamlit是什麼          2. 如何開始一個Streamlit項目          3. Streamlit架構與設計初探python

    • APP模型git

    • 網頁佈局github

     4. 經常使用工具總結web

    • 顯示文本spring

    • 顯示數據json

    • 顯示交互控件bootstrap

    • 顯示圖表緩存

    • 其餘工具前端框架

    • 側邊欄

     5. 重要功能

    • 緩存機制

    • 錄屏功能

     6. 近期重大更新
     7. 優秀demo

    • 自動駕駛目標檢測

    • GAN面部生成項目

1、Streamlit是什麼?

Streamlit是一個強大的python開源工具包,能夠用來快速搭建web app,以優雅地展現你的機器學習或數據科學項目。Streamlit的優點在於:

  • 不須要任何網頁前端設計基礎便可輕鬆搭建web app

  • 因爲web自己會隨着代碼塊自動刷新,寫程序時能夠及時觀察到每一步代碼改動對於網頁的顯示效果影響,方便調試

  • 交互式界面能夠優雅地展現數據科學項目

  • streamlit的代碼框架遵循從上到下的運行邏輯,極易理解,所見即所得

2、如何開始一個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

3、Streamlit架構與設計初探

在開始介紹streamlit提供的諸多小工具以前,須要簡單介紹下streamlit的架構和佈局設計思路。

3.1 APP模型

下圖爲官網展現的app模型架構圖,一個streamlit app是這樣工做的:

  • streamlit會將python腳本按順序從上往下運行

  • 每次用戶打開指向該app服務的網頁時,整個腳本會被從新執行

  • 在腳本運行的過程當中,streamlit會將數據表,圖像,控件等實時地顯示在網頁上

  • 在運行過程當中,streamlit會優先調用緩存(須要用戶在程序中設置)避免高昂計算過程

  • 每次用戶和控件進行交互時,腳本會被從新執行,圖像,控件等被從新顯示爲新的值

3.2 網頁佈局

Streamlit的佈局結構十分簡單(這既是它的優勢,也是它的缺點)。和bootstrap等前端框架中的複雜柵格佈局不一樣,Streamlit只支持左側邊欄和右側正文欄的佈局,事實上因爲上一節提到Streamlit特殊的從上往下執行程序的結構,用戶也無需考慮到佈局問題,控件會按照程序中的順序從上往下天然排列。這樣的設計天然是極大程度上簡化了用戶在佈局設計上所花的精力,能夠將精力更多地用在項目展現上。

4、經常使用工具總結

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、重要功能

5.1 緩存機制

緩存機制是streamlit的一大重要功能,緩存功能使得用戶在加載或處理大型數據時能夠直接讀取緩存,避免昂貴的計算過程。

streamlit的緩存機制是經過@st.cache的裝飾器實現的。


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

每當程序運行至被cache裝飾的函數時,當第一次運行時,會正常執行並將結果存入緩存,當函數被再次運行,首先會判斷函數的輸入參數,函數主體內容是否發生變化,若是發生變化,則從新運行函數,不然將跳過函數,直接讀取緩存結果。

5.2 錄屏功能

streamlit還提供了一個很是有用的錄屏功能,在網頁右上角的菜單欄,有一個Record a screencast功能,能夠支持錄製屏幕互動操做,很是適合團隊協做和效果展現。

圖片

圖片

6、近期重大更新

streamlit雖然問世不久,已經擁有十分活躍的社區和用戶羣,而且官網也在不斷豐富現有的功能中,以應對用戶各類廣泛的需求。根據官網發佈的2020路線圖,今天預計會有一些重大的新功能推出,包括:

  • 定製化的組件(用戶自定義Javascript/React)

  • 定製化佈局結構(全新推出的網格和水平佈局)

  • 更爲豐富的緩存機制

7、優秀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
相關文章
相關標籤/搜索