I tried to make a machine learning application with Dash (+ Docker) part2 ~ Basic way of writing Dash ~

Introduction

I created a simple machine learning app using Python's web app framework Dash, so I wrote this article as a learning record (the deliverable is here. /)). In The above (part1), I introduced how to build a Dash environment with Docker. In this article, we will continue to introduce how to write app.py, which is the main part of the Dash app, focusing on the two major elements, Layout (the part that sets the appearance of the app) and Callback (the part that sets the interactive movement). I will continue to do it. Basically, it is an excerpt from Official Tutorial, so if you are comfortable with English, please read it. Also, I think it will be easier to understand if you have basic knowledge about HTML and CSS (to the extent that you can take Progate for free).

How to write Layout

In the Layout part, we will create the appearance of the application. In other frameworks, html files are often created separately, but in Dash, basically one sheet (app.py) is created. When Dash is installed, the package dash_html_components that provides HTML tags and the package dash_core_components that provides the UI required for drawing are automatically installed, and Layout is written using these. As an example, the same app.py file used for building the environment is shown.

app.py


#Import library
import dash
import dash_core_components as dcc  #A package that provides the UI required for drawing
import dash_html_components as html #A package that provides HTML tags

#Specify the external CSS path
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

#Launch the app. You can specify the app name (in this case__name__=Become an app). External CSS is also specified here.
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)


