AI Insights

Streamlit Tutorial: Deploying an AutoML Model Using Streamlit [Step by Step]

August 9, 2022


article featured image
A step-by-step Streamlit tutorial on displaying the predicted safety ratings of roads to prevent road crashes and save lives.

Introduction

To find out how the data used in this tutorial was extracted from traffic images, check the workflow 3D Object detection and AI on satellite images for improving road safety.

Superb that you gave yourself a chance to learn to build and deploy fast and beautiful web apps using Streamlit, a low-code web app development framework made by data scientists specifically for data scientists.

So, let’s dive right into building our road safety star rating web app. We’re going to use Streamlit to build a functional, interactive, and beautiful dashboard app. Plus, the good thing is that there’s no need of having any prior experience with front-end technologies such as HTML and CSS to get started.

Project Overview

So, the app was built as part of Omdena’s IRAP project to prevent road crashes and saving lives by effectively and efficiently predicting the star ratings of the roads for car users.

The Star Ratings are based on road inspection data and provide a simple and objective measure of the level of safety which is ‘built-in’ to the road for vehicle occupants, motorcyclists, bicyclists, and pedestrians.

We focused primarily on car vehicle occupants for this app. The app takes 66 different input features in order to provide a star rating prediction. The 66 features are different attributes that contribute to the determination of a star rating. On the other hand, the output is going to be an integer value falling within the range of 1 to 5, with 1-star being the least safe and 5-star being the safest.

Development

Now if you are starting out with Streamlit from very scratch then you have two options to use it:

1. Install Streamlit locally using the following command:

pip install streamlit

2. Request for having access to Streamlit Sharing, a free web service to deploy public Github repositories. The link is given below:

www.streamlit.io

Provided, that either you have installed Streamlit locally or have been granted access by the Streamlit Sharing guys, let’s move towards creating a fresh python file with the name streamlit_app.py. Note: you can name whatever you like but it’s a good practice to name files in such a manner that you can remember their function later on, just by looking at its name. Very well, now let’s start with importing all of the relevant libraries to our use case. Note that we’re going to use PyCaret’s Random forest Regression model but you can use any model you want. Since PyCaret provides us two great functions to load the model and to make a prediction using the saved .pkl using load_model and predict_model functions respectively.

# Importing Libraries

from pycaret.regression import load_model, predict_model
import streamlit as st
import pandas as pd
import numpy as np

Then our next task will be to create a rating prediction function that can return us predictions based on our model as well as input data provided by the user.

# Defining Prediction Function

def predict_rating(model, df):
    
    predictions_data = predict_model(estimator = model, data = df)
    
    return predictions_data['Label'][0]

If you are worried about where this df came from, then keep reading 🙂

next task, create a variable named model that stores the model using the load_model function:

# Loading Model

model = load_model('car_random_forest_regressor')

So, after creating the prediction function and loading our model, our next job is going to create the title of our web app as well as some description to elaborate our app’s purpose using st.title and st.write functions respectively:

# Writing App Title and Description

