DEV Community

Cover image for Deploying ML models using Streamlit
apurva866
apurva866

Posted on

Deploying ML models using Streamlit

Imagine building a supervised machine learning ML model to decide whether a credit card transaction has detected fraud or not. With the model confidence level in successful applications, we can evaluate the risk-free credit cards transactions. So you have built the model, which can detect credit card frauds, now what? The deployment of such ML-model is the prime goal of the project.
Deploying an ML-model simply means the integration of the model into an existing production environment which can take in an input and return an output that can be used in making practical business decisions. Here is where Streamlit comes to play !

Streamlit is a open-source app framework is the easiest way for data scientists and machine learning engineers to create beautiful, performant apps in only a few hours! All in pure Python. All for free.

In the part one of this tutorial I am going to deploy a Supervised machine learning model to predict the age of a Abalone and in the next part of the tutorial we will host this web app on Heroku. An Abalone is a molluscs with a peculiar ear-shaped shell lined of mother of pearl. Abalone's age can be obtained using their physical measurement. Let us deploy the model.

Alt Text

Create the pickle file for the model, refer to my kaggle notebook for the Machine learning model. We will be focusing on the deployment in this tutorial. Import the necessary packages. Import streamlit and pickle, to unpickle the pickled file.

import streamlit as st
import pickle
import numpy as np
model = pickle.load(open('final_model.pkl','rb'))
Enter fullscreen mode Exit fullscreen mode

Create a function to use the pickled model. Convert all the input values into into a Numpy array and change the data type of the input array to float. Create prediction values using model.predict(input). Return the prediction values.

def predict_age(Length,Diameter,Height,Whole_weight,Shucked_weight,
                Viscera_weight,Shell_weight):
    input=np.array([[Length,Diameter,Height,Whole_weight,Shucked_weight,
                     Viscera_weight,Shell_weight]]).astype(np.float64)
    prediction = model.predict(input)

    return int(prediction)
Enter fullscreen mode Exit fullscreen mode

Create the main function.

def main()

Now, let us build the components of the main function.

  1. Create a title for your page. Use st.markdown to create the html title text.
    st.title("Abalone Age Prediction")
    html_temp = """
    <div style="background:#025246 ;padding:10px">
    <h2 style="color:white;text-align:center;"> Abalone Age Prediction ML App </h2>
    </div>
    """
    st.markdown(html_temp, unsafe_allow_html = True)
Enter fullscreen mode Exit fullscreen mode
  1. For taking the user input, Streamlit provides with an API to directly create HTML form components like input fields, use st.text_input() to take input value for the app.
    Length = st.text_input("Length","Type Here")
    Diameter = st.text_input("Diameter","Type Here")
    Height = st.text_input("Height","Type Here")
    Whole_weight = st.text_input("Whole weight","Type Here")
    Shucked_weight = st.text_input("Shucked weight","Type Here")
    Viscera_weight = st.text_input("Viscera weight","Type Here")
    Shell_weight = st.text_input("Shell weight","Type Here")

Enter fullscreen mode Exit fullscreen mode
  1. Define the output field. Create the html text you want to display for the output like safe_html, similarly define warn_html and danger_html. Use st.button() to build the button widget and st.success() to display a message when the model successfully predicts the value.
        safe_html ="""  
        <div style="background-color:#80ff80; padding:10px >
        <h2 style="color:white;text-align:center;"> The Abalone is young</h2>
        </div>
        """
        if st.button("Predict the age"):
        output = predict_age(Length,Diameter,Height,Whole_weight,
                             Shucked_weight,Viscera_weight,Shell_weight)
        st.success('The age is {}'.format(output))

        if output == 1:
            st.markdown(safe_html,unsafe_allow_html=True)
        elif output == 2:
            st.markdown(warn_html,unsafe_allow_html=True)
        elif output == 3:
            st.markdown(danger_html,unsafe_allow_html=True)
Enter fullscreen mode Exit fullscreen mode

Every module in Python has a special attribute called name. The value of name attribute is set to 'main' when module run as main program. Hence, call the main() function if name = 'main' .

if __name__=='__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Now let’s get to the deployment.
i) Install streamlit on your local machine.

pip install Flask
pip install streamlit

ii) Save your file as filename.py and add the final_model.pkl file in the same directory. Or simply clone the GitHub repository on your machine.

git clone https://github.com/Apurva-tech/abalone-age-app.git

iii) Open your command prompt/terminal and navigate to the file directory. And run the following command. This starts the web app on

localhost:8501

streamlit run filename.py

Input the values, and click on predict aaaannndd Voila!
With that we have come to end to the part one of this tutorial. Stay tuned for the next part where we will host this web app on Heroku, the link to the web app - https://abalone-age-app.herokuapp.com/.
See you there!
Happy learning 😄

Top comments (2)

Collapse
 
albertulysses profile image
Albert Ulysses

I love the idea of steamlit, I haven't played around with it yet. This is inspiring glad I saw it.

Collapse
 
apurvatech profile image
apurva866

I'm glad my article helped you 😄