K nearest neighbour Lab 5

library(caret)
## Loading required package: ggplot2
## Loading required package: lattice
library(mlbench)
library(partykit)
## Loading required package: grid
## Loading required package: libcoin
## Loading required package: mvtnorm
# load PimaIndiansDiabetes dataset from mlbench library
data(PimaIndiansDiabetes)
# leave one out evaluation
ctrl1 <- trainControl(method="LOOCV")
# ensure reproducibility of results by setting the seed to a known value
set.seed(123)
#use knn on the PimaIndiansDiabetes dataset
mod11.knn<- train(diabetes~., data=PimaIndiansDiabetes, 
        method="knn", trControl=ctrl1)

To check accuracy for values k values

print(mod11.knn)
## k-Nearest Neighbors 
## 
## 768 samples
##   8 predictor
##   2 classes: 'neg', 'pos' 
## 
## No pre-processing
## Resampling: Leave-One-Out Cross-Validation 
## Summary of sample sizes: 767, 767, 767, 767, 767, 767, ... 
## Resampling results across tuning parameters:
## 
##   k  Accuracy   Kappa    
##   5  0.7148438  0.3516514
##   7  0.7278646  0.3812564
##   9  0.7343750  0.3911584
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 9.
print(mod11.knn$results)
##   k  Accuracy     Kappa
## 1 5 0.7148438 0.3516514
## 2 7 0.7278646 0.3812564
## 3 9 0.7343750 0.3911584

To visualise the accuracy for various k values

plot(mod11.knn, type = "p")

## Get results for best k, which are stored in “pred”.

results1 <- (mod11.knn$pred[mod11.knn$pred$k == mod11.knn$bestTune$k,])

Remove unwanted columns (k and instance number)

results1$k <- NULL
results1$rowIndex <- NULL

Produce the confusion matrix.

table(results1)
##      obs
## pred  neg pos
##   neg 421 125
##   pos  79 143
# using same train control as before, i.e. leave one out (defined above)
# # ensure reproducibility of results by setting the seed to a known value
set.seed(123)
mod21.knn<- train(diabetes~., data=PimaIndiansDiabetes, 
        method="knn", tuneGrid=expand.grid(k=1:20), trControl=ctrl1)
print(mod21.knn)
## k-Nearest Neighbors 
## 
## 768 samples
##   8 predictor
##   2 classes: 'neg', 'pos' 
## 
## No pre-processing
## Resampling: Leave-One-Out Cross-Validation 
## Summary of sample sizes: 767, 767, 767, 767, 767, 767, ... 
## Resampling results across tuning parameters:
## 
##   k   Accuracy   Kappa    
##    1  0.6796875  0.2938221
##    2  0.6627604  0.2660507
##    3  0.6940104  0.3189023
##    4  0.6927083  0.3056696
##    5  0.7148438  0.3516514
##    6  0.7291667  0.3780989
##    7  0.7278646  0.3812564
##    8  0.7161458  0.3505462
##    9  0.7343750  0.3911584
##   10  0.7382812  0.3984850
##   11  0.7330729  0.3876217
##   12  0.7343750  0.3900586
##   13  0.7473958  0.4189080
##   14  0.7408854  0.3990374
##   15  0.7408854  0.4012224
##   16  0.7382812  0.3952045
##   17  0.7526042  0.4235874
##   18  0.7565104  0.4321683
##   19  0.7604167  0.4397361
##   20  0.7434896  0.3996000
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 19.
plot(mod21.knn, type="p")

#Getting the results
results2 <- (mod21.knn$pred[mod21.knn$pred$k == mod21.knn$bestTune$k,])
#Remove unwanted columns (k and instance number)
results2$k <- NULL
results2$rowIndex <- NULL
## Previous table for comparison.
print("Previous confusion matrix")
## [1] "Previous confusion matrix"
table(results1)
##      obs
## pred  neg pos
##   neg 421 125
##   pos  79 143
# Produce the confusion matrix.

print("Confusion matrix for best k between 1 and 20")
## [1] "Confusion matrix for best k between 1 and 20"
table(results2)
##      obs
## pred  neg pos
##   neg 442 126
##   pos  58 142

It can be seen that in the new matrix there are more negatives predicted as negatives whereas the correct positive predictions remains almost identical.

control1 <- trainControl(method = "repeatedcv", number = 10, repeats = 3)
set.seed(123)
mod21.knn<- train(diabetes~., data=PimaIndiansDiabetes, 
        method="knn", tuneGrid=expand.grid(k=1:20), trControl=ctrl1)
