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.

Goal

The goal of this project is to predict the manner in which they did the exercise. This is the “classe” variable in the training set. Any of the other variables can be used to predict with.

Loading Libraries

library(caret)
## Warning: package 'caret' was built under R version 3.1.2
## Loading required package: lattice
## Loading required package: ggplot2
library(rpart)
library(rpart.plot)
## Warning: package 'rpart.plot' was built under R version 3.1.2
library(RColorBrewer)
library(rattle)
## Warning: package 'rattle' was built under R version 3.1.2
## Rattle: A free graphical interface for data mining with R.
## Version 3.3.0 Copyright (c) 2006-2014 Togaware Pty Ltd.
## Type 'rattle()' to shake, rattle, and roll your data.
library(randomForest)
## Warning: package 'randomForest' was built under R version 3.1.2
## randomForest 4.6-10
## Type rfNews() to see new features/changes/bug fixes.

Getting Data

training<-read.csv("./trainingdata.csv")
testing<-read.csv("./testingdata.csv")
set.seed(111)

Partitioning Data

inTrain<-createDataPartition(training$classe, p=0.6, list=FALSE)
myTraining<-training[inTrain,]
myTesting<-training[-inTrain,]

Cleaning Data

Before cleaning the data, the dimensions of myTraining are:

dim(myTraining)
## [1] 11776   160

Step 1: Removing 1st 7 columns because they are specific to the participants and thus won’t be god candidates for the Prediction Model.

temp<-1:7
myTraining<-myTraining[,-temp]
dim(myTraining)
## [1] 11776   153

Step 2: Removing Variables with Near Zero Variance

nzvData<-nearZeroVar(myTraining, saveMetrics=TRUE)
myTraining<-myTraining[,!nzvData$nzv]
dim(myTraining)
## [1] 11776    99

Step 3: Removing variables which have more than 60% NA values

columnNumbersToRemove<-vector()
vectorIndex<-0
for(i in 1:ncol(myTraining)){
  if((sum(is.na(myTraining[,i]))/nrow(myTraining))>=0.60){
    vectorIndex<-vectorIndex+1
    columnNumbersToRemove[vectorIndex]<-i
  }
}
myTraining<-myTraining[,-columnNumbersToRemove]
dim(myTraining)
## [1] 11776    53

Step 4: Doing the same steps for datasets “myTesting” and “testing”

variables1<-colnames(myTraining)
variables2<-colnames(myTraining[,-53])
myTesting<-myTesting[variables1]
testing<-testing[variables2]
dim(myTesting)
## [1] 7846   53
dim(testing)
## [1] 20 52

Applying Machine Learning Algorithms for Building Prediction Models:

1) Decision Tree:

Building the model:

modFit1 <- rpart(classe ~ ., data=myTraining, method="class")

Plot:

fancyRpartPlot(modFit1)
## Warning: labs do not fit even at cex 0.15, there may be some overplotting

plot of chunk unnamed-chunk-10

Predicting:

predictions1 <- predict(modFit1, myTesting, type = "class")

Results:

confusionMatrix(predictions1, myTesting$classe)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction    A    B    C    D    E
##          A 2055  236   44   85   64
##          B   79  997  153  117  170
##          C   41  125 1085  192  149
##          D   26  120   86  812   88
##          E   31   40    0   80  971
## 
## Overall Statistics
##                                         
##                Accuracy : 0.755         
##                  95% CI : (0.745, 0.764)
##     No Information Rate : 0.284         
##     P-Value [Acc > NIR] : <2e-16        
##                                         
##                   Kappa : 0.688         
##  Mcnemar's Test P-Value : <2e-16        
## 
## Statistics by Class:
## 
##                      Class: A Class: B Class: C Class: D Class: E
## Sensitivity             0.921    0.657    0.793    0.631    0.673
## Specificity             0.924    0.918    0.922    0.951    0.976
## Pos Pred Value          0.827    0.658    0.682    0.717    0.865
## Neg Pred Value          0.967    0.918    0.955    0.929    0.930
## Prevalence              0.284    0.193    0.174    0.164    0.184
## Detection Rate          0.262    0.127    0.138    0.103    0.124
## Detection Prevalence    0.317    0.193    0.203    0.144    0.143
## Balanced Accuracy       0.922    0.787    0.857    0.791    0.825

We can see the Accuracy= 75.5%. Let’s try using Random Forests to see if we can get a better accuracy.

2) Random Forests:

Building the model:

modFit2 <- randomForest(classe ~. , data=myTraining)

Predicting:

predictions2 <- predict(modFit2, myTesting, type = "class")

Results:

confusionMatrix(predictions2, myTesting$classe)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction    A    B    C    D    E
##          A 2230   20    0    0    0
##          B    2 1493    6    0    0
##          C    0    5 1362   18    2
##          D    0    0    0 1267    1
##          E    0    0    0    1 1439
## 
## Overall Statistics
##                                         
##                Accuracy : 0.993         
##                  95% CI : (0.991, 0.995)
##     No Information Rate : 0.284         
##     P-Value [Acc > NIR] : <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.999    0.984    0.996    0.985    0.998
## Specificity             0.996    0.999    0.996    1.000    1.000
## Pos Pred Value          0.991    0.995    0.982    0.999    0.999
## Neg Pred Value          1.000    0.996    0.999    0.997    1.000
## Prevalence              0.284    0.193    0.174    0.164    0.184
## Detection Rate          0.284    0.190    0.174    0.161    0.183
## Detection Prevalence    0.287    0.191    0.177    0.162    0.184
## Balanced Accuracy       0.998    0.991    0.996    0.993    0.999

We now get an accuracy of 99.3%.

Result:

Random Forests gives us an Accuracy of 99.3% which is more than the accuracy we got from Decision Trees. The expected out-of-sample error is 100-99.3 = 0.7%. Therefore, Random Forests are chosen to predict classes for the test samples.

Predicting for the Test Samples

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