How to deploy a machine learning model for free?

Deploy your machine-learning web app in minutes for free.

Krishan Walia
ILLUMINATION
6 min readJan 20, 2024

--

If you have ever created a machine-learning pipeline project, and wish to get it deployed for free and as easily as it is to make a cup of tea, then you are in the right place.

Photo by Glenn Carstens-Peters on Unsplash

In this article, you will learn how you can easily publish your machine-learning web app so that you can share the link with anyone and can add it to your portfolio as well.

Everyone understands the importance of making the project available to public and receiving reviews for it. So, without further ado, let's get into it.

We will be using a python package to facilitate the deployment of the machine learning web app. And the package is streamlit.

So, before we actually get into the main things, here’s the table of content of this article.

· Streamlit
·
Tutorial
Create a streamlit_app.py
Example Code
Running the Web App
Deploying to Streamlit
Live Example
·
Conclusion
·
References
·
Today’s Quote
·
More from Author
·
About The Author

Streamlit

Image from Streamlit.io

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[1].

With the use of streamlit, one can deploy their machine learning web apps easily and quickly. Connecting the GitHub repository of the project facilitates the project in the continuous integration and continuous deployment, which is very much useful in case of large pipeline projects.

Streamlit offers a lot of components that can be easily integrated and would be useful in enhancing the User-Interface of the web app. You will be learning about some of the convoluted components in this series of machine learning deployment articles published on this account. So, Follow!

Tutorial

The following portion of this article demonstrates the use of streamlit in deploying a machine learning web app.

The project is a complete end-to-end machine learning pipeline project, built over the most infamous ‘titanic dataset’. You can find the link to the project in the references section below [2].

Create a streamlit_app.py

The streamlit package usually searches for a file named as streamlit_app in the project directory. If you wish to change the name of the app. You can also do that but for the sake of simplicity, make it like that, though you can change it afterwards, once you know about the necessary changes that are needed to be produced with the change of the file name.

Example Code

After creating a file named as “streamlit_app”. We have to initialize the web app, and add the components as per our need. The code below shows the example of a “streamlit_app” for the project [2].

import os
from pathlib import Path
import time
import streamlit as st
import pandas as pd
from titanic.pipeline.prediction import PredictionPipeline
from titanic.utils.common import read_yaml


class ClientApp:
def __init__(self):
self.filename = "test.csv"
self.classifier = PredictionPipeline(self.filename)


# Define the feature input function
def main():

st.title("Titanic Survival Prediction")

pclass_options ={
1:'Upper',
2:'Middle',
3:'Lower'
}

embark_options = {
"C":'Cherbourg',
"Q":"Queenstown",
"S":"Southampton"
}

def embar_format_func(option):
return embark_options[option]
def pclass_format_func(option):
return pclass_options[option]


# Define your features here. For example:
Pclass = st.selectbox('Ticket Class',pclass_options.keys(),format_func=pclass_format_func )
Sex = st.selectbox('Gender', ['Male', 'Female'])
Age = st.slider('Age in years', 0, 100, 30)
SibSp = st.slider('Number of Siblings/Sposes aboard', 0, 10, 1)
Parch = st.slider('Number of Parents/Children aboard', 0, 10, 0)
# Fare = st.sidebar.slider('Fare', 0.0, 600.0, 50.0)f
Embarked = st.selectbox('Port of Embarkation',embark_options.keys(), format_func=embar_format_func)

if st.button("Train"):
with st.spinner('Training the model'):
os.system("dvc repro")
time.sleep(5)
st.write("Model trained successfully")
content = read_yaml(Path('metrics.yaml'))

st.write(f"The accuracy of the model is {float(content.accuracy)*100}")

if st.button('Predict', help="Click to know if the person has suvived"):

# Create a data frame from the inputs
data = {'Pclass': Pclass,
'Sex': Sex,
'Age': Age,
'SibSp': SibSp,
'Parch': Parch,
# 'Fare': Fare,
'Embarked': Embarked}
df = pd.DataFrame(data, index=[0])
print(df)

# st.subheader('User Input parameters')
st.write(df)

df.to_csv(clApp.filename, index=False)

# df.to_csv("training.csv", mode='a', index=False, header=False)

result = clApp.classifier.predict()
if result == 0:
st.write("There is very less hope that this person could have survived the tragedy.")
else:
st.write("There is very high hope that this person could have survived the tragedy.")


if __name__ == '__main__':
clApp = ClientApp()
main()

To run the streamlit web app, you have to initialise the web app by defining the title of the web app using ‘streamlit.title(“Title Of Your Project”)’.

Running the Web App

To run the web app created one has to open the terminal and write the following command,

streamlit run streamlit_app.py

This action will create a web app of your project and open it in your local browser.

Deploying to Streamlit

To deploy the web app using streamlit, one has to have a GitHub repository for the project.

After logging in streamlit.io, you have to integrate your GitHub account with your streamlit account and then have to click on New app, as indicated in the image below,

Image by Author

After clicking on the New app, you will get a screen like this,

Image by Author

Here, you have to fill in the required details like the GitHub repository, Branch, Main file path, and the App URL.

With streamlit one can also choose the app url of their choice, depending upon the availability.

Then click on Deploy, and you are done! Within minutes your app will be live if everything went well.

Live Example

One of the example of the project that has been deployed using streamlit is,

https://titanicpipelineproject123.streamlit.app/

Conclusion

This article gives information about how one can deploy a machine learning web app for free and that too within minutes and easily. Streamlit is used for deploying the machine learning web app.

Today’s Quote

It is often the small steps, not the giant leaps, that bring about the most lasting change.
By- Queen Elizabeth II

About The Author

Hi 👋, myself Krishan Walia🤠, a full stack developer👨‍💻 with a deep interest in quantum computing🖥️, machine learning💻and cyber security🎩 (I know they are quite diverse fields😅). I write✍️ because of the affection😍 to sharing knowledge and experiences😇 with people and also learning from them, cause that’s actually how (according to me) we all as a community can grow📈.

I usually write📝 about software development and about the big advancement made in the field of tech ⚙️so that we all are aware of how we can utilize the best resources📚 available out there to our maximum advantage.
If you liked👍 my content, kindly consider following me👏and to get the articles I publish, at the earliest and straight into your inbox📨 you can definitely subscribe to my email list📝 from the below link, I’d really appreciate that

Thank you!!!

--

--

Krishan Walia
ILLUMINATION

ML Expert | Entrepreneur | Full Stack Developer | Curious | Quick Learner | Meditator | Nature Lover | Researcher | Working on a Patent