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: http://groupware.les.inf.puc-rio.br/har (see the section on the Weight Lifting Exercise Dataset).

(From Course Project description)


Dataset preparation

In order to model the predictor, I have chosen variables which does not describe dataset (0:6) and ones that are almost composed by NA’s:

set.seed(1378)

#Load dataset
dataset <- read.csv('pml-training.csv',na.strings=c("NA",""))
dim(dataset)
## [1] 19622   160
#Remove description variables
dataset <- dataset[,8:160]

#Select only variables that matters
variables <- apply(!is.na(dataset),2,sum) > nrow(dataset)*0.99
dataset<-dataset[,variables]

#dataset <- subset(dataset, select = grep("accel*|classe", names(dataset)))

#Updated feature dimension
dim(dataset)
## [1] 19622    53


Split dataset

Split dataset into 70% for training and 30% for testing. Then, missing values rows are excluded from dataset

library(caret)
## Loading required package: lattice
## Loading required package: ggplot2
partition <- createDataPartition(y=dataset$classe, p=0.7, list=FALSE)

train_dataset <- dataset[partition,]
test_dataset <- dataset[-partition,]


Modeling

Perform Random Forest analysis to fit model. 5-fold cross validation to speed up algorithm output:

#Parallelize computation
library(doMC)
registerDoMC(cores = 1)
#Random forest algorithm settings. 5-fold cross validation

cv <- trainControl(method = "cv", 5)
model <- train(classe ~., method = "rf", trControl = cv, data = train_dataset, prox = TRUE,  allowParallel = TRUE)

#Model summary output
print(model)
## Random Forest 
## 
## 13737 samples
##    52 predictors
##     5 classes: 'A', 'B', 'C', 'D', 'E' 
## 
## No pre-processing
## Resampling: Cross-Validated (5 fold) 
## Summary of sample sizes: 10991, 10989, 10990, 10989, 10989 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy   Kappa      Accuracy SD  Kappa SD   
##    2    0.9903912  0.9878440  0.002501709  0.003165642
##   27    0.9911195  0.9887670  0.003027817  0.003830365
##   52    0.9852228  0.9813092  0.002143590  0.002711338
## 
## Accuracy was used to select the optimal model using  the largest value.
## The final value used for the model was mtry = 27.
#Model output
print(model$finalModel)
## 
## Call:
##  randomForest(x = x, y = y, mtry = param$mtry, proximity = TRUE,      allowParallel = TRUE) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 27
## 
##         OOB estimate of  error rate: 0.74%
## Confusion matrix:
##      A    B    C    D    E class.error
## A 3902    4    0    0    0 0.001024066
## B   16 2633    8    1    0 0.009405568
## C    0   17 2370    9    0 0.010851419
## D    1    1   26 2222    2 0.013321492
## E    0    1    7    9 2508 0.006732673


Sample error is about 0.74%. Let’s run prediction over test dataset and see what happens to the estimated error.

Prediction

Prediction over test subset, using training set fitted model:

prediction <- predict(model, test_dataset)
## Loading required package: randomForest
## randomForest 4.6-10
## Type rfNews() to see new features/changes/bug fixes.
confusionMatrix(prediction, test_dataset$classe)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction    A    B    C    D    E
##          A 1671    9    0    0    0
##          B    1 1126    6    0    0
##          C    1    4 1017   11    1
##          D    0    0    3  950    2
##          E    1    0    0    3 1079
## 
## Overall Statistics
##                                           
##                Accuracy : 0.9929          
##                  95% CI : (0.9904, 0.9949)
##     No Information Rate : 0.2845          
##     P-Value [Acc > NIR] : < 2.2e-16       
##                                           
##                   Kappa : 0.991           
##  Mcnemar's Test P-Value : NA              
## 
## Statistics by Class:
## 
##                      Class: A Class: B Class: C Class: D Class: E
## Sensitivity            0.9982   0.9886   0.9912   0.9855   0.9972
## Specificity            0.9979   0.9985   0.9965   0.9990   0.9992
## Pos Pred Value         0.9946   0.9938   0.9836   0.9948   0.9963
## Neg Pred Value         0.9993   0.9973   0.9981   0.9972   0.9994
## Prevalence             0.2845   0.1935   0.1743   0.1638   0.1839
## Detection Rate         0.2839   0.1913   0.1728   0.1614   0.1833
## Detection Prevalence   0.2855   0.1925   0.1757   0.1623   0.1840
## Balanced Accuracy      0.9980   0.9936   0.9939   0.9922   0.9982

In the end, estimate error is about 0.01%, which indicates that model is very suitable to generalize dataset instances. Now let’s predict classes for provided testset:

submission_test <- read.csv('pml-testing.csv',na.strings=c("NA",""))
prediction <- predict(model, submission_test)
prediction
##  [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


Conclusions

Even with almost no tunning, just choosing reasonable variables from dataset, Random Forest algorithm with a 5-fold cross validation is able to perform a great classification task, and seems to generalize test set.