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 [2]:
from sklearn import naive_bayes
from sklearn import metrics
import numpy as np
import csv

Reading data file as list object

In [8]:
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 [9]:
(c,d) = readFileThroughCSV("loanacceptance.csv")
# shape of the variables
(500, 6)

Fitting a naive bayes model

In [5]:
# Note that only 80% of the dataset is being used for training
clf = naive_bayes.GaussianNB()[0:400,:],y=c[0:400])
GaussianNB(priors=None, var_smoothing=1e-09)

Printing performance metrics

In [6]:
# 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.6625
R-square accuracy 0.59
Testing accuracy 0.59

Always look at the confusion matrix

In [7]:
m = metrics.confusion_matrix(c[indices],c_predicted)
[[11 19]
 [22 48]]