print(mod21.knn)
## k-Nearest Neighbors 
## 
## 768 samples
##   8 predictor
##   2 classes: 'neg', 'pos' 
## 
## No pre-processing
## Resampling: Leave-One-Out Cross-Validation 
## Summary of sample sizes: 767, 767, 767, 767, 767, 767, ... 
## Resampling results across tuning parameters:
## 
##   k   Accuracy   Kappa    
##    1  0.6796875  0.2938221
##    2  0.6627604  0.2660507
##    3  0.6940104  0.3189023
##    4  0.6927083  0.3056696
##    5  0.7148438  0.3516514
##    6  0.7291667  0.3780989
##    7  0.7278646  0.3812564
##    8  0.7161458  0.3505462
##    9  0.7343750  0.3911584
##   10  0.7382812  0.3984850
##   11  0.7330729  0.3876217
##   12  0.7343750  0.3900586
##   13  0.7473958  0.4189080
##   14  0.7408854  0.3990374
##   15  0.7408854  0.4012224
##   16  0.7382812  0.3952045
##   17  0.7526042  0.4235874
##   18  0.7565104  0.4321683
##   19  0.7604167  0.4397361
##   20  0.7434896  0.3996000
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 19.
plot(mod21.knn, type="p")

ctrl <- trainControl(method="repeatedcv", number=10, repeats=3)
set.seed(123)
mod12 <- train(diabetes~., data=PimaIndiansDiabetes, method="knn", trControl=ctrl)
print(mod12)
## k-Nearest Neighbors 
## 
## 768 samples
##   8 predictor
##   2 classes: 'neg', 'pos' 
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold, repeated 3 times) 
## Summary of sample sizes: 691, 691, 691, 692, 692, 691, ... 
## Resampling results across tuning parameters:
## 
##   k  Accuracy   Kappa    
##   5  0.7248690  0.3721698
##   7  0.7326954  0.3906039
##   9  0.7370301  0.4006972
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 9.
plot(mod12)

mod31.knn <- train(diabetes~., data=PimaIndiansDiabetes, 
method="knn", tuneGrid=expand.grid(k=c(21,23)), trControl=ctrl1)
print(mod31.knn)
## k-Nearest Neighbors 
## 
## 768 samples
##   8 predictor
##   2 classes: 'neg', 'pos' 
## 
## No pre-processing
## Resampling: Leave-One-Out Cross-Validation 
## Summary of sample sizes: 767, 767, 767, 767, 767, 767, ... 
## Resampling results across tuning parameters:
## 
##   k   Accuracy   Kappa    
##   21  0.7578125  0.4346863
##   23  0.7552083  0.4265014
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 21.
plot(mod31.knn, type="p")

# exploring different dataset to find best and worst k values (iris dataset)
data("iris")
# training the iris dataset with knn algorithm using the leave one out evaluation method
ctrl2 <- trainControl(method = "LOOCV")
set.seed(123)
irisknn <- train(Species ~.,
                 data = iris,
                 method = "knn",
                 trControl = ctrl2)
# printing the result from above
print(irisknn)
## k-Nearest Neighbors 
## 
## 150 samples
##   4 predictor
##   3 classes: 'setosa', 'versicolor', 'virginica' 
## 
## No pre-processing
## Resampling: Leave-One-Out Cross-Validation 
## Summary of sample sizes: 149, 149, 149, 149, 149, 149, ... 
## Resampling results across tuning parameters:
## 
##   k  Accuracy   Kappa
##   5  0.9666667  0.95 
##   7  0.9666667  0.95 
##   9  0.9600000  0.94 
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 7.
# the final value used for the above model was k = 7
# plotting the k values for above
plot(irisknn)

## notice that 5 and 7 have the-same values for the percemtage of k and are both the best k values

# using confusion matrix
result3 <- (irisknn$pred[irisknn$pred$k == irisknn$bestTune$k,])
# printing the confusion matrix result for best k
result3$rowIndex = NULL
result3$k = NULL
table(result3)
##             obs
## pred         setosa versicolor virginica
##   setosa         50          0         0
##   versicolor      0         46         1
##   virginica       0          4        49
plot(irisknn, type = "p")

### To check the range of values for numeric attributes, use summary().