#########################Layout part####################################
app.layout = html.Div(children=[

    html.H1(children='Hello Dash'),
    html.Div(children='Dash: A web application framework for Python.'),
    dcc.Graph(
        id='example-graph',
        figure={
            'data':[{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
                    {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'}],
            'layout':{'title': 'Dash Data Visualization'}
        }
    )
])
########################################################################

#Server startup
if __name__ == '__main__':
    app.run_server(host='0.0.0.0', port=5050, debug=True)

Since dash_html_components has the same name corresponding to HTML tags (div, H1, etc.), we will write them in HTML-like manner. The Layout part of the above app.py is written in HTML as below.

<div>
    <h1>Hello Dash</h1>
    <div>Dash: A web application framework for Python.</div>
    <div id="exampl-graph" class="dash-graph">
        <!--Drawing contents-->
    </div>
</div>

In the argument children, give the text part to be displayed (the part sandwiched between tags in HTML). You can also create an HTML nesting structure by passing a list to this argument, such as children = [html.H3 (), html.H5 (), ...]. In the argument id, id can be specified arbitrarily like HTML, and id is mainly used for Callback which will be introduced later. Write CSS on the same sheet, and specify it as a dictionary in the argument style. For example, in the'Hello Dash'part

html.H1(children='Hello Dash', style={'color':'red'})

If you add something like,'Hello Dash' will be displayed in red. Use dash_core_components to implement pull-downs, checkboxes, buttons, etc. I will omit it because there is no sharpness to introduce all, but it is very easy to implement by looking at Code example of official site. Similarly, draw the graph using dash_core_components and make it likedcc.Graph (figure = ...). If you want to use a Plotly diagram, there are many code examples on here, so specify it with the argument figure while referring to it. Please note that you need to describe the import of the package provided by Plotly. I think the installation was already done when you installed Dash.

How to write Callback

In the Callback part, we will set the interactive movement. As an example, let's take a simple app that reflects the characters entered in the text box in the text.

app.py


import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash()

#########################Layout part####################################
app.layout = html.Div([
    html.H6("Change the value in the text box to see callbacks in action!"),
    html.Div(['Input:',
        #Text box part
        dcc.Input(
            id='my-id', 
            value='initial value',  #Initial value (not required)
            type='text'
        )
    ]),
    #The part to display the text
    html.Div(id='my-div')
])
########################################################################

#########################Callback part##################################
@app.callback(
    Output(component_id='my-div', component_property='children'),
    [Input(component_id='my-id', component_property='value')]
)
def update_output_div(input_value):
    return 'Output: "{}"'.format(input_value)
########################################################################

if __name__ == '__main__':
    app.run_server(host='0.0.0.0', port=5050, debug=True)

スクリーンショット 2020-11-12 14.02.22.png

Callback is written under Layout using the decorator @ app.callback. It doesn't matter if you don't know what the decorator is, but if you want to study, this article is easy to understand. Also, import Input and Output used in Callback.

Callback movement is very simple, (1) The element specified by Input is passed as an argument of the function defined under it. (2) The output of the function is passed to the element specified by Output. There are two steps. Input and Output are specified by specifying id and property. In this example, ① the value of 'my-id' id is the value of dc.Input () which is the text box part (= the value entered by UI operation) is the update_output_div function. It is passed as an argument (input_value) of (2) The output result ('Output: ~') of this function is passed to the children of html.Div () where id ='my-div'. This allows the character string entered in the text box to be reflected after the'Output:'below.

@app.callback(
    Output(component_id='id_3', component_property='children'),
    [Input(component_id='id_1', component_property='value'),
     Input(component_id='id_2', component_property='value')]
)
def func(input1, input2):
    return ...

in conclusion

I introduced the basic way of writing Dash. You can basically make an application that seems complicated at first glance by combining this Callback, and conversely, if you understand this mechanism, you can apply it to various things while looking at the official sample code. I will. In Next article, I would like to introduce a machine learning application that I actually created as an application example while partially excerpting it.

Recommended Posts

I tried to make a machine learning application with Dash (+ Docker) part2 ~ Basic way of writing Dash ~
I tried to make a machine learning application with Dash (+ Docker) part3 ~ Practice ~
I tried to make a machine learning application with Dash (+ Docker) part1 ~ Environment construction and operation check ~
I tried to make Basic authentication with Java
[iOS] I tried to make a processing application like Instagram with Swift
I tried to build a Firebase application development environment with Docker in 2020
I tried to clone a web application full of bugs with Spring Boot
I tried to make a message function of Rails Tutorial extension (Part 1): Create a model
I tried to make an introduction to PHP + MySQL with Docker
I tried to modernize a Java EE application with OpenShift.
I tried to make a client of RESAS-API in Java
I tried to create a padrino development environment with Docker
I tried to make a reply function of Rails Tutorial extension (Part 3): Corrected a misunderstanding of specifications
I tried to make the sample application into a microservice according to the idea of the book "Microservice Architecture".
I tried to develop a web application from a month and a half of programming learning history
I tried to make a message function of Rails Tutorial extension (Part 2): Create a screen to display
I tried running a letter of credit transaction application with Corda 1
I tried to build the environment of PlantUML Server with Docker
I tried to make an Android application with MVC now (Java)
I tried to make a group function (bulletin board) with Rails
[Rails] Implementation of multi-layer category function using ancestry "I tried to make a window with Bootstrap 3"
I tried to make a parent class of a value object in Ruby
I tried to make an automatic backup with pleasanter + PostgreSQL + SSL + docker
I tried to make a Web API that connects to DB with Quarkus
I tried to make a talk application in Java using AI "A3RT"
I tried to verify AdoptOpenJDK 11 (11.0.2) with Docker image
I tried to chew C # (basic of encapsulation)
I tried to break a block with java (1)
I tried to create a portfolio with AWS, Docker, CircleCI, Laravel [with reference link]
I tried to make a simple game with Javafx ① "Let's find happiness game" (unfinished)
Rails6 I want to make an array of values with a check box
[Android] I tried to make a material list screen with ListView + Bottom Sheet
I tried to summarize the state transition of docker
I tried to make a login function in Java
[Machine learning] I tried Object Detection with Create ML [Object detection]
Introduction to Machine Learning with Spark "Price Estimate" # 3 Make a [Price Estimate Engine] by learning with training data
Rails6 I tried to introduce Docker to an existing application
I tried to make a web application that searches tweets with vue-word cloud and examines the tendency of what is written in the associated profile
[Azure] I tried to create a Java application for free ~ Connect with FTP ~ [Beginner]
I tried to make a product price comparison tool of Amazon around the world with Java, Amazon Product Advertising API, Currency API (2017/01/29)
kintone clone? I was quite addicted to launching OSS WebDB Extension with Lightsail + Docker, so make a note of it.
A memo when I tried "Talking about writing a Java application in Eclipse and publishing it in Kubernetes with a Liberty container (Part 1)"
Easy to make LINE BOT with Java Servlet Part 2: I tried image messages and templates
I tried to make an application in 3 months from inexperienced
I tried to create a java8 development environment with Chocolatey
[Rails] I tried to create a mini app with FullCalendar
[Swift] I tried to implement the function of the vending machine
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
Learning Ruby with AtCoder 13 How to make a two-dimensional array
I tried to summarize the basic grammar of Ruby briefly
I tried to build the environment of WSL2 + Docker + VSCode
I tried to touch JavaScript Part.1 Basic processing code system
I tried to implement a buggy web application in Kotlin
I tried OCR processing a PDF file with Java part2
I tried BIND with Docker
I tried to express the result of before and after of Date class with a number line
I tried to make the "Select File" button of the sample application created in the Rails tutorial cool
After learning Progate, I tried to make an SNS application using Rails in the local environment
I tried to take a look at the flow of Android development environment construction with Android Studio
Let's make a book management web application with Spring Boot part1