# Machine Learning: Pima Indians Diabetes

# Introduction¶

The **Pima** are a group of **Native Americans** living in Arizona. A genetic predisposition allowed this group to survive normally to a diet poor of carbohydrates for years. In the recent years, because of a sudden shift from traditional agricultural crops to processed foods, together with a decline in physical activity, made them develop **the highest prevalence of type 2 diabetes** and for this reason they have been subject of many studies.

## Dataset¶

The dataset includes data from **768** women with **8** characteristics, in particular:

- Number of times pregnant
- Plasma glucose concentration a 2 hours in an oral glucose tolerance test
- Diastolic blood pressure (mm Hg)
- Triceps skin fold thickness (mm)
- 2-Hour serum insulin (mu U/ml)
- Body mass index (weight in kg/(height in m)^2)
- Diabetes pedigree function
- Age (years)

The last column of the dataset indicates if the person has been diagnosed with diabetes (1) or not (0)

### Source¶

The original dataset is available at **UCI Machine Learning Repository** and can be downloaded from this address: http://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes

## The problem¶

The type of dataset and problem is a classic **supervised binary classification**. Given a number of elements all with certain characteristics (features), we want to build a machine learning model to identify people affected by type 2 diabetes.

To solve the problem we will have to analyse the data, do any required transformation and normalisation, apply a machine learning algorithm, train a model, check the performance of the trained model and iterate with other algorithms until we find the most performant for our type of dataset.

# Imports and configuration¶

```
# We import the libraries needed to read the dataset
import os
import pandas as pd
import numpy as np
```

```
# We placed the dataset under datasets/ sub folder
DATASET_PATH = 'datasets/'
```

# Load the dataset¶

```
# We read the data from the CSV file
data_path = os.path.join(DATASET_PATH, 'pima-indians-diabetes.csv')
dataset = pd.read_csv(data_path, header=None)
# Because thr CSV doesn't contain any header, we add column names
# using the description from the original dataset website
dataset.columns = [
"NumTimesPrg", "PlGlcConc", "BloodP",
"SkinThick", "TwoHourSerIns", "BMI",
"DiPedFunc", "Age", "HasDiabetes"]
```

# Inspect the Dataset¶

```
# Check the shape of the data: we have 768 rows and 9 columns:
# the first 8 columns are features while the last one
# is the supervised label (1 = has diabetes, 0 = no diabetes)
dataset.shape
```

```
# Visualise a table with the first rows of the dataset, to
# better understand the data format
dataset.head()
```

## Data correlation matrix¶

The correlation matrix is an important tool to understand the correlation between the different characteristics. The values range from -1 to 1 and the closer a value is to 1 the bettere correlation there is between two characteristics. Let's calculate the correlation matrix for our dataset.

```
corr = dataset.corr()
corr
```

I'm not a doctor and I don't have any knowledge of medicine, but from the data I can guess that **the greater the age or the BMI of a patient is, the greater probabilities are the patient can develop type 2 diabetes**.

```
%matplotlib inline
import seaborn as sns
sns.heatmap(corr, annot = True)
```

# Visualise the Dataset¶

Visualising the data is an important step of the data analysis. With a graphical visualisation of the data we have a better understanding of the various features values distribution: for example we can understand what's the average age of the people or the average BMI etc...

We could of course limit our inspection to the table visualisation, but we could miss important things that may affect our model precision.

```
import matplotlib.pyplot as plt
dataset.hist(bins=50, figsize=(20, 15))
plt.show()
```