summary(PimaIndiansDiabetes)
##     pregnant         glucose         pressure         triceps     
##  Min.   : 0.000   Min.   :  0.0   Min.   :  0.00   Min.   : 0.00  
##  1st Qu.: 1.000   1st Qu.: 99.0   1st Qu.: 62.00   1st Qu.: 0.00  
##  Median : 3.000   Median :117.0   Median : 72.00   Median :23.00  
##  Mean   : 3.845   Mean   :120.9   Mean   : 69.11   Mean   :20.54  
##  3rd Qu.: 6.000   3rd Qu.:140.2   3rd Qu.: 80.00   3rd Qu.:32.00  
##  Max.   :17.000   Max.   :199.0   Max.   :122.00   Max.   :99.00  
##     insulin           mass          pedigree           age        diabetes 
##  Min.   :  0.0   Min.   : 0.00   Min.   :0.0780   Min.   :21.00   neg:500  
##  1st Qu.:  0.0   1st Qu.:27.30   1st Qu.:0.2437   1st Qu.:24.00   pos:268  
##  Median : 30.5   Median :32.00   Median :0.3725   Median :29.00            
##  Mean   : 79.8   Mean   :31.99   Mean   :0.4719   Mean   :33.24            
##  3rd Qu.:127.2   3rd Qu.:36.60   3rd Qu.:0.6262   3rd Qu.:41.00            
##  Max.   :846.0   Max.   :67.10   Max.   :2.4200   Max.   :81.00

To preprocess values so that they are normalised to a value in the range ranges (a MATRIX of min and max values for each attribute, default [0,1]) set the preProcess parameter to c(“range”).

set.seed(123)
mod51.knn<- train(diabetes~., data=PimaIndiansDiabetes, 
method="knn", tuneGrid=expand.grid(k=1:20),
preProcess=c("range"), trControl=ctrl1)
print(mod51.knn)
## k-Nearest Neighbors 
## 
## 768 samples
##   8 predictor
##   2 classes: 'neg', 'pos' 
## 
## Pre-processing: re-scaling to [0, 1] (8) 
## Resampling: Leave-One-Out Cross-Validation 
## Summary of sample sizes: 767, 767, 767, 767, 767, 767, ... 
## Resampling results across tuning parameters:
## 
##   k   Accuracy   Kappa    
##    1  0.7070312  0.3432854
##    2  0.6888021  0.3156969
##    3  0.7408854  0.4140057
##    4  0.7356771  0.4000924
##    5  0.7421875  0.4174686
##    6  0.7460938  0.4216689
##    7  0.7513021  0.4284111
##    8  0.7304688  0.3805293
##    9  0.7382812  0.4017301
##   10  0.7356771  0.3902950
##   11  0.7343750  0.3933461
##   12  0.7343750  0.3922542
##   13  0.7408854  0.4023089
##   14  0.7382812  0.3918881
##   15  0.7460938  0.4111171
##   16  0.7395833  0.3943600
##   17  0.7552083  0.4338060
##   18  0.7486979  0.4171569
##   19  0.7513021  0.4200221
##   20  0.7434896  0.3984924
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 17.
plot(mod51.knn, type="p")

### Standardisation: centering and scaling data Normally, numeric attributes are centered (mean is 0) and scaled (standard deviation of 1). To do this use preProcess() set to c(“center”, “scale”). Try

set.seed(1)
mod41.knn<- train(diabetes~., data=PimaIndiansDiabetes, 
method="knn", preProcess=c("center", "scale"), trControl=ctrl1)
print(mod41.knn)
## k-Nearest Neighbors 
## 
## 768 samples
##   8 predictor
##   2 classes: 'neg', 'pos' 
## 
## Pre-processing: centered (8), scaled (8) 
## Resampling: Leave-One-Out Cross-Validation 
## Summary of sample sizes: 767, 767, 767, 767, 767, 767, ... 
## Resampling results across tuning parameters:
## 
##   k  Accuracy   Kappa    
##   5  0.7421875  0.4111889
##   7  0.7408854  0.4119132
##   9  0.7408854  0.4055450
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 5.
plot(mod41.knn, type="p")

### To see the normalised dataset try

