Galle, LK--:--5/6 sites live

Diabetes model for API

Streamlit app එකක් browser එකේ click කරන මිනිසෙකුට ලොකු වැඩක් — ඒත් වෙනත් software (mobile app එකක්, server එකක්) ඕන කරන්නෙ API එකක්. ඒ හිතුවෙකේ මාරුව තමයි මේක.

A Streamlit app is great for a human clicking through a browser — but other software (a mobile app, another server) needs an API instead. This is that shift in thinking.

21 May 20265 min readSelf Guide · Stage 17#Shipping Models to the World#Deploy ML model as API on Heroku#Machine learning

Lesson 60 of 64 · Part 5 · Shipping Models to the World · Deploy ML model as API on Heroku · bilingual notes (English + සිංහල)

Why this matters. A Streamlit app is great for a human clicking through a browser — but other software (a mobile app, another server) needs an API instead. This is that shift in thinking.

සිංහලෙන්: Streamlit app එකක් browser එකේ click කරන මිනිසෙකුට ලොකු වැඩක් — ඒත් වෙනත් software (mobile app එකක්, server එකක්) ඕන කරන්නෙ API එකක්. ඒ හිතුවෙකේ මාරුව තමයි මේක.

What you'll use this for. Any time one program needs to ask another program for a prediction (not a human, a program), it goes through exactly this kind of API layer.

සිංහලෙන්: Program එකකින් අනිත් program එකෙන් prediction එකක් අහන ඕනම වෙලාවක (මිනිසෙක් නෙවෙයි, program එකක්), යන්නෙ හරියටම මේ වගේ API layer එකකින්.

Key principles

  • An API separates "the model" from "how someone talks to the model". The same underlying model can now be called from a website, a mobile app, or another server — because they all speak the same simple request/response language.
    API එකකින් "model එක" සහ "model එකට කතා කරන විදිහ" වෙන් කරනවා

Walkthrough

Importing the Dependencies

ExamplePython
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import accuracy_score

Data Collection and Analysis

PIMA Diabetes Dataset

ExamplePython
# loading the diabetes dataset to a pandas DataFrame
diabetes_dataset = pd.read_csv('/content/diabetes.csv')
ExamplePython
# printing the first 5 rows of the dataset
diabetes_dataset.head()
PregnanciesGlucoseBloodPressureSkinThicknessInsulinBMIDiabetesPedigreeFunction…
061487235033.60.627…
11856629026.60.351…
28183640023.30.672…
318966239428.10.167…
40137403516843.12.288…
ExamplePython
# number of rows and Columns in this dataset
diabetes_dataset.shape

Output

Output
(768, 9)
ExamplePython
# getting the statistical measures of the data
diabetes_dataset.describe()
PregnanciesGlucoseBloodPressureSkinThicknessInsulinBMIDiabetesPedigreeFunction…
count768.000000768.000000768.000000768.000000768.000000768.000000768.000000…
mean3.845052120.89453169.10546920.53645879.79947931.9925780.471876…
std3.36957831.97261819.35580715.952218115.2440027.8841600.331329…
min0.0000000.0000000.0000000.0000000.0000000.0000000.078000…
25%1.00000099.00000062.0000000.0000000.00000027.3000000.243750…
50%3.000000117.00000072.00000023.00000030.50000032.0000000.372500…

… 2 more rows

ExamplePython
diabetes_dataset['Outcome'].value_counts()

Output

Output
0    500
1    268
Name: Outcome, dtype: int64

0 --> Non-Diabetic

1 --> Diabetic

ExamplePython
diabetes_dataset.groupby('Outcome').mean()
PregnanciesGlucoseBloodPressureSkinThicknessInsulinBMIDiabetesPedigreeFunctionAge
Outcome
03.298000109.98000068.18400019.66400068.79200030.3042000.42973431.190000
14.865672141.25746370.82462722.164179100.33582135.1425370.55050037.067164
ExamplePython
# separating the data and labels
X = diabetes_dataset.drop(columns = 'Outcome', axis=1)
Y = diabetes_dataset['Outcome']
ExamplePython
print(X)

Output

