ML Model Training to Model in production with Few Lines of Code

Do you know?

Significant major symptoms of a heart attack are

Immediatly Call 9–1–1 if you notice symptoms of a heart attack.

In this blog we are going to do:

Let’s start!

Introduction

For those who don’t know

About Dataset

Installation

!pip install lucifer-ml  mlfoundry servicefoundry gradio

Importing Libraries

import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
plt.style.use('dark_background')
import numpy as np
import pandas as pd
import seaborn as sns
#Importing LuciferML
from luciferml.supervised.classification import Classification
import mlfoundry as mlf
import warnings
import servicefoundry.core as sfy
warnings.simplefilter(action='ignore', category=Warning)

Loading Dataset

dataset = pd.read_csv('../input/heart-attack-analysis-prediction-dataset/heart.csv')

Exploratory Data Analysis

dataset.head()

Data Preparation

features = dataset.iloc[:, 0:-1]
labels = dataset.iloc[:, -1]

Training a lot of Models…

classifier =  Classification(predictor = 'all', lda = 'y',smote = 'y')
classifier.fit(features, labels)
result = classifier.result_df

Leaderboard

result = result.sort_values(by = 'KFold Accuracy', ascending = False).reset_index(drop = True)
result.iloc[0]

Experiment Tracking

sfy.login(api_key)
mlf_api = mlf.get_client(
api_key=api_key)
mlf_run = mlf_api.create_run(
project_name='heart', run_name='heart-run-4')
mlf_run.log_dataset("features", features)
mlf_run.log_dataset("labels", labels)
mlf_run.log_model(name = 'Best Model', model = result.iloc[0]['Model'], framework = 'sklearn', description = 'My Model')

Deploying model in 3..2..1…

Directory Structure

First, we will write deployment code using the magic function

%%writefile deploy.py
import mlfoundry as mlf
import gradio as gr
import pandas as pd
import numpy as np
mlf_client = mlf.get_client(
api_key=api_key')
runs = mlf_client.get_all_runs('heart')run = mlf_client.get_run(runs['run_id'][0])model = run.get_model()df = run.get_dataset('features')df = pd.DataFrame(df.features)inputs = []
i = 0
sample = df.iloc[0:1].values.tolist()[0]
for x in df.columns:
if df[x].dtype == 'object':
inputs.append(gr.Textbox(label=x, value=sample[i]))
elif df[x].dtype == 'float64' or df[x].dtype == 'int64':
inputs.append(gr.Number(label=x, value=sample[i]),)
i += 1
def predict(*val):
global model
if type(val) != list:
val = [val]
if type(val) != np.array:
val = np.array(val)
print(val.shape)
if val.ndim == 1:
val = val.reshape(1, -1)
pred = model.predict(val)
return pred.tolist()[0]
app = gr.Interface(fn=predict, inputs=inputs,
outputs=gr.Textbox(label='Output'))
app.launch(server_name="0.0.0.0", server_port=8080)

Next, we will write the requirements.txt

requirements = sfy.gather_requirements("deploy.py")
reqs = []
for i, j in enumerate(requirements):
reqs.append('{}=={}'.format(j, requirements[j]))
with open('requirements.txt', 'w') as f:
for line in reqs:
f.write(line)
f.write('\n')

Creating service and deploying it on our workspace

service = Service(
name="heart-service-1",
image=Build(
build_spec=PythonBuild(
command="python deploy.py",
),
),
ports=[{"port": 8080}],
resources=Resources(memory_limit="1.5Gi", memory_request="1Gi"),
)
service.deploy(workspace_fqn=workspace)

Deployed Model

--

--

Thinking…..

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store