Other options of deployment using Streamlit and Heroku – Platform as a Service

ML Deployment using Streamlit

Deployment using Streamlit

Streamlit - Streamlit is an open-source Python library that makes it easy to create and share beautiful, custom web apps for machine learning and data science. - In just a few minutes you can build and deploy powerful data apps. So let’s get started!

Deployment of IRIS plan classification:

  • Using IRIS dataset

  • The Iris dataset was used in R.A. Fisher’s classic 1936 paper.

  • The Use of Multiple Measurements in Taxonomic Problems, and can also be found on the UCI Machine Learning Repository.

IRIS Image

  • It includes three iris species with 50 samples each as well as some properties about each flower.

  • One flower species is linearly separable from the other two, but the other two are not linearly separable from each other.

The columns in this dataset are:

Id
SepalLengthCm
SepalWidthCm
PetalLengthCm
PetalWidthCm
Species

Training the model

Import the data
[1]:
import pandas as pd
import numpy as np

df = pd.read_csv('/home/pruthvish/Ganpat University/Odd_2023_2024/7_MLOPs/TheoryMaterials/Demonstrations/Docker/IRIS_Data/Iris.csv')
df.head()

[1]:
Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species
0 1 5.1 3.5 1.4 0.2 Iris-setosa
1 2 4.9 3.0 1.4 0.2 Iris-setosa
2 3 4.7 3.2 1.3 0.2 Iris-setosa
3 4 4.6 3.1 1.5 0.2 Iris-setosa
4 5 5.0 3.6 1.4 0.2 Iris-setosa
Preprocessing
[2]:
# Dropping the Id column
df.drop('Id', axis = 1, inplace = True)

# Renaming the target column into numbers to aid training of the model
df['Species']= df['Species'].map({'Iris-setosa':0, 'Iris-versicolor':1, 'Iris-virginica':2})

# splitting the data into the columns which need to be trained(X) and the target column(y)
X = df.iloc[:, :-1]
y = df.iloc[:, -1]
Test-train split
[3]:
# splitting data into training and testing data with 30 % of data as testing data respectively
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)


Importing the random forest classifier model and training it on the dataset
[4]:
# importing the random forest classifier model and training it on the dataset
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier()
classifier.fit(X_train, y_train)

# predicting on the test dataset
y_pred = classifier.predict(X_test)

# finding out the accuracy
from sklearn.metrics import accuracy_score
score = accuracy_score(y_test, y_pred)
print(score)
0.9777777777777777
Save the model
[5]:
import pickle
pickle_out = open("classifier.pkl", "wb")
pickle.dump(classifier, pickle_out)
pickle_out.close()

Deploy the model using Streamlit

Task 1: Create the main function specifying the HTML view for user
# this is the main function in which we define our webpage
def main():
    # giving the webpage a title
    st.title("Iris Flower Prediction")

    # here we define some of the front end elements of the web page like
    # the font and background color, the padding and the text to be displayed
    html_temp = """
    <div style ="background-color:yellow;padding:13px">
    <h1 style ="color:black;text-align:center;">Streamlit Iris Flower Classifier ML App </h1>
    </div>
    """

    # this line allows us to display the front end aspects we have
    # defined in the above code
    st.markdown(html_temp, unsafe_allow_html = True)

    # the following lines create text boxes in which the user can enter
    # the data required to make the prediction
    sepal_length = st.text_input("Sepal Length", "Type Here")
    sepal_width = st.text_input("Sepal Width", "Type Here")
    petal_length = st.text_input("Petal Length", "Type Here")
    petal_width = st.text_input("Petal Width", "Type Here")
    result =""

    # the below line ensures that when the button called 'Predict' is clicked,
    # the prediction function defined above is called to make the prediction
    # and store it in the variable result
    if st.button("Predict"):
        result = prediction(sepal_length, sepal_width, petal_length, petal_width)
    st.success('The output is {}'.format(result))
