Summary

Using devices such as Jawbone Up, Nike FuelBand, and Fitbit it is now possible to collect a large amount of data about personal activity relatively inexpensively. These type of devices are part of the quantified self movement - a group of enthusiasts who take measurements about themselves regularly to improve their health, to find patterns in their behavior, or because they are tech geeks. One thing that people regularly do is quantify how much of a particular activity they do, but they rarely quantify how well they do it. In this project, your goal will be to use data from accelerometers on the belt, forearm, arm, and dumbell of 6 participants. They were asked to perform barbell lifts correctly and incorrectly in 5 different ways. More information is available from the website here (see the section on the Weight Lifting Exercise Dataset). The goal of this report is to predict the manner in which they did the exercise.

Exploring the Dataset

First of all, let’s read and take a look at the dataset.

#load libraries & data
library(caret)

data<- read.csv("pml-training.csv")
data_test <- read.csv("pml-testing.csv")

class(data$classe)
## [1] "factor"
dim(data)
## [1] 19622   160
summary(data[, 1:10])
##        X            user_name    raw_timestamp_part_1 raw_timestamp_part_2
##  Min.   :    1   adelmo  :3892   Min.   :1.322e+09    Min.   :   294      
##  1st Qu.: 4906   carlitos:3112   1st Qu.:1.323e+09    1st Qu.:252912      
##  Median : 9812   charles :3536   Median :1.323e+09    Median :496380      
##  Mean   : 9812   eurico  :3070   Mean   :1.323e+09    Mean   :500656      
##  3rd Qu.:14717   jeremy  :3402   3rd Qu.:1.323e+09    3rd Qu.:751891      
##  Max.   :19622   pedro   :2610   Max.   :1.323e+09    Max.   :998801      
##                                                                           
##           cvtd_timestamp  new_window    num_window      roll_belt     
##  28/11/2011 14:14: 1498   no :19216   Min.   :  1.0   Min.   :-28.90  
##  05/12/2011 11:24: 1497   yes:  406   1st Qu.:222.0   1st Qu.:  1.10  
##  30/11/2011 17:11: 1440               Median :424.0   Median :113.00  
##  05/12/2011 11:25: 1425               Mean   :430.6   Mean   : 64.41  
##  02/12/2011 14:57: 1380               3rd Qu.:644.0   3rd Qu.:123.00  
##  02/12/2011 13:34: 1375               Max.   :864.0   Max.   :162.00  
##  (Other)         :11007                                               
##    pitch_belt          yaw_belt      
##  Min.   :-55.8000   Min.   :-180.00  
##  1st Qu.:  1.7600   1st Qu.: -88.30  
##  Median :  5.2800   Median : -13.00  
##  Mean   :  0.3053   Mean   : -11.21  
##  3rd Qu.: 14.9000   3rd Qu.:  12.90  
##  Max.   : 60.3000   Max.   : 179.00  
## 
str(data[, 1:10])
## 'data.frame':    19622 obs. of  10 variables:
##  $ X                   : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ user_name           : Factor w/ 6 levels "adelmo","carlitos",..: 2 2 2 2 2 2 2 2 2 2 ...
##  $ raw_timestamp_part_1: int  1323084231 1323084231 1323084231 1323084232 1323084232 1323084232 1323084232 1323084232 1323084232 1323084232 ...
##  $ raw_timestamp_part_2: int  788290 808298 820366 120339 196328 304277 368296 440390 484323 484434 ...
##  $ cvtd_timestamp      : Factor w/ 20 levels "02/12/2011 13:32",..: 9 9 9 9 9 9 9 9 9 9 ...
##  $ new_window          : Factor w/ 2 levels "no","yes": 1 1 1 1 1 1 1 1 1 1 ...
##  $ num_window          : int  11 11 11 12 12 12 12 12 12 12 ...
##  $ roll_belt           : num  1.41 1.41 1.42 1.48 1.48 1.45 1.42 1.42 1.43 1.45 ...
##  $ pitch_belt          : num  8.07 8.07 8.07 8.05 8.07 8.06 8.09 8.13 8.16 8.17 ...
##  $ yaw_belt            : num  -94.4 -94.4 -94.4 -94.4 -94.4 -94.4 -94.4 -94.4 -94.4 -94.4 ...

Our dataset has 160 variables.

Remove Missing Values