preProcValuesN <- preProcess(PimaIndiansDiabetes, method = c("range"))
diabetesNormalised <- predict(preProcValuesN, PimaIndiansDiabetes)
# checking the results. Use head for knitting so that the results appear
# in the knitted document. View shows them in a separate window.
# View(diabetesNormalised)
head(diabetesNormalised, 15)
##      pregnant   glucose  pressure   triceps   insulin      mass   pedigree
## 1  0.35294118 0.7437186 0.5901639 0.3535354 0.0000000 0.5007452 0.23441503
## 2  0.05882353 0.4271357 0.5409836 0.2929293 0.0000000 0.3964232 0.11656704
## 3  0.47058824 0.9195980 0.5245902 0.0000000 0.0000000 0.3472429 0.25362938
## 4  0.05882353 0.4472362 0.5409836 0.2323232 0.1111111 0.4187779 0.03800171
## 5  0.00000000 0.6884422 0.3278689 0.3535354 0.1985816 0.6423249 0.94363792
## 6  0.29411765 0.5829146 0.6065574 0.0000000 0.0000000 0.3815201 0.05251921
## 7  0.17647059 0.3919598 0.4098361 0.3232323 0.1040189 0.4619970 0.07258753
## 8  0.58823529 0.5778894 0.0000000 0.0000000 0.0000000 0.5260805 0.02391119
## 9  0.11764706 0.9899497 0.5737705 0.4545455 0.6418440 0.4545455 0.03415884
## 10 0.47058824 0.6281407 0.7868852 0.0000000 0.0000000 0.0000000 0.06575576
## 11 0.23529412 0.5527638 0.7540984 0.0000000 0.0000000 0.5603577 0.04824936
## 12 0.58823529 0.8442211 0.6065574 0.0000000 0.0000000 0.5663189 0.19598634
## 13 0.58823529 0.6984925 0.6557377 0.0000000 0.0000000 0.4038748 0.58198121
## 14 0.05882353 0.9497487 0.4918033 0.2323232 1.0000000 0.4485842 0.13663535
## 15 0.29411765 0.8341709 0.5901639 0.1919192 0.2068558 0.3845007 0.21733561
##           age diabetes
## 1  0.48333333      pos
## 2  0.16666667      neg
## 3  0.18333333      pos
## 4  0.00000000      neg
## 5  0.20000000      pos
## 6  0.15000000      neg
## 7  0.08333333      pos
## 8  0.13333333      neg
## 9  0.53333333      pos
## 10 0.55000000      pos
## 11 0.15000000      neg
## 12 0.21666667      pos
## 13 0.60000000      neg
## 14 0.63333333      pos
## 15 0.50000000      pos

To check that all the values are on the scale [0, 1] use the summary function.

summary(diabetesNormalised)
##     pregnant          glucose          pressure         triceps      
##  Min.   :0.00000   Min.   :0.0000   Min.   :0.0000   Min.   :0.0000  
##  1st Qu.:0.05882   1st Qu.:0.4975   1st Qu.:0.5082   1st Qu.:0.0000  
##  Median :0.17647   Median :0.5879   Median :0.5902   Median :0.2323  
##  Mean   :0.22618   Mean   :0.6075   Mean   :0.5664   Mean   :0.2074  
##  3rd Qu.:0.35294   3rd Qu.:0.7048   3rd Qu.:0.6557   3rd Qu.:0.3232  
##  Max.   :1.00000   Max.   :1.0000   Max.   :1.0000   Max.   :1.0000  
##     insulin             mass           pedigree            age        
##  Min.   :0.00000   Min.   :0.0000   Min.   :0.00000   Min.   :0.0000  
##  1st Qu.:0.00000   1st Qu.:0.4069   1st Qu.:0.07077   1st Qu.:0.0500  
##  Median :0.03605   Median :0.4769   Median :0.12575   Median :0.1333  
##  Mean   :0.09433   Mean   :0.4768   Mean   :0.16818   Mean   :0.2040  
##  3rd Qu.:0.15041   3rd Qu.:0.5455   3rd Qu.:0.23409   3rd Qu.:0.3333  
##  Max.   :1.00000   Max.   :1.0000   Max.   :1.00000   Max.   :1.0000  
##  diabetes 
##  neg:500  
##  pos:268  
##           
##           
##           
## 

To check the centered and scaled dataset use

