The following exercise is part of the course of Data Sciences in Coursera and it is intended to be used for the application of methods and techniques of Machine Learning. The problem consists on predicting the way a workout (barbell lifts) is being realized by gathering information from sensors attached to each participant while performing the exercises. A variable named classe is the level of quality of the exercise and is the output to be predicted. The information has been download from http://groupware.les.inf.puc-rio.br/har in the section Weight Lifting Exercise Dataset.
library(caret)
## Loading required package: ggplot2
## Loading required package: lattice
library(readr)
library(ggplot2)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(Matrix)
To read the data we will use the read_csv function within readr library since the data is in a csv file, both training and testing dataset will e store as data frames, the training set is going to be named as raw data because we will have to manipulate it to get it into a tidy form.
The database contains columns with no relevant information about the output to predict. These are the very first 7 columns, which contain the user name, window number, time, and other inputs not related to the quality of the workout. These columns will be eliminated for the analysis. Also, let’s explore if there are NAs in the columns:
predictors <- training_raw[,c(8:ncol(training_raw))]
length(which(colSums(is.na(predictors)) > 0))
## [1] 100
Remaining columns contain NAs, we need to evaluate which variables have enough information to contribute as predictors. The following code will identify columns with less than 20% of values in each observation, those variables won’t be included on the analysis.
drop_list <- which(colSums(!is.na(predictors)) < 0.2*nrow(predictors))
predictors <- predictors[,-drop_list]
sum(colSums(is.na(predictors)))
sum(!lapply(predictors[,-53],class) == "numeric")
Now the database is tidy because there is no NA, no need to impute values and the data is 19622 observations with 52 predictors and 1 output variable and ready for analysis. All 52 predictors are numerical variables, one more detail is to change the output variable classe to a factor, so to use caret functions for fitting a model.
predictors$classe <- as.factor(predictors$classe)
dim(predictors)
## [1] 19622 53
str(predictors$classe)
## Factor w/ 5 levels "A","B","C","D",..: 1 1 1 1 1 1 1 1 1 1 ...
Now the output variable is facgorial with 5 levels which classify the quality of the workout. Let’s look at the predictors to find correlations that allows to simplify the database, first determine the variables with near zero variances:
nsv <- nearZeroVar(predictors,saveMetrics = TRUE)
which(nsv$zeroVar & nsv$zeroVar)
## integer(0)
There is no Near Zero Variances variables, next step is to build a correlation matrix among the predictors and identify those which correlation is higher than 0.8 to be considered co linear. The following code does that and display a table of variable’s correlation:
M <- abs(cor(predictors[,-53]))
diag(M) <- 0
which(M > 0.8,arr.ind=TRUE)
## row col
## yaw_belt 3 1
## total_accel_belt 4 1
## accel_belt_y 9 1
## accel_belt_z 10 1
## accel_belt_x 8 2
## magnet_belt_x 11 2
## roll_belt 1 3
## roll_belt 1 4
## accel_belt_y 9 4
## accel_belt_z 10 4
## pitch_belt 2 8
## magnet_belt_x 11 8
## roll_belt 1 9
## total_accel_belt 4 9
## accel_belt_z 10 9
## roll_belt 1 10
## total_accel_belt 4 10
## accel_belt_y 9 10
## pitch_belt 2 11
## accel_belt_x 8 11
## gyros_arm_y 19 18
## gyros_arm_x 18 19
## magnet_arm_x 24 21
## accel_arm_x 21 24
## magnet_arm_z 26 25
## magnet_arm_y 25 26
## accel_dumbbell_x 34 28
## accel_dumbbell_z 36 29
## gyros_dumbbell_z 33 31
## gyros_forearm_z 46 31
## gyros_dumbbell_x 31 33
## gyros_forearm_z 46 33
## pitch_dumbbell 28 34
## yaw_dumbbell 29 36
## gyros_forearm_z 46 45
## gyros_dumbbell_x 31 46
## gyros_dumbbell_z 33 46
## gyros_forearm_y 45 46
It’s noticed there are some variables correlated, one way to handle them and simplify the fitting of the model is to use PCA pre-processing to reduce the number of variables.
The strategy to find a predicting model is to try 3 different methods, having in mind that the output variables is a multi-factor with 5 levels which means our method should be as the classification type. For this exercise the options for method will be:
In order to select the best option for a method, the predictor dataset will be split into Training and Validation, the split will be done by picking a defined percentage of random data per level of the classe variable, this can be done by using the createDatapartition function and set classe as input:
set.seed(123)
inTrain <- createDataPartition(predictors$classe, p=0.7, list=FALSE)
training <- predictors[inTrain,]
validation <- predictors[-inTrain,]
As mentioned before, since there are some predictors that probed to be colinear a PCA pre-processing method is going to be use to simplify the analysis. The function train have this option.
model_rf <- train(classe ~ ., data = training, preProcess="pca",
method = 'rf', tuneLength = 1)
Now we will get the confusion matrix to revew the results of the model in the validation dataset:
confusionMatrix(validation$classe,predict(model_rf,validation))
## Confusion Matrix and Statistics
##
## Reference
## Prediction A B C D E
## A 1662 1 8 2 1
## B 17 1103 18 0 1
## C 4 15 1001 4 2
## D 0 0 42 918 4
## E 3 5 12 2 1060
##
## Overall Statistics
##
## Accuracy : 0.976
## 95% CI : (0.9718, 0.9798)
## No Information Rate : 0.2865
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.9697
##
## Mcnemar's Test P-Value : NA
##
## Statistics by Class:
##
## Class: A Class: B Class: C Class: D Class: E
## Sensitivity 0.9858 0.9813 0.9260 0.9914 0.9925
## Specificity 0.9971 0.9924 0.9948 0.9907 0.9954
## Pos Pred Value 0.9928 0.9684 0.9756 0.9523 0.9797
## Neg Pred Value 0.9943 0.9956 0.9835 0.9984 0.9983
## Prevalence 0.2865 0.1910 0.1837 0.1573 0.1815
## Detection Rate 0.2824 0.1874 0.1701 0.1560 0.1801
## Detection Prevalence 0.2845 0.1935 0.1743 0.1638 0.1839
## Balanced Accuracy 0.9915 0.9869 0.9604 0.9910 0.9940
The model is quite accurate in 97.6% , class C is where most of the misses occur and a p-value of 2.2e-16.
model_glm <- train(classe ~ ., data = training,
preProcess=c("pca","center","scale"),
method = 'glmnet',family="multinomial",
type.multinomial="grouped")
Let’s review the confusion matrix:
confusionMatrix(validation$classe,predict(model_glm,validation))
## Confusion Matrix and Statistics
##
## Reference
## Prediction A B C D E
## A 1106 139 170 216 43
## B 268 494 174 89 114
## C 304 112 481 99 30
## D 94 127 104 534 105
## E 108 192 129 137 516
##
## Overall Statistics
##
## Accuracy : 0.532
## 95% CI : (0.5192, 0.5448)
## No Information Rate : 0.3195
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.4059
##
## Mcnemar's Test P-Value : < 2.2e-16
##
## Statistics by Class:
##
## Class: A Class: B Class: C Class: D Class: E
## Sensitivity 0.5883 0.46429 0.45463 0.49674 0.63861
## Specificity 0.8582 0.86621 0.88709 0.91060 0.88852
## Pos Pred Value 0.6607 0.43371 0.46881 0.55394 0.47689
## Neg Pred Value 0.8162 0.87990 0.88125 0.89006 0.93920
## Prevalence 0.3195 0.18080 0.17978 0.18267 0.13730
## Detection Rate 0.1879 0.08394 0.08173 0.09074 0.08768
## Detection Prevalence 0.2845 0.19354 0.17434 0.16381 0.18386
## Balanced Accuracy 0.7232 0.66525 0.67086 0.70367 0.76357
GLM fits a model with a 53.2% accuracy, classification error is distributed in all classes.
model_bag <- train(classe ~ ., data = training, preProcess="pca",
method = 'treebag', mfinal =25,
tuneLength = 1)
And the confusion matrix will show:
confusionMatrix(validation$classe,predict(model_bag,validation))
## Confusion Matrix and Statistics
##
## Reference
## Prediction A B C D E
## A 1642 7 11 9 5
## B 27 1066 31 6 9
## C 4 15 995 8 4
## D 1 2 37 917 7
## E 8 11 13 6 1044
##
## Overall Statistics
##
## Accuracy : 0.9624
## 95% CI : (0.9573, 0.9672)
## No Information Rate : 0.2858
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.9525
##
## Mcnemar's Test P-Value : 6.223e-08
##
## Statistics by Class:
##
## Class: A Class: B Class: C Class: D Class: E
## Sensitivity 0.9762 0.9682 0.9154 0.9693 0.9766
## Specificity 0.9924 0.9847 0.9935 0.9905 0.9921
## Pos Pred Value 0.9809 0.9359 0.9698 0.9512 0.9649
## Neg Pred Value 0.9905 0.9926 0.9811 0.9941 0.9948
## Prevalence 0.2858 0.1871 0.1847 0.1607 0.1816
## Detection Rate 0.2790 0.1811 0.1691 0.1558 0.1774
## Detection Prevalence 0.2845 0.1935 0.1743 0.1638 0.1839
## Balanced Accuracy 0.9843 0.9765 0.9545 0.9799 0.9844
Bagging model achieves a 96.2 % accuracy.
Random Forest model seems to have a better results on predicting the validation dataset than the other 2 models (glm,bag), the out of sample error is expected to be a 0.034% vs 0.038% for the bagging model, hence, we will use random forest to make the prediction on the test dataset.
Using the random forest model, let’s predict the classe on each of the observations in the testing dataset, then add the results to the testing data frame:
Below is the results of the prediction:
## # A tibble: 20 × 2
## problem_id classe
## <dbl> <fct>
## 1 1 B
## 2 2 A
## 3 3 A
## 4 4 A
## 5 5 A
## 6 6 E
## 7 7 D
## 8 8 B
## 9 9 A
## 10 10 A
## 11 11 B
## 12 12 C
## 13 13 B
## 14 14 A
## 15 15 E
## 16 16 E
## 17 17 A
## 18 18 B
## 19 19 B
## 20 20 B
Based on a 0.034% out of sample error, it is expected to have as much as 1 miss value on the testing dataset.
In this paper we tried 3 different methods to predict a classification multinomial problem, after cleaning the database and determining the co-linearity among variables, and decide to apply PCA for pre-processing variables, the random forest method probed to be the most accurate (97.3%). Bagging method was the second best accurate with a 95.9%, while Generalized Linear Model was the least accurate by more than 43 percentage points. These results suggest that the data is quite non-linear and that Random Forest and Bagging methods are better for a classification problem.