Task 2: Loading the model and prediction function
# loading in the model to predict on the data
pickle_in = open('classifier.pkl', 'rb')
classifier = pickle.load(pickle_in)


# defining the function which will make the prediction using
# the data which the user inputs
def prediction(sepal_length, sepal_width, petal_length, petal_width):

    prediction = classifier.predict(
        [[sepal_length, sepal_width, petal_length, petal_width]])
    print(prediction)
    return prediction
Combining the code

Create the new app.py file and save the following python code in it.

import pandas as pd
import numpy as np
import pickle
import streamlit as st

# loading in the model to predict on the data
pickle_in = open('classifier.pkl', 'rb')
classifier = pickle.load(pickle_in)

# defining the function which will make the prediction using
# the data which the user inputs
def prediction(sepal_length, sepal_width, petal_length, petal_width):

    prediction = classifier.predict(
        [[sepal_length, sepal_width, petal_length, petal_width]])
    print(prediction)
    return prediction


# this is the main function in which we define our webpage
def main():
    # giving the webpage a title
    st.title("Iris Flower Prediction")

    # here we define some of the front end elements of the web page like
    # the font and background color, the padding and the text to be displayed
    html_temp = """
    <div style ="background-color:yellow;padding:13px">
    <h1 style ="color:black;text-align:center;">Streamlit Iris Flower Classifier ML App </h1>
    </div>
    """

    # this line allows us to display the front end aspects we have
    # defined in the above code
    st.markdown(html_temp, unsafe_allow_html = True)

    # the following lines create text boxes in which the user can enter
    # the data required to make the prediction
    sepal_length = st.text_input("Sepal Length", "Type Here")
    sepal_width = st.text_input("Sepal Width", "Type Here")
    petal_length = st.text_input("Petal Length", "Type Here")
    petal_width = st.text_input("Petal Width", "Type Here")
    result =""

    # the below line ensures that when the button called 'Predict' is clicked,
    # the prediction function defined above is called to make the prediction
    # and store it in the variable result
    if st.button("Predict"):
        result = prediction(sepal_length, sepal_width, petal_length, petal_width)
    st.success('The output is {}'.format(result))

if __name__=='__main__':
    main()

Run the Streamlit server

Command:

foo@bar:$ streamlit run app.py

Host machine learning model using streamlit and docker

(Reference link)

Step 1: Create the folder RequiredFilesForDocker. It shoud consist of following files:

model.pkl: pickle file of trained model
requirements.txt: a list of required libraries
app.py: streamlit app script to host the model over the webpage

Step 2: Create the docker file (let say using name dockerFile)

#Using the base image with Python 3.10
# FROM python:3.10
FROM python:3.10

#Set our working directory as app
WORKDIR /app

COPY RequiredFilesForDocker ./

#Installing Python packages through requirements.txt file
RUN pip install -r requirements.txt


#Exposing port 8501 from the container
EXPOSE 8501
#Starting the Python application
#CMD ["gunicorn", "--bind", "0.0.0.0:5000", "script:app"]
ENTRYPOINT ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]

Step 3: Build the docker image

Run the command: docker build -t streamlit -f dockerFile .

Step 4: Run the docker image in a container

Run the command: docker run -p 8501:8501 streamlit

Clone the docker image from Git Repo

Let us create a docker image from following Git Repo: https://github.com/streamlit/streamlit-example.git

# app/Dockerfile

FROM python:3.9-slim

WORKDIR /app

RUN apt-get update && apt-get install -y \
    build-essential \
    curl \
    software-properties-common \
    git \
    && rm -rf /var/lib/apt/lists/*

RUN git clone https://github.com/streamlit/streamlit-example.git .

RUN pip3 install -r requirements.txt

EXPOSE 8501

HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health

ENTRYPOINT ["streamlit", "run", "streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]

Run the command: docker build -t streamlitFromGit -f dockerFileFromGit .

Run the command: docker run -p 8501:8501 streamlitFromGit