使用streamlit構建快速美觀的應用程序

Every data tells a story. It’s easier to understand them through visual representations rather than looking at thousands of records.Data Scientists often leverage graphs such as bar charts, line plots, area curves, etc to communicate this story to their stakeholders.Python and R have been preferred language of choice when working with data. There are multiple libraries such as Matplotlib, Seaborn, pyVis, etc through which one creates visualizations inside the Jupyter Notebooks or stand-alone apps using Bokeh, Flask, for example.

每個數據都講述一個故事。 通過可視化表示比查看成千上萬條記錄更容易理解數據科學家經常利用條形圖,折線圖,面積曲線等圖形將其故事傳達給利益相關者,Python和R是首選語言處理數據時。 有多個庫,例如Matplotlib,Seaborn,pyVis等,通過這些庫,可以在Jupyter Notebook或使用Bokeh,Flask的獨立應用程序內部創建可視化效果。

In this article, I will try to introduce you to Streamlit and get familiar with it. At the end of this article, you will be able to create an interactive app based on your data. Let’s take a publicly available data set from Kaggle. In the end, we will be able to create an app like this.

在本文中,我將嘗試向您介紹Streamlit並熟悉它。 在本文的結尾,您將能夠基於您的數據創建一個交互式應用程序。 讓我們從Kaggle獲取公開可用的數據集。 最後,我們將能夠創建一個這樣的應用程序。

Image for post
Demo App (Gif by Author)
演示應用程序(作者提供的Gif)

The above gif is actually a screen record of the demo app. Streamlit provides you with an easy option to record your app with audio, in case you need for a demo. This is very helpful if you plan to showcase it to an audience.

上面的gif實際上是演示應用程序的屏幕記錄。 Streamlit爲您提供了一個簡單的選項,可以在需要演示的情況下用音頻錄製應用程序。 如果您打算向觀衆展示它,這將非常有幫助。

Image for post
(Image by Author)
(圖片由作者提供)

設置Streamlit (Setting up Streamlit)

Before we start with building apps, lets set up streamlit. I am working on a Ubuntu machine. Commands would be mostly the same for all OS.

在開始構建應用程序之前,讓我們先進行精簡設置。 我在Ubuntu機器上工作。 所有操作系統的命令幾乎都是相同的。

python3 -m pip install streamlit

python3 -m pip安裝streamlit

In case you face errors such as this which is a quite common one:AttributeError: module ‘google.protobuf.descriptor’ has no attribute ‘_internal_create_key’

如果您遇到這樣的錯誤,這是很常見的錯誤: AttributeError:模塊'google.protobuf.descriptor'沒有屬性'_internal_create_key'

The fix is to upgrade protobuf

解決方法是升級protobuf

python3 -m pip install — upgrade protobuf

python3 -m pip install —升級protobuf

讓我們來構建我們的應用程序 (Let’s build our App)

設計(Design)

Before we go ahead and start coding one should spend some time to create a rough layout. The way I go about is to draw it on a piece of paper — where charts should go, where would the drop-downs be? Will the charts be connected to the buttons?… so onIn case you do not have a pen and paper, draw.io is an alternative to draw designs/flow charts/UML diagrams, etc. This is what I have had drawn on a piece of paper.

在我們繼續進行編碼之前,應該花一些時間來創建粗略的佈局。 我的方法是將其繪製在一張紙上–圖表應該放在哪裏,下拉菜單應該在哪裏? 圖表可以連接到按鈕嗎?…等等如果沒有筆和紙,draw.io是繪製設計/流程圖/ UML圖等的替代方法。這就是我在一塊上繪製的內容紙

Image for post
App Layout (Image by Author)
應用佈局(作者提供的圖像)

(Code)

Now that we have the design in mind, let’s start adding the Title followed by some description of the analysis. You may wish to add an image if that increases the appealing nature of the application.

現在我們已經有了設計思想,讓我們開始添加標題,然後對分析進行一些描述。 如果可能增加了應用程序的吸引力,您可能希望添加圖像。

The code is very simple and intuitive. To load an image, you just have to read the image and call streamlit.image method. One could also write markdowns which are very similar to that of Github. To add a description we just have to call the write method with python objects as parameters. It could be a string or pandas data frame.

該代碼非常簡單直觀。 要加載圖像,只需讀取圖像並調用streamlit.image方法。 還可以編寫與Github非常相似的降價促銷。 要添加描述,我們只需要使用python對象作爲參數調用write方法。 它可以是字符串或熊貓數據框。

In the above code, we are reading the data set and showing a glance of the values. In terms of code, it’s very straight forward. You just call that sampled pandas data frame. This is the magical part of streamlit, also called as Magic Commands. When you write a variable name, streamlit implicitly writes that out to your application just that way you would using the write method. We will be utilizing some of the magic commands in this app to create charts and interactive options.

在上面的代碼中,我們正在讀取數據集並顯示這些值。 就代碼而言,這非常簡單。 您只需調用該採樣的熊貓數據框即可。 這是streamlit的神奇部分,也稱爲Magic Commands 。 當您寫一個變量名時,streamlit隱式地將其寫到您的應用程序中,就像您使用write方法一樣。 我們將利用此應用程序中的一些魔術命令來創建圖表和交互式選項。

To start the app — streamlit run app.py. You will get an app like this:

要啓動該應用程序-streamlit運行app.py。 您將獲得一個這樣的應用程序:

