The data was collected and made available by “National Institute of Diabetes and Digestive and Kidney Diseases” as part of the Pima Indians Diabetes Database. Several constraints were placed on the selection of these instances from a larger database. In particular, all patients here belong to the Pima Indian heritage (subgroup of Native Americans), and are females of ages 21 and above.
The columns of the dataset are as follows:
You can download the dataset from here: https://www.kaggle.com/kandij/diabetes-dataset
Before getting into implementing the first application of cross validation, let us first implement Logistic Regression classifier to show how the random state affects the accuracy. Once we have implemented that, we will go ahead and see how to prevent the fluctuating values of accuracy caused due to random state
import pandas as pd
import numpy as np
df = pd.read_csv("diabetes2.csv")
df.head()
df.shape
from sklearn.utils import shuffle
df_shuffle = shuffle(df)
df_shuffle.head()
DV = 'Outcome'
X = df_shuffle.drop(DV,axis=1)
Y = df_shuffle[DV]
X.head()
Y.head()
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,Y,test_size =0.3, random_state = 30)
X_train.shape
X_test.shape
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(X_train,y_train)
predicted_score = model.predict(X_test)
predicted_score
In this case if we re-run the model again, our model accuracy will change. To prevent this fluctuating accuracy which is caused due to the random state, we will implement different types of cross validation
model.score(X_test,y_test)
K- Fold Cross Validation will work as illustrated in the below sample figure:
Suppose, we have 10K records in our dataset, and the K value we are selecting here is 10. Below figure shows how that data is splitted as Train Test Split for 10 iterations as our K value is 10.
So, K = 10000/10 => 1000
This means that each Test split would be having 1000 records.
Let’s try to understand how the K Fold Cross Validation works. In the first iteration, the first set of 1000 records would be considered as the Test Split and the rest would be the Train Split.Similarly for the 2nd experiment/iteration, the next block of 1000 records will be considered as the Test Split and the 1st block and the remaining blocks after the 2nd block of Test records would be considered as the Train Split. This process will continue till the end of the 10th experiment/iteration. For every Experiment/Iteration we will get the accuracy of the model until we reach the end of the experiment/iteration.
Based on the results we get for the accuracy, we could take the mean of all the 10 accuracy results and provide the overall result for model performance or we could also provide the upper bound and lower bound percentage for the model specifying the model performance.

from sklearn.model_selection import cross_val_score
score = cross_val_score(model, X,Y,cv=15)
score
score.mean()
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import accuracy_score
'''Creating a list to store the accuracy scores for the splits'''
accuracy = []
'''Initiating the StratifiedKFold function by passing the split value(n_splits) and random state as none'''
str_fied = StratifiedKFold(n_splits=15,random_state=None)
##Splitting the dependent(Y) and Independent(X) feature with the StratifiedKFold function
#and looping through their train(train_index) and test index(test_index)
for train_index, test_index in str_fied.split(X,Y):
#print("Train Index: ",train_index, "Test Index: ",test_index)
#Retrieving the values for training( X0_train,Y0_train) and testing(X0_test,Y0_test) set by passing the
#index values to the dependent(Y) and independent(X) features
X0_train, X0_test = X.iloc[train_index],X.iloc[test_index]
Y0_train, Y0_test = Y.iloc[train_index],Y.iloc[test_index]
# Fitting the model with the training set
model.fit(X0_train,Y0_train)
# predicting the model on the testing set'''
predict = model.predict(X0_test)
# Evaluating the accuracy for all the 15 splits'''
score = accuracy_score(predict,Y0_test)
accuracy.append(score)
print(accuracy)
np.mean(accuracy)
max(accuracy)
min(accuracy)
From the above 2 approaches we have got the same results for the accuracy.Therefore we could choose anyone of them. However if the volume of the data changes, then we might have different results for the 2 approaches. And also the accuracy depends on the no of splits. In this case we have taken no of splits as 15. If we take 10, then StratifiedKfolds cross validation would yield better results
Cross Validation helps us evaluate which model should be a best fit for predicting results. Let's see how we could use cross validation to choose the best model
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
from sklearn.model_selection import cross_val_score
knnclassifier = KNeighborsClassifier(n_neighbors=4)
print(cross_val_score(knnclassifier, X, Y, cv=10, scoring ='accuracy').mean())
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
print (cross_val_score(logreg, X, Y, cv=10, scoring = 'accuracy').mean())
Based on the results for the 2 models, we could conclude that Logistic regression is a better option here. So we will choose Logistic Regression over K-Nearest neighbours.