The TensorFlow tutorials are written as Jupyter notebooks and run directly in Google Colab—a hosted notebook environment that requires no setup. Click the Run in Google Colab button.
Colab link - Open colab
How to Easily Deploy Machine Learning Models Using Flask
Why Flask?
1. Easy to use.
2. Built in development server and debugger.
3. Integrated unit testing support.
4. RESTful request dispatching.
5. Extensively documented.
Importing Needed packages
import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import numpy as np
%matplotlib inline
!pip install scikit-learn==0.23.2
import sklearn
print(sklearn.__version__)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn import linear_model
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
import numpy as np
import matplotlib.pyplot as plt
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.model_selection import learning_curve
from sklearn.model_selection import ShuffleSplit
import warnings
warnings.filterwarnings('ignore')
# setting up default plotting parameters
%matplotlib inline
plt.rcParams['figure.figsize'] = [20.0, 7.0]
plt.rcParams.update({'font.size': 22,})
sns.set_palette('viridis')
sns.set_style('white')
sns.set_context('talk', font_scale=0.8)
np.random.seed(27)
!wget -O FuelConsumption.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv
df = pd.read_csv("FuelConsumption.csv")
from xgboost import XGBRegressor
train_x = df.drop(['MODELYEAR', 'MAKE', 'MODEL','VEHICLECLASS','TRANSMISSION','FUELTYPE', 'CO2EMISSIONS'], axis=1)
train_y = df['CO2EMISSIONS']
train_x = np.array(train_x)
train_y = np.array(train_y)
obj1 = XGBRegressor()
# split data into train and test sets
seed = 7
test_size = 0.2
X_train, X_test, y_train, y_test = train_test_split(train_x, train_y, test_size=test_size, random_state=seed)
Grid search is an exhaustive search over specified parameter values.
booster = ['gbtree']
eta = [0.1]
gamma = [0]
max_depth = [4]
min_child_weight = [1]
subsample = [0.5]
reg_lambda = [0.5]
scale_pos_weight = [2]
param_grid = dict(scale_pos_weight=scale_pos_weight,booster=booster,eta=eta,gamma=gamma,max_depth=max_depth,min_child_weight=min_child_weight,subsample=subsample,reg_lambda=reg_lambda)
grid = GridSearchCV(estimator=obj1, param_grid=param_grid, scoring='neg_root_mean_squared_error', verbose=1, n_jobs=-1)
grid_result = grid.fit(X_train, y_train)
STORE YOUR MODEL
import pickle
pickle.dump(grid, open('model.pkl','wb'))
model = pickle.load(open('model.pkl','rb'))
TEST MODEL
print(model.predict([[1,1,1,1,1,1]]))
Build requirements
pip freeze > requirements.txt
CREATE A Procfile : Create a file with name Procfile and paste content below line in it into it
web: gunicorn app:app
ORGANIZE FILES 1. Create folder templates and add your .html files in it. We create a webpage for calling the api. This is available at https://github.com/pranavn91/demoflask/blob/main/templates/index.html
2. Paste Procfile and model.pkl in outside templates
INSTALL FLASK AND NGROK
!pip install flask-ngrok
from flask_ngrok import run_with_ngrok
from flask import Flask
Create file - app.py
import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__)
run_with_ngrok(app) #starts ngrok when the app is run
model = pickle.load(open('model.pkl', 'rb'))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict',methods=['POST','GET'])
def predict():
int_features = [int(x) for x in request.form.values()]
final_features = [np.array(int_features)]
prediction = model.predict(final_features)
output = round(prediction[0], 2)
return render_template('index.html', prediction_text='CO2EMISSIONS should be $ {}'.format(output))
if __name__ == "__main__":
app.run()