preProcValuesCS <- preProcess(PimaIndiansDiabetes, 
method =c("center", "scale"))
diabetesCenteredScaled <- predict(preProcValuesCS, PimaIndiansDiabetes)
# View(diabetesCenteredScaled)
head(diabetesCenteredScaled, 15)
##       pregnant    glucose    pressure     triceps    insulin       mass
## 1   0.63953049  0.8477713  0.14954330  0.90667906 -0.6924393  0.2038799
## 2  -0.84433482 -1.1226647 -0.16044119  0.53055581 -0.6924393 -0.6839762
## 3   1.23307662  1.9424580 -0.26376935 -1.28737326 -0.6924393 -1.1025370
## 4  -0.84433482 -0.9975577 -0.16044119  0.15443255  0.1232213 -0.4937213
## 5  -1.14110788  0.5037269 -1.50370731  0.90667906  0.7653372  1.4088275
## 6   0.34275743 -0.1530851  0.25287146 -1.28737326 -0.6924393 -0.8108128
## 7  -0.25078869 -1.3416021 -0.98706650  0.71861743  0.0711579 -0.1258952
## 8   1.82662274 -0.1843619 -3.57027057 -1.28737326 -0.6924393  0.4195021
## 9  -0.54756176  2.3803327  0.04621514  1.53355115  4.0193026 -0.1893135
## 10  1.23307662  0.1284058  1.38948126 -1.28737326 -0.6924393 -4.0578295
## 11  0.04598437 -0.3407457  1.18282493 -1.28737326 -0.6924393  0.7112263
## 12  1.82662274  1.4733066  0.25287146 -1.28737326 -0.6924393  0.7619609
## 13  1.82662274  0.5662805  0.56285595 -1.28737326 -0.6924393 -0.6205579
## 14 -0.84433482  2.1301186 -0.47042568  0.15443255  6.6485067 -0.2400482
## 15  0.34275743  1.4107531  0.14954330 -0.09631628  0.8260779 -0.7854455
##      pedigree         age diabetes
## 1   0.4681869  1.42506672      pos
## 2  -0.3648230 -0.19054773      neg
## 3   0.6040037 -0.10551539      pos
## 4  -0.9201630 -1.04087112      neg
## 5   5.4813370 -0.02048305      pos
## 6  -0.8175458 -0.27558007      neg
## 7  -0.6756927 -0.61570943      pos
## 8  -1.0197620 -0.36061241      neg
## 9  -0.9473263  1.68016374      pos
## 10 -0.7239831  1.76519608      pos
## 11 -0.8477273 -0.27558007      neg
## 12  0.1965532  0.06454929      pos
## 13  2.9249624  2.02029310      neg
## 14 -0.2229699  2.19035777      pos
## 15  0.3474608  1.51009906      pos
# Checking summary of each attribute.
summary(diabetesCenteredScaled)
##     pregnant          glucose           pressure          triceps       
##  Min.   :-1.1411   Min.   :-3.7812   Min.   :-3.5703   Min.   :-1.2874  
##  1st Qu.:-0.8443   1st Qu.:-0.6848   1st Qu.:-0.3671   1st Qu.:-1.2874  
##  Median :-0.2508   Median :-0.1218   Median : 0.1495   Median : 0.1544  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6395   3rd Qu.: 0.6054   3rd Qu.: 0.5629   3rd Qu.: 0.7186  
##  Max.   : 3.9040   Max.   : 2.4429   Max.   : 2.7327   Max.   : 4.9187  
##     insulin             mass              pedigree            age         
##  Min.   :-0.6924   Min.   :-4.057829   Min.   :-1.1888   Min.   :-1.0409  
##  1st Qu.:-0.6924   1st Qu.:-0.595191   1st Qu.:-0.6885   1st Qu.:-0.7858  
##  Median :-0.4278   Median : 0.000941   Median :-0.2999   Median :-0.3606  
##  Mean   : 0.0000   Mean   : 0.000000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4117   3rd Qu.: 0.584390   3rd Qu.: 0.4659   3rd Qu.: 0.6598  
##  Max.   : 6.6485   Max.   : 4.452906   Max.   : 5.8797   Max.   : 4.0611  
##  diabetes 
##  neg:500  
##  pos:268  
##           
##           
##           
## 

normalising weatherplay

# load the dataset
data("WeatherPlay")

normalising weatherplay dataset

preProcValues <- preProcess(WeatherPlay, method = c("range"))
 
weatherNorm <- predict(preProcValues, WeatherPlay)

