The file "loanacceptance.csv" contains various attributes of 500 customers based on which loan has either been granted or denied. You have to create a system that automatically decides whether to grant a loan or not to grant a loan.

Importing libraries

In [3]:
from sklearn import neighbors
from sklearn import metrics
import numpy as np
import csv

Reading data file as list object

In [4]:
def readFileThroughCSV(filename):
    csvfile = open(filename)

    # creating a csv reader object
    readerobject = csv.reader(csvfile, delimiter=',')
    lst = list(readerobject)

    # removing first row from list
    lst = lst[1:]
    arr = np.array(lst)
    data = arr.astype(float)

    # extract last column which is classification label
    c = data[:,-1]
    # extract remaining data
    d = data[:,1:-1]
In [5]:
(c,d) = readFileThroughCSV("loanacceptance.csv")
# shape of the variables
(500, 6)

Fitting a K-nearest neighbor model

In [6]:
# Note that only 80% of the dataset is being used for training
clf = neighbors.KNeighborsClassifier(n_neighbors=10)[0:400,:],y=c[0:400])
KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
           metric_params=None, n_jobs=None, n_neighbors=10, p=2,

Printing performance metrics

In [7]:
# returns accuracy
print("Training accuracy",clf.score(X=d[:400,:],y=c[:400]))
# for decision trees clf.score returns the R-squared value (it can be negative as well in case of bad performance)
print("R-square accuracy",clf.score(X=d[400:,:],y=c[400:]))

indices = range(400,500)
c_predicted = clf.predict(d[indices,:])

print("Testing accuracy",metrics.accuracy_score(c[indices],c_predicted))
Training accuracy 0.7675
R-square accuracy 0.69
Testing accuracy 0.69

Always look at the confusion matrix

In [8]:
m = metrics.confusion_matrix(c[indices],c_predicted)
[[13 17]
 [14 56]]