How to Deploy Your Machine Learning Model as a Web App Using Streamlit

A brief tutorial on how to deploy your ML model on Streamlit

Ibrahim Ogunbiyi
Heartbeat

--

Photo by Emiel Molenaar on Unsplash

You’re a data scientist or machine learning engineer, and you’ve built a model with 99.99% accuracy — congratulations!

But, now what?

The final phase of your end-to-end project is to deploy the model into production in a way that both techies and non-techies alike can engage with it. There are numerous ways to do this, and in this article, we will discuss one of those methods: deploying the model as a web app using a platform called Streamlit. Let’s get started!

Prerequisites

Before we dive in, this article assumes you’re familiar with the following topics:

  • Fitting a model.
  • Environment set-up (note that Streamlit requires .py files, so we will be working in an IDE, rather than in a Jupyter notebook).
  • Fundamental Python concepts (e.g., functions, conditional statements, basic syntax, etc.).

What is Streamlit?

Streamlit is an open-source (i.e., free!) framework that allows you to build and share your web app without any prior knowledge of frontend programming languages such as JavaScript, HTML, and so on. With Streamlit, you can create a web app using Python and integrate any popular Python libraries, such as pandas, Scikit-learn, TensorFlow, and many others.

How to Install Streamlit

We install Streamlit in exactly the same way that we install any other library in Python! Simply open your terminal and and navigate to the appropriate directory:

pip install streamlit

-or-

conda install -c conda-forge streamlit

We’ve now installed Streamlit on our local machine! Now, let’s go over a few Streamlit basics before we embark on deploying our model.

Creating Our First Web App

For our first exercise, let’s build a very simple web app that asks the user for their name, state, and a number. Once the user has submitted a response, the web app will greet the user, say something about the state they selected, and provide the multiple (square) of the number they submitted. This is the code we will need to accomplish this task:

import streamlit as stst.title("Our First Web App")
st.sidebar.subheader("Nigeria States")
state = st.sidebar.radio("Choose the state", options =("Ibadan",
"Lagos"))
name = st.text_input("Enter your name")
number = st.number_input('Insert a number')
def return_val(name, number, state):
if state == "Ibadan":
fact = "Hi {}! Did you know that {} is the largest city \
by area in Nigeria?".format(name, "Ibadan")
num = "The multiple of {} is {}".format(number,
(round(number * number, 2)))
return [fact,num]
else:
fact = "Hi {}! Did you know that {} is the most populous \
city in Nigeria?".format(name, state)
num = "The multiple of {} is {}".format(number,
(round(number * number, 2)))
return [fact, num]
results = return_val(name, number, state)
if st.button("Get Fact"):
st.success(results[0])
st.write(results[1])

I have saved the above code in a file called stream.py. Next, I will run it from the terminal by typing the following code:

streamlit run stream.py

Once we run the above code in our terminal, Streamlit will direct us to our web browser and we should see something like this:

Photo by Author

So when I fill the above question I now have this as the output:

Photo by Author

Now, let’s take a deeper look at the above code to better understand what’s going on:

After importing Streamlit, we utilize the following commands:

st.title: This allows us to format the text we supply into it as a title for our web app.

st.sidebar.subheader: (starting with st.sidebar) This enables us to move and organize any component we create to the sidebar (usually located on the left). By specifying .subheader, our text is formatted in a subheader (rather than a header) style.

st.sidebar.radio: This is used to display a radio button (in this case in the sidebar). Then we pass the label argument, which is used to name the radio button, and the option argument, which contains the options we wish to have in our radio (and which must be passed as a tuple). In our example, we provide two options: Ibadan or Lagos as our options for the variable state.

st.text_input: This is used to obtain the text that the user has input. Here we don’t include the .sidebar because we want this to be included in the main section of our app. As a result, it will be placed in the middle container, which also includes our title.

st.number_input: This functions just like .text_input, only (as the name suggests), it accepts a numerical value as a user input.

After we’ve stored all relevant user inputs into our variables, we define a conditional statement to determine our output.

st.button: This is used to create a button and returns a Boolean value. If the user selects it, it will return a True, and the code inside the conditional statement will then be executed.

st.success: This is used to display an output message and indicate if the app was successfully executed. Our output, in this case, was green, indicating the function did, in fact, execute successfully.

