A computer is able to learn from experience without being explicitly programmed. Machine Learning is one of the top fields to enter currently and top companies all over the world are using it for improving their services and products. But there is no use of a Machine Learning model which is trained in your Jupyter Notebook. And so we need to deploy these models so that everyone can use them. In this article, we will first train an Iris Species classifier and then deploy the model using Streamlit which is an open-source app framework used to deploy ML models easily.
Streamlit lets you create apps for your machine learning project using simple python scripts. It also supports hot-reloading, so that your app can update live as you edit and save your file. An app can be built in a few lines of code only(as we will see below) using the Streamlit API. Adding a widget is the same as declaring a variable. There is no need to write a backend, define different routes or handle HTTP requests. It is easy to deploy and manage. More information can be found on their website – https://www.streamlit.io/
So first we will train our model. We will not do much preprocessing as the main aim of this article is not to make an accurate ML model but to show its deployment.
Firstly we need to install the following –
pip install pandas
pip install numpy
pip install sklearn
pip install streamlit
The dataset can be found here: https://www.kaggle.com/uciml/iris
Now we drop the Id column first as it is not important for classifying the Iris species. Then we will split the dataset into training and testing dataset and will use a Random Forest Classifier. You can use any other classifier of your choice, for example, logistic regression, support vector machine, etc.
We get an accuracy of 95.55% which is pretty good.
Now, in order to use this model to predict other unknown data, we need to save it. We can save it by using pickle, which is used for serializing and deserializing a Python object structure.
There will be a new file created called “classifier.pkl” in the same directory. Now we can get down to using Streamlit to deploy the model –
Paste the below code into another python file.
You can run this by typing the following command in the terminal –
streamlit run app.py
app.py is the name of the file where we wrote the Streamlit code.
The website will open in your browser and then you can test it. This method can be used to deploy other machine and deep learning models too.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course