We will find and remove all the variables that have more missing than non-missing values from the dataset.

missing1 <- which(apply(data, 2, function(x) sum(is.na(x))>length(x)/2))
missing2 <- which(apply(data, 2, function(x) sum(x=="")>length(x)/2))

data_clean <- subset(data, select = -c(missing1,missing2))

dim(data_clean)
## [1] 19622    60

So we managed to reduce the dimensions of the dataset from 160 to 60.

Remove Redundant Variables

The variables that had nothing to do with movement and the first variable X which is just an index were removed

data_ready  <- data_clean [,-c(1:6)]

Before we continue we will slice the train data into train and test datasets using createDataPartition function.

# Setting seed in order to make results reproducable
set.seed(42)
# create 80%/20% for training and validation datasets
validationIndex <- createDataPartition(data_clean$classe,p = 0.8,list = FALSE)
training <- data_ready [validationIndex,]
validation <- data_ready [-validationIndex,]

Now that our datasets are ready we will use the training data to train and tune our model and the validation data as an out of sample dataset in order to test the final model.

Model Fitting

We are going to use cross-validation to estimate the error on the validation set by specificying method = “cv” within the trainControl().

set.seed(42)
trainControl <- trainControl(method = "cv", number = 5,  allowParallel = TRUE)
fit.rf<- train(classe ~ ., data =training, method="rf", metric = "Accuracy", trcontrol = trainControl)
print(fit.rf)  
## Random Forest 
## 
## 15699 samples
##    53 predictor
##     5 classes: 'A', 'B', 'C', 'D', 'E' 
## 
## No pre-processing
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 15699, 15699, 15699, 15699, 15699, 15699, ... 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy   Kappa    
##    2    0.9933247  0.9915545
##   27    0.9967011  0.9958260
##   53    0.9933216  0.9915504
## 
## Accuracy was used to select the optimal model using  the largest value.
## The final value used for the model was mtry = 27.
print(fit.rf$finalModel)
## 
## Call:
##  randomForest(x = x, y = y, mtry = param$mtry, trcontrol = ..1) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 27
## 
##         OOB estimate of  error rate: 0.15%
## Confusion matrix:
##      A    B    C    D    E  class.error
## A 4462    1    0    0    1 0.0004480287
## B    5 3030    3    0    0 0.0026333114
## C    0    5 2733    0    0 0.0018261505
## D    0    0    8 2565    0 0.0031092110
## E    0    0    0    1 2885 0.0003465003

We can see that the OOB error rate is 0.15%.

Test the Final Model

Next we will use the validation data as an out of sample dataset in order to test our fitted model and find out if the accuracy that we estimated is close to our results.

## estimate skill on validation dataset
set.seed(42)
predictions <- predict(fit.rf, newdata=validation)
confusionMatrix(predictions, validation$classe)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction    A    B    C    D    E
##          A 1116    3    0    0    0
##          B    0  753    1    0    0
##          C    0    2  683    4    0
##          D    0    1    0  638    0
##          E    0    0    0    1  721
## 
## Overall Statistics
##                                           
##                Accuracy : 0.9969          
##                  95% CI : (0.9947, 0.9984)
##     No Information Rate : 0.2845          
##     P-Value [Acc > NIR] : < 2.2e-16       
##                                           
##                   Kappa : 0.9961          
##  Mcnemar's Test P-Value : NA              
## 
## Statistics by Class:
## 
##                      Class: A Class: B Class: C Class: D Class: E
## Sensitivity            1.0000   0.9921   0.9985   0.9922   1.0000
## Specificity            0.9989   0.9997   0.9981   0.9997   0.9997
## Pos Pred Value         0.9973   0.9987   0.9913   0.9984   0.9986
## Neg Pred Value         1.0000   0.9981   0.9997   0.9985   1.0000
## Prevalence             0.2845   0.1935   0.1744   0.1639   0.1838
## Detection Rate         0.2845   0.1919   0.1741   0.1626   0.1838
## Detection Prevalence   0.2852   0.1922   0.1756   0.1629   0.1840
## Balanced Accuracy      0.9995   0.9959   0.9983   0.9960   0.9998

The accuracy for the validation set is 99.6% with a 95% confidence interval.

Predicting the 20 cases

predict(fit.rf, newdata = data_test)
##  [1] B A B A A E D B A A B C B A E E A B B B
## Levels: A B C D E