Flask API for Machine Learning Model from scratch
If you are completely unaware about building Flask web application, go through tutorials given below :
Building Flask web application — Part 1
Building Flask web application — Part 2
Prerequisite : First you need to install VS code.
Step 1 :
Create a new folder on desktop. Open it and hit right click inside it to open it using VS code as given below.
Step 2 :
First install required libraries in the VS code terminal.
pip install flaskpip install pandas pip install numpypip install sklearn
Step 3 :
Download song popularity dataset from kaggle.
Keep the train.csv file in this folder and create preprocessing.py file as given below.
import pandas as pdimport numpy as npimport picklefrom sklearn.linear_model import LogisticRegressionfrom sklearn.preprocessing import StandardScalerdf = pd.read_csv('train.csv', index_col = 0)# list of all the columns that have null valuesnull_col_list = []for col in filter((lambda x : df[x].isnull().sum() > 0), df.isnull().sum().index): null_col_list.append(col)# filling the null values with median value of the respective columnsfor col in null_col_list: median = df[col].median() df[col].fillna(median, inplace = True)X = df.drop('song_popularity', axis= 1)y = df['song_popularity']# normalizing the datascaler = StandardScaler()scaler.fit(X)X_trans = scaler.transform(X)# using Logistic regression modelmodel = LogisticRegression()model.fit(X_trans,y)# dumping the model in pickle filewith open('model.pkl', 'wb') as files: pickle.dump(model, files)
“Pickling” is process which enables storage and preservation. So in this file, our trained model is preserved to be used later in main.py file where values are fetched from API and model is used to predict the output based on these values.
Execute following command in VS code terminal to run preprocessing.py file. Then model.pkl file will be automatically created as shown below.
python preprocessing.py
OR if above code doesn’t work, try :
python3 preprocessing.py
Step 4:
Create main.py file in this folder as given below.
from flask import Flask, request, render_templateimport pickleimport numpy as npapp=Flask(__name__,template_folder='./templates')model = pickle.load(open("model.pkl", "rb"))@app.route('/')def home(): return render_template('index.html')@app.route('/predict',methods=['POST'])def predict(): int_features = [float(x) for x in request.form.values()]
#if above line does not fetch expected output, try code given below:
# int_features = [float(x) for x in list(request.form.values())] final_features = [np.array(int_features)] prediction = model.predict(final_features) if prediction == 0: output = "This song is not popular." else : output = "This song is poplar." return render_template('index.html', result=output)if __name__ =="__main__": app.run()
If you find this code difficult to understand, you need to go through this.
Step 5 :
Create a folder and it must be named as “templates”. (Remember lowercase “t”). Create a html file inside it “index.html” and write code given below, inside it.
<html><body><h3>Song Popular Form</h3><div><form action="/predict" method="POST"><label for="song_duration_ms">Song Duration</label><input type="text" id="song_duration_ms" name="song_duration_ms"><br><label for="acousticness">Acousticness</label><input type="text" id="acousticness" name="acousticness"><br><label for="danceability">Danceability</label><input type="text" id="danceability" name="danceability"><br><label for="energy">Energy</label><input type="text" id="energy" name="energy"><br><label for="instrumentalness">Instrumentalness</label><input type="text" id="instrumentalness" name="instrumentalness"><br><label for="key">Key</label><select id="key" name="key"><option value="0">0.0</option><option value="1">1.0</option><option value="2">2.0</option><option value="3">3.0</option><option value="4">4.0</option><option value="5">5.0</option><option value="6">6.0</option><option value="7">7.0</option><option value="8">8.0</option><option value="9">9.0</option><option value="10">10.0</option><option value="11">11.0</option><option value="12">12.0</option></select><br><label for="liveness">Liveness</label><input type="text" id="liveness" name="liveness"><br><label for="loudness">Loudness</label><input type="text" id="loudness" name="loudness"><br><label for="audio_mode">Audio Mode</label><select id="audio_mode" name="audio_mode"><option value="0">0</option><option value="1">1</option></select><br><label for="speechiness">Speechiness</label><input type="text" id="speechiness" name="speechiness"><br><label for="tempo">Tempo</label><input type="text" id="tempo" name="tempo"><br><label for="time_signature">Time Signature</label><select id="time_signature" name="time_signature"><option value="0">2</option><option value="1">3</option><option value="2">4</option><option value="3">5</option></select><br><label for="audio_valence">Audio Valence</label><input type="text" id="audio_valence" name="audio_valence"><br><input type="submit" value="Submit"></form><br><br>{{ result }}</div></body></html>
Step 6 :
Now run following command in the terminal :
python main.py
OR if above code doesn’t work, try :
python3 main.py
This will generate URL in the terminal, as shown below.
Copy and paste this URL in web browser and hit submit button after passing the random values for the features, you can see the webpage as :
You will get the prediction from the trained model as given below :
Congratulations !!!
You have created first Flask API for Machine Learning model. You can learn how to deploy ML model on Heroku platform here.
Happy Learning !!!