K-NN Classifier – R

0
136

In this section we would cover K-NN in R. As we have already covered basics of K-NN algorithm in our previous topic, so in this section we would look into R Packages we need to have in our system, R Commands required to implement the K-NN logic. So Let us start with our step by step process of implementation of K-NN.

Step 1: Set up a working library. Setting up a working library is always of great help. Once we decided on working library we need not change file referencing or any while reading data set from a particular directory. “setwd” is the command used with path followed in quotes.

K_C1

Step 2: Read the data set from working library. In this analysis we would use “Loan Defaults” data set to understand the K-NN logic. Use the following command to read the data.

K_C2

Step 3: Install the R- Packages required for K-NN logic implementation. We would download “class” package using the following command. The second command “library” helps to activate/select the package once we download the package.

K_C3

Step 4: In our analysis we would need just last 3 variables to implement the K-NN logic. So we would select last three variables using the following commands.

K_C4

Step 5: Since range of two of our predictor variables is very different, while Age varies from 18-60 whereas salary varies from 1127-142293. We need to do feature scaling so that both of the variables have same proportional impact on the target variable. In the following command we are excluding the target variable from feature scaling which is at position 3

K_C5

Step 6: Finally use the following command to implement the K-NN algorithm

K_C6

Step 7: Testing the accuracy of K-NN using the confusion matrix

K_C7

 

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here