Image for post
Data Overview (Image by Author)
數據概述(作者提供的圖像)

Having looked at the data, we would like to create some bi-variate visualizations. These should be interactive as well so that one can select different values and analyze the trend. For example, I would like to show sales across years for various platforms. And to make it interactive, let’s add a drop-down where the end-user can select the values.

查看數據後,我們想創建一些雙變量可視化。 這些也應該是交互式的,以便可以選擇不同的值並分析趨勢。 例如,我想顯示各種平臺多年來的銷售額。 爲了使其具有交互性,讓我們添加一個下拉菜單,最終用戶可以在其中選擇值。

In the above code, we are creating one drop down and 2 charts (line graph and a stacked bar graph). To create a drop-down in streamlit, it's very simple — just call the Magic command st.selectbox

在上面的代碼中,我們將創建一個下拉列表和2個圖表(折線圖和堆積的條形圖)。 要創建流式下拉菜單,這非常簡單-只需調用Magic命令st.selectbox

platform_name = st.selectbox(‘Select a Platform’,options= df.Platform.unique())

platform_name = st.selectbox('選擇平臺',options = df.Platform.unique())

Now how do we make sure that the value selected in the drop-down option is reflected on the graphs? Well, that’s very easy too. Whatever selection you make gets assigned in the platform_name variable. In this example, we are using altair library to create charts. Refer to line 6. To embed the graph in the app, just call

現在我們如何確保在下拉選項中選擇的值反映在圖形上? 好吧,這也很容易。 您所做的任何選擇都會在platform_name變量中分配。 在此示例中,我們使用altair庫創建圖表。 請參閱第6行。要將圖形嵌入到應用程序中,只需調用

st.altair_chart(basic_chart)st.altair_chart(stacked_bar)

st.altair_chart(basic_chart)st.altair_chart(stacked_bar)

And magic! below is what you get in your app

和魔術! 以下是您在應用程序中獲得的

Image for post
(Image by Author)
(圖片由作者提供)

I found an interesting functionality in the API. If you wish to share code snippets in the app, it just a single line of code in streamlit. Write your code after you call st.echo

我在API中發現了一個有趣的功能。 如果您希望在應用程序中共享代碼段,則只需一行代碼即可。 調用st.echo後編寫代碼

The above code is used in creating the data frame for the above stacked bar graph.

上面的代碼用於爲上面的堆疊條形圖創建數據框。

Image for post
This is how code is rendered in the app (Image by Author)
這就是在應用程序中呈現代碼的方式(作者提供的圖像)

側欄 (Side Bar)

In case you wish to have multiple sections to your app, you can definitely do so.

如果您希望在應用程序中包含多個部分,則絕對可以這樣做。

Image for post
(Image by Author)
(圖片由作者提供)

analysis = st.sidebar.selectbox('Select an Option',['Image Classification','Data Analysis & Visualization'])if analysis==’Data Analysis & Visualization’: code to render app part 1else: render app part 2

分析= st.sidebar.selectbox('選擇一個選項',['圖像分類','數據分析和可視化'])如果分析=='數據分析和可視化':渲染應用程序第1部分的代碼否則:渲染應用程序第2部分

建立了一個很棒的基於深度學習的圖像分類模型,想快速構建一個演示嗎?(Built an awesome Deep learning based Image classification model, want to build a demo quickly?)

Computer vision-based models have already found their applications in industrial uses as face identification based biometric authentication; detect if there are pests in the cultivation, etc.

基於計算機視覺的模型已經在工業應用中用作基於面部識別的生物特徵認證; 檢測栽培中是否有害蟲等

Data scientists spend a good amount of time on processing data and then building a model out. Building a demo to showcase is equally important as building one. Streamlit makes that work easier too. Let’s say, I have built a keras based model to identify the number (0–9).

數據科學家花費大量時間來處理數據,然後建立模型。 製作一個演示來展示與製作一個演示同樣重要。 Streamlit也使這項工作更加容易。 假設我已經建立了一個基於keras的模型來標識數字(0–9)。

Just follow these easy 5 steps and you will get an App built out

只需按照以下5個簡單步驟操作,即可構建一個App

  1. Adding title, header, and description is very similar to the first app.

    添加標題,標題和描述與第一個應用程序非常相似。
  2. To classify an image we need to upload an image — we need a file upload widget.

    要對圖像進行分類,我們需要上傳圖像-我們需要文件上傳小部件。
  3. Just call st.file_uploader with the supported file type as a parameter (line 5).

    只需使用支持的文件類型作爲參數調用st.file_uploader (第5行)。

  4. Load the keras model

    加載keras模型
  5. Check if the button is pressed — if st.button(‘button name’). This line creates the button and also handles the event of the button being clicked.

    檢查按鈕是否被按下-如果是st.button('button name') 。 該行創建了按鈕,並且還處理了單擊按鈕的事件。

  6. Show some progress bar, in case the model is taking some time

    顯示一些進度條,以防模型花費一些時間
Image for post

Full code can be found on this Github repo.

完整的代碼可以在這個Github倉庫中找到。

I think this article can help you get started on Streamlit. They already have good documentation to refer. In case you have any queries, please post them in the comments section.

我認爲本文可以幫助您開始使用Streamlit。 他們已經有很好的文檔可供參考。 如有任何疑問,請在評論部分中發佈。

翻譯自: https://towardsdatascience.com/build-quick-and-beautiful-apps-using-streamlit-85f32ed01fb2