Output
     Pregnancies  Glucose  BloodPressure  SkinThickness  Insulin   BMI  \
0              6      148             72             35        0  33.6   
1              1       85             66             29        0  26.6   
2              8      183             64              0        0  23.3   
3              1       89             66             23       94  28.1   
4              0      137             40             35      168  43.1   
..           ...      ...            ...            ...      ...   ...   
763           10      101             76             48      180  32.9   
764            2      122             70             27        0  36.8   
765            5      121             72             23      112  26.2   
766            1      126             60              0        0  30.1   
767            1       93             70             31        0  30.4   

     DiabetesPedigreeFunction  Age  
0                       0.627   50  
1                       0.351   31  
2                       0.672   32  
3                       0.167   21  
… (9 more lines)
ExamplePython
print(Y)

Output

Output
0      1
1      0
2      1
3      0
4      1
      ..
763    0
764    0
765    0
766    1
767    0
Name: Outcome, Length: 768, dtype: int64

Train Test Split

ExamplePython
X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.2, stratify=Y, random_state=2)
ExamplePython
print(X.shape, X_train.shape, X_test.shape)

Output

Output
(768, 8) (614, 8) (154, 8)

Training the Model

ExamplePython
classifier = svm.SVC(kernel='linear')
ExamplePython
#training the support vector Machine Classifier
classifier.fit(X_train, Y_train)

Output

Output
SVC(kernel='linear')

Model Evaluation

Accuracy Score

ExamplePython
# accuracy score on the training data
X_train_prediction = classifier.predict(X_train)
training_data_accuracy = accuracy_score(X_train_prediction, Y_train)
ExamplePython
print('Accuracy score of the training data : ', training_data_accuracy)

Output

Output
Accuracy score of the training data :  0.7833876221498371
ExamplePython
# accuracy score on the test data
X_test_prediction = classifier.predict(X_test)
test_data_accuracy = accuracy_score(X_test_prediction, Y_test)
ExamplePython
print('Accuracy score of the test data : ', test_data_accuracy)

Output

Output
Accuracy score of the test data :  0.7727272727272727

Making a Predictive System

ExamplePython
input_data = (5,166,72,19,175,25.8,0.587,51)

# changing the input_data to numpy array
input_data_as_numpy_array = np.asarray(input_data)

# reshape the array as we are predicting for one instance
input_data_reshaped = input_data_as_numpy_array.reshape(1,-1)

prediction = classifier.predict(input_data_reshaped)
print(prediction)

if (prediction[0] == 0):
  print('The person is not diabetic')
else:
  print('The person is diabetic')

Output

Output
[1]
The person is diabetic

Output

Output
/usr/local/lib/python3.7/dist-packages/sklearn/base.py:451: UserWarning: X does not have valid feature names, but SVC was fitted with feature names
  "X does not have valid feature names, but"

Saving the trained model

ExamplePython
import pickle
ExamplePython
filename = 'diabetes_model.sav'
pickle.dump(classifier, open(filename, 'wb'))
ExamplePython
# loading the saved model
loaded_model = pickle.load(open('diabetes_model.sav', 'rb'))
ExamplePython
input_data = (5,166,72,19,175,25.8,0.587,51)

# changing the input_data to numpy array
input_data_as_numpy_array = np.asarray(input_data)

# reshape the array as we are predicting for one instance
input_data_reshaped = input_data_as_numpy_array.reshape(1,-1)

prediction = loaded_model.predict(input_data_reshaped)
print(prediction)

if (prediction[0] == 0):
  print('The person is not diabetic')
else:
  print('The person is diabetic')

Output

Output
[1]
The person is diabetic

Output

Output
/usr/local/lib/python3.7/dist-packages/sklearn/base.py:451: UserWarning: X does not have valid feature names, but SVC was fitted with feature names
  "X does not have valid feature names, but"
ExamplePython
for column in X.columns:
  print(column)

Output

Output
Pregnancies
Glucose
BloodPressure
SkinThickness
Insulin
BMI
DiabetesPedigreeFunction
Age

Keep going: ← Lesson 59 · Lesson 61 → · Track it in the Self Guide