# checking normalised dataset
head(weatherNorm, 14)
##     outlook temperature  humidity windy play
## 1     sunny  1.00000000 0.6451613 false   no
## 2     sunny  0.76190476 0.8064516  true   no
## 3  overcast  0.90476190 0.6774194 false  yes
## 4     rainy  0.28571429 1.0000000 false  yes
## 5     rainy  0.19047619 0.4838710 false  yes
## 6     rainy  0.04761905 0.1612903  true   no
## 7  overcast  0.00000000 0.0000000  true  yes
## 8     sunny  0.38095238 0.9677419 false   no
## 9     sunny  0.23809524 0.1612903 false  yes
## 10    rainy  0.52380952 0.4838710 false  yes
## 11    sunny  0.52380952 0.1612903  true  yes
## 12 overcast  0.38095238 0.8064516  true  yes
## 13 overcast  0.80952381 0.3225806 false  yes
## 14    rainy  0.33333333 0.8387097  true   no
preProcessvalsWP <- preProcess(WeatherPlay, method = c("center", "scale"))
weatherstandard <- predict(preProcessvalsWP, WeatherPlay)
head(weatherstandard, 14)
##     outlook temperature   humidity windy play
## 1     sunny   1.7390672  0.3264046 false   no
## 2     sunny   0.9782253  0.8125392  true   no
## 3  overcast   1.4347305  0.4236315 false  yes
## 4     rainy  -0.5434585  1.3959007 false  yes
## 5     rainy  -0.8477953 -0.1597299 false  yes
## 6     rainy  -1.3043004 -1.1319990  true   no
## 7  overcast  -1.4564688 -1.6181336  true  yes
## 8     sunny  -0.2391217  1.2986737 false   no
## 9     sunny  -0.6956269 -1.1319990 false  yes
## 10    rainy   0.2173834 -0.1597299 false  yes
## 11    sunny   0.2173834 -1.1319990  true  yes
## 12 overcast  -0.2391217  0.8125392  true  yes
## 13 overcast   1.1303937 -0.6458645 false  yes
## 14    rainy  -0.3912901  0.9097661  true   no
summary(weatherstandard)
##      outlook   temperature         humidity          windy    play  
##  sunny   :5   Min.   :-1.4565   Min.   :-1.61813   false:8   yes:9  
##  overcast:4   1st Qu.:-0.6576   1st Qu.:-1.01047   true :6   no :5  
##  rainy   :5   Median :-0.2391   Median : 0.08334                    
##               Mean   : 0.0000   Mean   : 0.00000                    
##               3rd Qu.: 0.7880   3rd Qu.: 0.81254                    
##               Max.   : 1.7391   Max.   : 1.39590

excersise 5 from lab solutions

preProcWeather <- preProcess(WeatherPlay, method =c("center", "scale"))
WeatherCenteredScaled <- predict(preProcWeather, WeatherPlay)
# View(WeatherCenteredScaled)
head(WeatherCenteredScaled, 14)
##     outlook temperature   humidity windy play
## 1     sunny   1.7390672  0.3264046 false   no
## 2     sunny   0.9782253  0.8125392  true   no
## 3  overcast   1.4347305  0.4236315 false  yes
## 4     rainy  -0.5434585  1.3959007 false  yes
## 5     rainy  -0.8477953 -0.1597299 false  yes
## 6     rainy  -1.3043004 -1.1319990  true   no
## 7  overcast  -1.4564688 -1.6181336  true  yes
## 8     sunny  -0.2391217  1.2986737 false   no
## 9     sunny  -0.6956269 -1.1319990 false  yes
## 10    rainy   0.2173834 -0.1597299 false  yes
## 11    sunny   0.2173834 -1.1319990  true  yes
## 12 overcast  -0.2391217  0.8125392  true  yes
## 13 overcast   1.1303937 -0.6458645 false  yes
## 14    rainy  -0.3912901  0.9097661  true   no
# checking ranges for standardised data
summary(WeatherCenteredScaled)
##      outlook   temperature         humidity          windy    play  
##  sunny   :5   Min.   :-1.4565   Min.   :-1.61813   false:8   yes:9  
##  overcast:4   1st Qu.:-0.6576   1st Qu.:-1.01047   true :6   no :5  
##  rainy   :5   Median :-0.2391   Median : 0.08334                    
##               Mean   : 0.0000   Mean   : 0.00000                    
##               3rd Qu.: 0.7880   3rd Qu.: 0.81254                    
##               Max.   : 1.7391   Max.   : 1.39590
data("WeatherPlay")
#binarise nominal attributes – one-hot encoding

# make a copy
noClass <-WeatherPlay

# remove the class - it is not transformed
noClass$play <- NULL

set.seed(123)
#binarise nominal attributes - one-hot encoding
binaryVars <- dummyVars(~ ., data = noClass)
newWeather <- predict(binaryVars, newdata = noClass)