st.write: This is also used to display an output message, but will not indicate with color whether the operation was successful or not.

Now that we’re familiar with some basic concepts, let’s deploy a Random Forest Classifier!

How does the team at Uber manage to keep their data organized and their team united? Comet’s experiment tracking. Learn more from Uber’s Olcay Cirit.

Deploying our Model

I’ll be utilizing a classification model that I’ve fitted and saved as a pickle file in this tutorial. When you develop a large, complex model that takes a long time to train, there are a few options for saving your model. One of the most common formats is hdf5, but for larger files, one of the most efficient is a pickle file. Here we will save as a pickle.

To save a model using pickle, just import the library and follow these simple steps:

import picklemodel = RandomForestClassifier()
model.fit(X_train, y_train)
# After you've fitted the model, save it as a pickle file: with open("model.pkl", "wb") as f:
pickle.dump(model, f)

To load the model back into a variable:

with open("model location.pkl", "rb") as f:
model = pickle.load(f)

Now that we’ve covered saving and loading a trained model from a pickle file, let’s take a look at the code we’ll use deploy that model to Streamlit:

import streamlit as st

st.title("Classification Model")
st.sidebar.subheader("Employment Status")
employment_props = ("Employed", "Unemployed", "Student")
employment_stats = st.sidebar.radio(label= "Choose your \
employment status", options= employment_props)
name = st.text_input("Enter your name")
age = st.number_input("Enter your age", min_value=18,
max_value = 200)
bank_props = ("First Bank", "GTB", "FCMB", "Providus Bank",
"Zenith Bank", "Access Bank", "Sterling Bank")
bank = st.selectbox("Select your bank name", options=bank_props)
account_balance = st.number_input("Enter your Account Balance")
def make_prediction(age, employment_status, bank_name,
account_balance):
with open(filepath, "rb") as f:
clf = pickle.load(f)
preds = clf.predict([[age, employment_status,
bank_name, account_balance]])
return preds
results = make_prediction(age, employment_stats, bank,
account_balance)
if st.button("Predict"):
if results == 1:
st.success("Hi {} Congratulations you are eligible for \
the loan".format(name))
else:
st.warning("Hi {} I'm so sorry, you are not eligible \
for loan".format(name))

Congratulations, the model has now been deployed into Streamlit! The code above is very similar to what we used to create our first web app above, so we don’t need to break down each of the steps again. Now that our model has been deployed in Streamlit, the next step is to publish it online! There are a few options for hosting our Web App (e.g. cloud-based platforms like Heroku, AWS, etc.), but in this tutorial we will use the Streamlit server.

To host our web app on the Streamlit server, we must first push our code to GitHub, along with all dependencies (without the dependencies, Streamlit will not be able to run the app). In order for us to export all the libraries we will first need to install pipreqs. To do that we need to type the following code in our terminal:

pip install pipreqs

-or-

conda install -c conda-forge pipreqs

After we’ve installed pipreqs we can use the following code in our terminal, which will save the required libraries into a .txt file in our current working directory:

pipreqs

Next, all we need to do is upload our code, along with the .txt file, to the GitHub repository we’ve created.

Finally, we can register our account on the Streamlit server and upload the link to our GitHub repository. To register on the Streamlit server just click here. After registering, we should see the screen below. Simply click on “New app,” and this will prompt us to link our GitHub repo with the Streamlit server.

Next, we enter the name of our repository and the name of our file like this:

Finally, we click on the “Deploy!” button. Our app is now ready to be shared with anyone!

Conclusion

Thank you for reading this tutorial. We covered a lot, but the learning doesn’t stop here. You can explore more on the Streamlit website for more features, as well as additional documentation.

Editor’s Note: Heartbeat is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.

Editorially independent, Heartbeat is sponsored and published by Comet, an MLOps platform that enables data scientists & ML teams to track, compare, explain, & optimize their experiments. We pay our contributors, and we don’t sell ads.

If you’d like to contribute, head on over to our call for contributors. You can also sign up to receive our weekly newsletters (Deep Learning Weekly and the Comet Newsletter), join us on Slack, and follow Comet on Twitter and LinkedIn for resources, events, and much more that will help you build better ML models, faster.

--

--