An important thing I notice in the dataset (and that wasn't obvious at the beginning) is the fact that some people have **null (zero) values** for some of the features: it's not quite possible to have 0 as BMI or for the blood pressure.

How can we deal with similar values? We will see it later during the **data transformation** phase.

# Data cleaning and transformation¶

We have noticed from the previous analysis that some patients have missing data for some of the features. Machine learning algorithms don't work very well when the data is missing so we have to find a solution to "clean" the data we have.

The easiest option could be to eliminate all those patients with null/zero values, but in this way we would eliminate a lot of important data.

Another option is to calculate the **median** value for a specific column and substitute that value everywhere (in the same column) we have zero or null. Let's see how to apply this second method.

```
# Calculate the median value for BMI
median_bmi = dataset['BMI'].median()
# Substitute it in the BMI column of the
# dataset where values are 0
dataset['BMI'] = dataset['BMI'].replace(
to_replace=0, value=median_bmi)
```

```
# Calculate the median value for BloodP
median_bloodp = dataset['BloodP'].median()
# Substitute it in the BloodP column of the
# dataset where values are 0
dataset['BloodP'] = dataset['BloodP'].replace(
to_replace=0, value=median_bloodp)
```

```
# Calculate the median value for PlGlcConc
median_plglcconc = dataset['PlGlcConc'].median()
# Substitute it in the PlGlcConc column of the
# dataset where values are 0
dataset['PlGlcConc'] = dataset['PlGlcConc'].replace(
to_replace=0, value=median_plglcconc)
```

```
# Calculate the median value for SkinThick
median_skinthick = dataset['SkinThick'].median()
# Substitute it in the SkinThick column of the
# dataset where values are 0
dataset['SkinThick'] = dataset['SkinThick'].replace(
to_replace=0, value=median_skinthick)
```

```
# Calculate the median value for TwoHourSerIns
median_twohourserins = dataset['TwoHourSerIns'].median()
# Substitute it in the TwoHourSerIns column of the
# dataset where values are 0
dataset['TwoHourSerIns'] = dataset['TwoHourSerIns'].replace(
to_replace=0, value=median_twohourserins)
```

I haven't transformed all the columns, because for some values can make sense to be zero (like "Number of times pregnant").

# Splitting the Dataset¶

Now that we have transformed the data we need to split the dataset in two parts: a training dataset and a test dataset. Splitting the dataset is a very important step for supervised machine learning models. Basically we are going to use the first part to train the model (ignoring the column with the pre assigned label), then we use the trained model to make predictions on new data (which is the test dataset, not part of the training set) and compare the predicted value with the pre assigned label.

```
# Split the training dataset in 80% / 20%
from sklearn.model_selection import train_test_split
train_set, test_set = train_test_split(
dataset, test_size=0.2, random_state=42)
```

```
# Separate labels from the rest of the dataset
train_set_labels = train_set["HasDiabetes"].copy()
train_set = train_set.drop("HasDiabetes", axis=1)
test_set_labels = test_set["HasDiabetes"].copy()
test_set = test_set.drop("HasDiabetes", axis=1)
```

# Feature Scaling¶

One of the most important data transformations we need to apply is the **features scaling**. Basically most of the machine learning **algorithms don't work very well if the features have a different set of values**. In our case for example the Age ranges from 20 to 80 years old, while the number of times a patient has been pregnant ranges from 0 to 17. For this reason we need to apply a proper transformation.

```
# Apply a scaler
from sklearn.preprocessing import MinMaxScaler as Scaler
scaler = Scaler()
scaler.fit(train_set)
train_set_scaled = scaler.transform(train_set)
test_set_scaled = scaler.transform(test_set)
```

## Scaled Values¶

```
df = pd.DataFrame(data=train_set_scaled)
df.head()
```

# Select and train a model¶

It's not possible to know in advance which algorithm will work better with our dataset. We need to compare a few and select the one with the "best score".

## Comparing multiple algorithms¶

To compare multiple algorithms with the same dataset, there is a very nice utility in sklearn called **model_selection**. We create a list of algorithms and then we score them using the same comparison method. At the end we pick the one with the best score.

```
# Import all the algorithms we want to test
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.svm import LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeRegressor
```

```
# Import the slearn utility to compare algorithms
from sklearn import model_selection
```

```
# Prepare an array with all the algorithms
models = []
models.append(('LR', LogisticRegression()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('NB', GaussianNB()))
models.append(('SVC', SVC()))
models.append(('LSVC', LinearSVC()))
models.append(('RFC', RandomForestClassifier()))
models.append(('DTR', DecisionTreeRegressor()))
```

```
# Prepare the configuration to run the test
seed = 7
results = []
names = []
X = train_set_scaled
Y = train_set_labels
```

```
# Every algorithm is tested and results are
# collected and printed
for name, model in models:
kfold = model_selection.KFold(
n_splits=10, random_state=seed)
cv_results = model_selection.cross_val_score(
model, X, Y, cv=kfold, scoring='accuracy')
results.append(cv_results)
names.append(name)
msg = "%s: %f (%f)" % (
name, cv_results.mean(), cv_results.std())
print(msg)
```

```
# boxplot algorithm comparison
fig = plt.figure()
fig.suptitle('Algorithm Comparison')
ax = fig.add_subplot(111)
plt.boxplot(results)
ax.set_xticklabels(names)
plt.show()
```

It looks like that using this comparison method, the most performant algorithm is **SVC**.

## Find the best parameters for SVC¶

The default parameters for an algorithm are rarely the best ones for our dataset. Using sklearn we can easily build a parameters grid and try all the possible combinations. At the end we inspect the `best_estimator_`

property and get the best ones for our dataset.

```
from sklearn.model_selection import GridSearchCV
param_grid = {
'C': [1.0, 10.0, 50.0],
'kernel': ['linear', 'rbf', 'poly', 'sigmoid'],
'shrinking': [True, False],
'gamma': ['auto', 1, 0.1],
'coef0': [0.0, 0.1, 0.5]
}
model_svc = SVC()
grid_search = GridSearchCV(
model_svc, param_grid, cv=10, scoring='accuracy')
grid_search.fit(train_set_scaled, train_set_labels)
```

```
# Print the bext score found
grid_search.best_score_
```

## Apply the parameters to the model and train it¶

```
# Create an instance of the algorithm using parameters
# from best_estimator_ property
svc = grid_search.best_estimator_
# Use the whole dataset to train the model
X = np.append(train_set_scaled, test_set_scaled, axis=0)
Y = np.append(train_set_labels, test_set_labels, axis=0)
# Train the model
svc.fit(X, Y)
```

# Make a Prediction¶

```
# We create a new (fake) person having the three most correated values high
new_df = pd.DataFrame([[6, 168, 72, 35, 0, 43.6, 0.627, 65]])
# We scale those values like the others
new_df_scaled = scaler.transform(new_df)
```

```
# We predict the outcome
prediction = svc.predict(new_df_scaled)
```

```
# A value of "1" means that this person is likley to have type 2 diabetes
prediction
```

## Conclusion¶

We finally find a **score of 76%** using **SVC algorithm** and parameters optimisation. Please note that there may be still space for further analysis and optimisation, for example trying different data transformations or trying algorithms that haven't been tested yet. Once again I want to repeat that training a machine learning model to solve a problem with a specific dataset is a **try / fail / improve** process.

## Credits¶

First of all I need to thank my wife **Dr Daniela Ceccarelli Ceccarelli** for helping me to validate this experiment and for checking I didn't write anything wrong from a medical point of view. Then I want to thank **Dr. Jason Brownlee** for his fantastic blog which has helped me a lot to understand many concepts used here. I strongly advise you to have a look at his blog: https://machinelearningmastery.com