library(lattice)
library(ggplot2)
library(caret)
library(rpart)
library(rpart.plot)
library(RColorBrewer)
library(rattle)
library(randomForest)
library(knitr)

Background

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).

Data

The training data for this project are available here: https://d396qusza40orc.cloudfront.net/predmachlearn/pml-training.csv

The test data are available here: https://d396qusza40orc.cloudfront.net/predmachlearn/pml-testing.csv

The data for this project come from this source: http://groupware.les.inf.puc-rio.br/har . If you use the document you create for this class for any purpose please cite them as they have been very generous in allowing their data to be used for this kind of assignment.

Getting and Cleaning the data

Getting the data

if (!dir.exists("Final_Project")) { 
dir.create("./Final_Project")}
setwd("./Final_Project")
fileUrl_training <- "https://d396qusza40orc.cloudfront.net/predmachlearn/pml-training.csv"
download.file(fileUrl_training, destfile = "./pml-training.csv")
fileUrl_testing <- "https://d396qusza40orc.cloudfront.net/predmachlearn/pml-testing.csv"
download.file(fileUrl_testing, destfile = "./pml-testing.csv")
training <- read.csv("pml-training.csv", na.strings=c("NA","#DIV/0!",""))
testing <- read.csv("pml-testing.csv", na.strings=c("NA","#DIV/0!",""))

Cleaning the data

nzv <- nearZeroVar(training, saveMetrics=TRUE)
training <- training[,nzv$nzv==FALSE]
training <- training[c(-1)]
trainingtemp <- training
for(i in 1:length(training)) {
    if( sum( is.na( training[, i] ) ) /nrow(training) >= .7) {
        for(j in 1:length(trainingtemp)) {
            if( length( grep(names(training[i]), names(trainingtemp)[j]) ) == 1)  {
                trainingtemp <- trainingtemp[ , -j]
            }   
        } 
    }
}
training <- trainingtemp
rm(trainingtemp)
inTrain <- createDataPartition(training$classe, p=0.6, list=FALSE)
myTraining <- training[inTrain, ]
myTesting <- training[-inTrain, ]
clean1 <- colnames(myTraining)
clean2 <- colnames(myTraining[, -58])
myTesting <- myTesting[clean1]
testing <- testing[clean2]
for (i in 1:length(testing) ) {
    for(j in 1:length(myTraining)) {
        if( length( grep(names(myTraining[i]), names(testing)[j]) ) == 1)  {
            class(testing[j]) <- class(myTraining[i])
        }      
    }      
}
testing <- rbind(myTraining[2, -58] , testing)
testing <- testing[-1,]

Prediction

Decision Trees

set.seed(123456)
modFitA1 <- rpart(classe ~ ., data=myTraining, method="class")
fancyRpartPlot(modFitA1)

predictionsA1 <- predict(modFitA1, myTesting, type = "class")
cmtree <- confusionMatrix(predictionsA1, myTesting$classe)
cmtree
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction    A    B    C    D    E
##          A 2161   60    5    2    0
##          B   51 1272   79   56    0
##          C   20  176 1237  132   48
##          D    0   10   27  887   81
##          E    0    0   20  209 1313
## 
## Overall Statistics
##                                           
##                Accuracy : 0.8756          
##                  95% CI : (0.8681, 0.8828)
##     No Information Rate : 0.2845          
##     P-Value [Acc > NIR] : < 2.2e-16       
##                                           
##                   Kappa : 0.8426          
##  Mcnemar's Test P-Value : NA              
## 
## Statistics by Class:
## 
##                      Class: A Class: B Class: C Class: D Class: E
## Sensitivity            0.9682   0.8379   0.9042   0.6897   0.9105
## Specificity            0.9881   0.9706   0.9420   0.9820   0.9642
## Pos Pred Value         0.9699   0.8724   0.7669   0.8826   0.8515
## Neg Pred Value         0.9874   0.9615   0.9790   0.9417   0.9795
## Prevalence             0.2845   0.1935   0.1744   0.1639   0.1838
## Detection Rate         0.2754   0.1621   0.1577   0.1131   0.1673
## Detection Prevalence   0.2840   0.1858   0.2056   0.1281   0.1965
## Balanced Accuracy      0.9781   0.9043   0.9231   0.8359   0.9374
plot(cmtree$table, col = cmtree$byClass, main = paste("Decision Tree Confusion Matrix: Accuracy =", round(cmtree$overall['Accuracy'], 4)))

Random Forests