# add the class to the binarised dataset
binWeather <-cbind(newWeather, WeatherPlay[5])

# check the result. 
# View(binWeather) could have been used instead but it does not appear in the knitted document.

head(binWeather, 14)
##    outlook.sunny outlook.overcast outlook.rainy temperature humidity
## 1              1                0             0          85       85
## 2              1                0             0          80       90
## 3              0                1             0          83       86
## 4              0                0             1          70       96
## 5              0                0             1          68       80
## 6              0                0             1          65       70
## 7              0                1             0          64       65
## 8              1                0             0          72       95
## 9              1                0             0          69       70
## 10             0                0             1          75       80
## 11             1                0             0          75       70
## 12             0                1             0          72       90
## 13             0                1             0          81       75
## 14             0                0             1          71       91
##    windy.false windy.true play
## 1            1          0   no
## 2            0          1   no
## 3            1          0  yes
## 4            1          0  yes
## 5            1          0  yes
## 6            0          1   no
## 7            0          1  yes
## 8            1          0   no
## 9            1          0  yes
## 10           1          0  yes
## 11           0          1  yes
## 12           0          1  yes
## 13           1          0  yes
## 14           0          1   no

Excercise 6

noClass1 <- WeatherPlay
noClass1$play <- NULL
binaryVars1 <- dummyVars(~., data = noClass1)
newWeather1 <- predict(binaryVars1, newdata = noClass1)
binWeather1 <- cbind(newWeather1, WeatherPlay[5] )
head(binWeather1, 14)
##    outlook.sunny outlook.overcast outlook.rainy temperature humidity
## 1              1                0             0          85       85
## 2              1                0             0          80       90
## 3              0                1             0          83       86
## 4              0                0             1          70       96
## 5              0                0             1          68       80
## 6              0                0             1          65       70
## 7              0                1             0          64       65
## 8              1                0             0          72       95
## 9              1                0             0          69       70
## 10             0                0             1          75       80
## 11             1                0             0          75       70
## 12             0                1             0          72       90
## 13             0                1             0          81       75
## 14             0                0             1          71       91
##    windy.false windy.true play
## 1            1          0   no
## 2            0          1   no
## 3            1          0  yes
## 4            1          0  yes
## 5            1          0  yes
## 6            0          1   no
## 7            0          1  yes
## 8            1          0   no
## 9            1          0  yes
## 10           1          0  yes
## 11           0          1  yes
## 12           0          1  yes
## 13           1          0  yes
## 14           0          1   no

normalise all numeric attributes

set.seed(123)
preprocessBinWeather <- preProcess(binWeather1, method = c("range"))
preprocessBinWeatherNorm <- predict(preprocessBinWeather, binWeather1)
# view normalised attributes
head(preprocessBinWeatherNorm, 14)
##    outlook.sunny outlook.overcast outlook.rainy temperature  humidity
## 1              1                0             0  1.00000000 0.6451613
## 2              1                0             0  0.76190476 0.8064516
## 3              0                1             0  0.90476190 0.6774194
## 4              0                0             1  0.28571429 1.0000000
## 5              0                0             1  0.19047619 0.4838710
## 6              0                0             1  0.04761905 0.1612903
## 7              0                1             0  0.00000000 0.0000000
## 8              1                0             0  0.38095238 0.9677419
## 9              1                0             0  0.23809524 0.1612903
## 10             0                0             1  0.52380952 0.4838710
## 11             1                0             0  0.52380952 0.1612903
## 12             0                1             0  0.38095238 0.8064516
## 13             0                1             0  0.80952381 0.3225806
## 14             0                0             1  0.33333333 0.8387097
##    windy.false windy.true play
## 1            1          0   no
## 2            0          1   no
## 3            1          0  yes
## 4            1          0  yes
## 5            1          0  yes
## 6            0          1   no
## 7            0          1  yes
## 8            1          0   no
## 9            1          0  yes
## 10           1          0  yes
## 11           0          1  yes
## 12           0          1  yes
## 13           1          0  yes
## 14           0          1   no

applying knn to the normalised attributes

set.seed(123)
NormWeatherPlayknn <- train(play ~., data = preprocessBinWeatherNorm, method = "knn", trControl = ctrl1)
print(NormWeatherPlayknn)
## k-Nearest Neighbors 
## 
## 14 samples
##  7 predictor
##  2 classes: 'yes', 'no' 
## 
## No pre-processing
## Resampling: Leave-One-Out Cross-Validation 
## Summary of sample sizes: 13, 13, 13, 13, 13, 13, ... 
## Resampling results across tuning parameters:
## 
##   k  Accuracy   Kappa     
##   5  0.7142857   0.2432432
##   7  0.6428571   0.1025641
##   9  0.5714286  -0.1351351
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 5.
plot(NormWeatherPlayknn)