st.title('Car Star Rating Regressor Web App')
st.write('This is a web app to predict the car star rating of the road based on
        several features that you can see in the sidebar. Please adjust the
        value of each feature. After that, click on the Predict button at the bottom to
        see the prediction of the regressor.')

Keep in mind, that the text is going to appear on the face of your application, so be careful of what you are going to share.

Next, we need a way to allow our users to provide their feature inputs on our app. Since almost all of our features are categorical, I suppose it will be best to represent them with a slider widget. This gives us two benefits:

  • We don’t need to worry about what value the user is going to provide us as an input because the slider will make our user choose only a value that will fall within the range of the slider bar.
  • Secondly, the range will make sure that our model will have the input in the right data type i.e. float for floating-point numbers and int for integers.

But it is totally dependent on case to case and if you want to learn more about Streamlit widgets do check out this reference link. So, to create a slider widget, we can use slider() function from Streamlit.

# Making Sliders and Feature Variables


vehicle_flow         = st.sidebar.slider(label = 'vehicle_flow', min_value = 0.0,
                        max_value = 182124.0 ,
                        value = 11516.0,
                        step = 1000.0)
                        
motorcycle_percent = st.sidebar.slider(label = 'motorcycle_percent', min_value = 3.0,
                        max_value = 8.0 ,
                        value = 7.0,
                        step = 1.0)

ped_peak_hour_flow_across = st.sidebar.slider(label = 'ped_peak_hour_flow_across', min_value = 1.0,
                        max_value = 8.0 ,
                        value = 3.0,
                        step = 1.0)

ped_peak_hour_flow_along_driver_side = st.sidebar.slider(label = 'ped_peak_hour_flow_along_driver_side', min_value = 1.0,
                        max_value = 8.0 ,
                        value = 3.0,
                        step = 1.0)
                        
...
...

Phew! That was one truly laborious job but trust me, the juice is worth the squeeze. So, in the code above, we have simply passed some parameters to ourslider() functions such as:

  • label — The name of the feature that will appear on the face of the slider to make people understand what a particular slider is about.
  • min_value — Slider’s Minimum value. Beware of the fact, that the minimum value should represent the category’s minimum value. for example, if a category is 1–5, then the min_value should be 1.
  • max_value — Slider’s Maximum value. Considering the above min_value example, the max_value should be 5.
  • value — Default value of the slider. This will be the pre-set value of our slider which will appear by default when a user will open our web app
  • step — The amount of increment and decrement when you move the slider. Again, we should be careful in selecting the step as it should reflect the minimum difference among the values of our feature. for example, in 1–5, the minimum difference that can exist between any two values is 1 i.e. 2–1 is 1.

Afterward, we will have to make a dictionary of all the features in which we will map each feature’s slider label with its corresponding variable that we created above (in which the user inputs will be stored).

# Mapping Feature Labels with Slider Values

features = {
  'vehicle_flow':vehicle_flow,
  'motorcycle_percent':motorcycle_percent,
  'ped_peak_hour_flow_across':ped_peak_hour_flow_across,
  'ped_peak_hour_flow_along_driver_side':	ped_peak_hour_flow_along_driver_side,
  'ped_peak_hour_flow_along_passenger_side':	ped_peak_hour_flow_along_passenger_side,
  'bicycle_peak_hour_flow':	bicycle_peak_hour_flow,
   '''
   '''

The next task, convert all of those user input values into a DataFrame and then pass that data frame into the Streamlit’s table function which displays a static table i.e. its entire contents are laid out directly on the web page. But why we converted the features dictionary into a DataFrame? Remember the df parameter we mentioned above! Yup, so that we can use the resultant data frame as the input of our prediction function which we created earlier. I believe now it will be much easier for you to connect the dots.

# Converting Features into DataFrame

features_df  = pd.DataFrame([features])

st.table(features_df)

Last but not least, we have reached the most fun part, making predictions. For that, first, we created a button using Streamlit’s button function and labeled it Predict to make everyone know its purpose. Afterward, we simply called our ratings prediction function i.e. predict_rating which we created earlier in our streamlit_app.py file. Finally, we again used Streamlit’s write function to show a message with the resultant prediction on the web page.

# Predicting Star Rating

if st.button('Predict'):
    
    prediction = predict_rating(model, features_df)
    
    st.write(' Based on feature values, the car star rating is '+ str(int(prediction)))

Hurrah! Now our web app is complete and it’s time for drum roll!!!! Deployment.

Deployment

For deployment, again we have two options which are the following:

1. To run our web app locally.

2. To run our web app on Streamlit sharing.

Option No.1: Running Locally

For running locally, we will need to open our prompt/terminal, then switch to the working directory of our streamlit_app.py Python file.

Finally, after reaching out to our working directory in the terminal, let’s enter:

# Running Streamlit locally


streamlit run streamlit_app.py

And you will see the magic happening right in front of you. Streamlit will start making the app recipe for you and you will watch random commands keep running on your screen and then suddenly your default browser window will pop up from nowhere and will render the user interface of your web app like the following:

Opening the Dashboard - Source: Omdena

Opening the Dashboard – Source: Omdena

OR

Option No.2: Running on Streamlit Sharing

Before, discussing Streamlit Sharing, it is important to know that:

1. You need to request access.

2. Streamlit sharing only supports public repositories not private.

Requesting the Streamlit Sharing Invite - Source: Omdena

Requesting the Streamlit Sharing Invite – Source: Omdena

Now, For that, we will have to first create a requirements.txt file. Now in our particular use case that’s a piece of cake but for a complex application that can be a bit challenging. There are many free and open-source lightweight python packages available such pipreqs or pigar etc. I am mentioning this stack overflow link here and in the references as well so that you can further explore the options on your own.

Making Requirements.txt


pycaret
streamlit
fastparquet
pandas
numpy

Finally, after having our model, streamlit_app.py, and the requirements.txt file ready, we will push them on a public Github repository on our Github account. Afterward, we will visit the Streamlit Sharing website.

Opening Streamlit.io Webpage - Source: Omdena

Opening Streamlit.io Webpage – Source: Omdena

Sign in with a Github account that Streamlit sharing has granted access to use it.

Signing in via Github - Source: Omdena

Signing in via Github – Source: Omdena

After getting signed in, we will click on the New app button.

Clicking on New App - Source: Omdena

Clicking on New App – Source: Omdena

And then will pass values of the required fields. When you will click on the first field, it will give you an auto-suggestion of all the public repositories hosted on your Github account. You need to select one and then pass the name of the branch you want to deploy. One important thing to remember is that your streamlit_app.py should be in the same branch that you are willing to deploy on Streamlit Sharing along with the model’s .pkl and requirements.txt files.

Clicking on Deploy - Source: Omdena

Clicking on Deploy – Source: Omdena

Finally, an interactive and functional Web User Interface will render like this on your browser:

Viewing the Dashboard - Source: Omdena

Viewing the Dashboard – Source: Omdena

The best of things is that you can share the link of your app with the world by just copying the URL of your app from the browser’s address bar.

And here it’s not an end but a beginning of a great journey! I hope, this article may help you in your projects to deploy awesome web apps. If you want to connect with me, do send me an invite on Linkedin and I am pretty sure, we might learn something new from each other. Well then, I‘ll see you soon, with some new topics and a new discussion. Peace!

Related Articles

media card
Building an AI Chatbot for Interview Preparation using NLP
media card
Improving Data Privacy Through Federated Machine Learning
media card
Using Satellite Imagery to Detect and Assess the Damage of Armyworms in Farming
media card
UK WellnessTech Company GoodBoost and Omdena Deploy Web App to Gamify Exercises for MSK Conditions