set.seed(123456)
modFitB1 <- randomForest(classe ~ ., data=myTraining)
predictionB1 <- predict(modFitB1, myTesting, type = "class")
cmrf <- confusionMatrix(predictionB1, myTesting$classe)
cmrf
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction    A    B    C    D    E
##          A 2231    1    0    0    0
##          B    1 1517    1    0    0
##          C    0    0 1365    0    0
##          D    0    0    2 1286    1
##          E    0    0    0    0 1441
## 
## Overall Statistics
##                                           
##                Accuracy : 0.9992          
##                  95% CI : (0.9983, 0.9997)
##     No Information Rate : 0.2845          
##     P-Value [Acc > NIR] : < 2.2e-16       
##                                           
##                   Kappa : 0.999           
##  Mcnemar's Test P-Value : NA              
## 
## Statistics by Class:
## 
##                      Class: A Class: B Class: C Class: D Class: E
## Sensitivity            0.9996   0.9993   0.9978   1.0000   0.9993
## Specificity            0.9998   0.9997   1.0000   0.9995   1.0000
## Pos Pred Value         0.9996   0.9987   1.0000   0.9977   1.0000
## Neg Pred Value         0.9998   0.9998   0.9995   1.0000   0.9998
## Prevalence             0.2845   0.1935   0.1744   0.1639   0.1838
## Detection Rate         0.2843   0.1933   0.1740   0.1639   0.1837
## Detection Prevalence   0.2845   0.1936   0.1740   0.1643   0.1837
## Balanced Accuracy      0.9997   0.9995   0.9989   0.9998   0.9997
plot(modFitB1)

plot(cmrf$table, col = cmtree$byClass, main = paste("Random Forest Confusion Matrix: Accuracy =", round(cmrf$overall['Accuracy'], 4)))

Generalized Boosted Regression

library(survival)
library(gbm)
library(splines)
library(parallel)
library(plyr)
set.seed(123456)
fitControl <- trainControl(method = "repeatedcv",
                           number = 5,
                           repeats = 1)

gbmFit1 <- train(classe ~ ., data=myTraining, method = "gbm",
                 trControl = fitControl,
                 verbose = FALSE)
gbmFinMod1 <- gbmFit1$finalModel
gbmPredTest <- predict(gbmFit1, newdata=myTesting)
gbmAccuracyTest <- confusionMatrix(gbmPredTest, myTesting$classe)
gbmAccuracyTest
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction    A    B    C    D    E
##          A 2230    2    0    0    0
##          B    2 1515    0    0    0
##          C    0    1 1358    4    0
##          D    0    0   10 1280    8
##          E    0    0    0    2 1434
## 
## Overall Statistics
##                                           
##                Accuracy : 0.9963          
##                  95% CI : (0.9947, 0.9975)
##     No Information Rate : 0.2845          
##     P-Value [Acc > NIR] : < 2.2e-16       
##                                           
##                   Kappa : 0.9953          
##  Mcnemar's Test P-Value : NA              
## 
## Statistics by Class:
## 
##                      Class: A Class: B Class: C Class: D Class: E
## Sensitivity            0.9991   0.9980   0.9927   0.9953   0.9945
## Specificity            0.9996   0.9997   0.9992   0.9973   0.9997
## Pos Pred Value         0.9991   0.9987   0.9963   0.9861   0.9986
## Neg Pred Value         0.9996   0.9995   0.9985   0.9991   0.9988
## Prevalence             0.2845   0.1935   0.1744   0.1639   0.1838
## Detection Rate         0.2842   0.1931   0.1731   0.1631   0.1828
## Detection Prevalence   0.2845   0.1933   0.1737   0.1654   0.1830
## Balanced Accuracy      0.9994   0.9989   0.9960   0.9963   0.9971
plot(gbmFit1, ylim=c(0.9, 1))

Course Project Prediction Results

Random Forest gives an Accuracy in the myTesting dataset of 99.89%, which was more accurate that what I got from the Decision Trees and GBM. The expected out-of-sample error is 100%-99.89% = 0.11%. Thus I choose Random Forest to be the final predictor.

predictionB2 <- predict(modFitB1, testing, type = "class")
predictionB2
##  2 31  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 
##  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

Write the results to a text file for submission

pml_write_files = function(x){
    n = length(x)
    for(i in 1:n){
        filename = paste0("problem_id_",i,".txt")
        write.table(x[i],file=filename,quote=FALSE,row.names=FALSE,col.names=FALSE)
    }
}
pml_write_files(predictionB2)