Week10 KNN Practical
Week10 KNN Practical
Week10 KNN Practical
Objectives
After completing this lab you will be able to:
In this Lab you will load a customer dataset, fit the data, and use K-Nearest Neighbors to predict a
data point. But what is K-Nearest Neighbors?
K-Nearest Neighbors is an algorithm for supervised learning. Where the data is 'trained' with data
points corresponding to their classification. Once a point is to be predicted, it takes into account
the 'K' nearest points to it to determine it's classification.
In this case, we have data points of Class A and B. We want to predict what the star (test data point)
is. If we consider a k value of 3 (3 nearest data points) we will obtain a prediction of Class B. Yet if
we consider a k value of 6, we will obtain a prediction of Class A.
In this sense, it is important to consider the value of k. But hopefully from this diagram, you should
get a sense of what the K-Nearest Neighbors algorithm is. It considers the 'K' Nearest Neighbors
(points) when it predicts the classification of the test point.
Page | 1
import numpy as np
from sklearn import preprocessing
%matplotlib inline
The example focuses on using demographic data, such as region, age, and marital, to predict usage
patterns.
The target field, called custcat, has four possible values that correspond to the four customer
groups, as follows: 1- Basic Service 2- E-Service 3- Plus Service 4- Total Service
Our objective is to build a classifier, to predict the class of unknown cases. We will use a specific
type of classification called K nearest neighbour.
Let’s download the dataset. To download the data, we will use !wget to download it from IBM
Object Storage.
!wget -O teleCust1000t.csv https://cf-courses-data.s3.us.cloud-object-stora
ge.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Mo
dule%203/data/teleCust1000t.csv
281 Plus Service, 266 Basic-service, 236 Total Service, and 217 E-Service customers
You can easily explore your data using visualization techniques:.
df.hist(column='income', bins=50)
Feature set
Lets define feature sets, X:.
df.columns
To use scikit-learn library, we have to convert the Pandas data frame to a Numpy array:.
X = df[['region', 'tenure','age', 'marital', 'address', 'income', 'ed', 'employ','retire', 'gender', 'reside']] .value
s #.astype(float)
X[0:5]
Page | 2
Normalize Data
Data Standardization give data zero mean and unit variance, it is good practice, especially for
algorithms such as KNN which is based on distance of cases:.
X = preprocessing.StandardScaler().fit(X).transform(X.astype(float))
X[0:5]
It is important that our models have a high, out-of-sample accuracy, because the purpose of any
model, of course, is to make correct predictions on unknown data. So how can we improve out-of-
sample accuracy? One way is to use an evaluation approach called Train/Test Split. Train/Test Split
involves splitting the dataset into training and testing sets respectively, which are mutually
exclusive. After which, you train with the training set and test with the testing set.
This will provide a more accurate evaluation on out-of-sample accuracy because the testing dataset
is not part of the dataset that have been used to train the data. It is more realistic for real world
problems.
Classification
K nearest neighbor (KNN)
Import library
Classifier implementing the k-nearest neighbors vote..
from sklearn.neighbors import KNeighborsClassifier
Training
Lets start the algorithm with k=4 for now:.
k=4
#Train Model and Predict
neigh = KNeighborsClassifier(n_neighbors = k).fit(X_train,y_train)
neigh
Predicting
we can use the model to predict the test set:.
yhat = neigh.predict(X_test)
yhat[0:5]
Accuracy evaluation
Page | 3
In multilabel classification, accuracy classification score is a function that computes subset
accuracy. This function is equal to the jaccard_score function. Essentially, it calculates how closely
the actual labels and predicted labels are matched in the test set..
from sklearn import metrics
print("Train set Accuracy: ", metrics.accuracy_score(y_train, neigh.predict(X_train)))
print("Test set Accuracy: ", metrics.accuracy_score(y_test, yhat))
Practice
Can you build the model again, but this time with k=6?.
# write your code here
for n in range(1,Ks):
std_acc[n-1]=np.std(yhat==y_test)/np.sqrt(yhat.shape[0])
mean_acc
Page | 4