Author:楊劍礪,Datawhale成員,數據分析師
From:Datawhale
很多數據科學工作者都存在這樣一個痛點,由於沒有能點亮網頁前端的技能樹,導致在項目展示或項目合作時,無法快速開發出這樣一套用戶界面以供使用。而今天要介紹的Streamlit正是為了應對這一痛點而生的。
Streamlit是一個機器學習工程師專用的,專門針對機器學習和數據科學團隊的應用開發框架,是目前開發自定義機器學習工具的最快的方法。可以認為它的目標是取代Flask在機器學習項目中的地位,可以幫助機器學習工程師快速開發用戶交互工具。
本文目錄:
1. Streamlit是什麼 2. 如何開始一個Streamlit項目 3. Streamlit架構與設計初探
4. 常用工具總結
顯示文本
顯示數據
顯示交互控制項
顯示圖表
其他工具
側邊欄
5. 重要功能
6. 近期重大更新
一、Streamlit是什麼?Streamlit是一個強大的python開源工具包,可以用來快速搭建web app,以優雅地展示你的機器學習或數據科學項目。
7. 優秀demo不需要任何網頁前端設計基礎即可輕鬆搭建web app
由於web本身會隨著代碼塊自動刷新,寫程序時可以及時觀察到每一步代碼改動對於網頁的顯示效果影響,方便調試
交互式界面可以優雅地展示數據科學項目
streamlit的代碼框架遵循從上到下的運行邏輯,極易理解,所見即所得
二、如何開始一個Streamlit項目在安裝streamlit之前,需要注意python版本至少為3.6。使用pip安裝streamlit庫
在python腳本中導入包
啟動一個streamlit app有兩種方式(命令行)。1)直接運行本地的python文件
2)運行遠程url,這個功能可以直接運行github中的連結
$ streamlit run https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/app.py可以嘗試運行以下命令啟動官網提供的demo項目
三、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
常用的顯示文本命令包括大標題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
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.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
這一組工具可用於構建機器學習模型時的不同格式的用戶輸入以及數據上傳。其中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
streamlit的強大之處在於提供了大量第三方可視化接口, 以最普遍的matplotlib為例,只需在常規的代碼基礎上加上一句st.pyplot()即可顯示在網頁上顯示圖表
arr = np.random.normal(1, 1, size=100)plt.hist(arr, bins=20)st.pyplot()4.5 其他工具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 * b
a = 2b = 21res = expensive_computation(a, b)
st.write("Result:", res)每當程序運行至被cache裝飾的函數時,當第一次運行時,會正常執行並將結果存入緩存,當函數被再次運行,首先會判斷函數的輸入參數,函數主體內容是否發生變化,如果發生變化,則重新運行函數,否則將跳過函數,直接讀取緩存結果。
5.2 錄屏功能streamlit還提供了一個非常有用的錄屏功能,在網頁右上角的菜單欄,有一個Record a screencast功能,可以支持錄製屏幕互動操作,非常適合團隊協作和效果展示。
六、近期重大更新streamlit雖然問世不久,已經擁有十分活躍的社區和用戶群,並且官網也在不斷豐富現有的功能中,以應對用戶各種普遍的需求。根據官網發布的2020路線圖,今天預計會有一些重大的新功能推出,包括:七、優秀demo官網收錄了許多優秀的demo作品,充分展示出streamlit的強大之處和應用前景。7.1 自動駕駛目標檢測這個項目使用不到300行代碼,通過streamlit的交互界面展示了Udacity自動駕駛數據集和YOLO目標檢測方法的應用。
$ streamlit run https://raw.githubusercontent.com/streamlit/demo-self-driving/master/app.py7.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往期精彩:
數學推導+純Python實現機器學習算法21:最大熵模型
數學推導+純Python實現機器學習算法27:LDA線性判別分析
一個算法工程師的成長之路
長按二維碼.關注機器學習實驗室