使用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