## knn on WeatherPlay without binarisation of attributes

set.seed(123)
WeatherPlayknn <- train(play ~., 
                        data = WeatherPlay,
                        method = "knn",
                        trControl = ctrl1)
print(WeatherPlayknn)
## k-Nearest Neighbors 
## 
## 14 samples
##  4 predictor
##  2 classes: 'yes', 'no' 
## 
## No pre-processing
## Resampling: Leave-One-Out Cross-Validation 
## Summary of sample sizes: 13, 13, 13, 13, 13, 13, ... 
## Resampling results across tuning parameters:
## 
##   k  Accuracy   Kappa      
##   5  0.5714286  -0.02439024
##   7  0.5714286  -0.13513514
##   9  0.6428571   0.00000000
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 9.
plot(WeatherPlayknn)

## note the difference between the binarised knn of WeatherPlay and the non binarised knn of WeatherPlay is the best k is 9 for non binarised and best k is 5 for binarised

for the standardised version of binarised Weatherplay

set.seed(123)
StandardpreProcessWeatherPlay <- preProcess(binWeather1, method = c("center", "scale"))
PreProcessWPStandardVals <- predict(StandardpreProcessWeatherPlay, binWeather1)
# view the standardised attributes
head(PreProcessWPStandardVals, 14)
##    outlook.sunny outlook.overcast outlook.rainy temperature   humidity
## 1       1.292837       -0.6094494     -0.718243   1.7390672  0.3264046
## 2       1.292837       -0.6094494     -0.718243   0.9782253  0.8125392
## 3      -0.718243        1.5236235     -0.718243   1.4347305  0.4236315
## 4      -0.718243       -0.6094494      1.292837  -0.5434585  1.3959007
## 5      -0.718243       -0.6094494      1.292837  -0.8477953 -0.1597299
## 6      -0.718243       -0.6094494      1.292837  -1.3043004 -1.1319990
## 7      -0.718243        1.5236235     -0.718243  -1.4564688 -1.6181336
## 8       1.292837       -0.6094494     -0.718243  -0.2391217  1.2986737
## 9       1.292837       -0.6094494     -0.718243  -0.6956269 -1.1319990
## 10     -0.718243       -0.6094494      1.292837   0.2173834 -0.1597299
## 11      1.292837       -0.6094494     -0.718243   0.2173834 -1.1319990
## 12     -0.718243        1.5236235     -0.718243  -0.2391217  0.8125392
## 13     -0.718243        1.5236235     -0.718243   1.1303937 -0.6458645
## 14     -0.718243       -0.6094494      1.292837  -0.3912901  0.9097661
##    windy.false windy.true play
## 1     0.834523  -0.834523   no
## 2    -1.112697   1.112697   no
## 3     0.834523  -0.834523  yes
## 4     0.834523  -0.834523  yes
## 5     0.834523  -0.834523  yes
## 6    -1.112697   1.112697   no
## 7    -1.112697   1.112697  yes
## 8     0.834523  -0.834523   no
## 9     0.834523  -0.834523  yes
## 10    0.834523  -0.834523  yes
## 11   -1.112697   1.112697  yes
## 12   -1.112697   1.112697  yes
## 13    0.834523  -0.834523  yes
## 14   -1.112697   1.112697   no

knn on standardised dataset of WeatherPlay

set.seed(123)
StandardWeatherPlayknn <- train(play ~.,
                                data = PreProcessWPStandardVals,
                                method = "knn",
                                trControl = ctrl1)
print(StandardWeatherPlayknn)
## k-Nearest Neighbors 
## 
## 14 samples
##  7 predictor
##  2 classes: 'yes', 'no' 
## 
## No pre-processing
## Resampling: Leave-One-Out Cross-Validation 
## Summary of sample sizes: 13, 13, 13, 13, 13, 13, ... 
## Resampling results across tuning parameters:
## 
##   k  Accuracy   Kappa     
##   5  0.6428571   0.1025641
##   7  0.5714286  -0.1351351
##   9  0.5714286  -0.1351351
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 5.
plot(StandardWeatherPlayknn)