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).
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
require(caret)
## Loading required package: caret
## Loading required package: lattice
## Loading required package: ggplot2
require(RGtk2)
## Loading required package: RGtk2
## Warning in library(package, lib.loc = lib.loc, character.only = TRUE,
## logical.return = TRUE, : there is no package called 'RGtk2'
require(rattle)
## Loading required package: rattle
require(cacher)
## Loading required package: cacher
## Warning in library(package, lib.loc = lib.loc, character.only = TRUE,
## logical.return = TRUE, : there is no package called 'cacher'
require(rpart.plot)
## Loading required package: rpart.plot
## Loading required package: rpart
read in the data. Anything with NA or DIV/0 should be considered a null value.
training=read.csv('pml-training.csv',na.strings=c("NA", "", "#DIV/0!"))
testing=read.csv('pml-testing.csv',na.strings=c("NA", "", "#DIV/0!"))
clean the data: Data appears to be a time series with the presence of windows and timestamps, but it does not seem that the data within a time period is dependent on other observations in the same time period. Hence we will remove the time period data from the analysis.; Remove first 7 columns:
training<-subset(training[,8:160])
testing<-subset(testing[,8:160])
Some columns are only populated once per window. Remove any columns with more than 95% NA values
training<-training[,colSums(is.na(training))<(0.95*nrow(training))]
testing<-testing[,colSums(is.na(testing))<(0.95*nrow(testing))]
Create feature plots of totals from each category (belt, arm, dumbbell, forearm) vs classe
featurePlot(x=training[,c("total_accel_belt","total_accel_arm","total_accel_dumbbell","total_accel_forearm")],y=training$classe,plot="density",
scales=list(x=list(relation="free"),
y=list(relation="free")),auto.key=list(columns=5))
#Prediction Model Break the training set into training and validation
inTrain <- createDataPartition(y=training$classe, p=0.7, list=FALSE)
training <- training[inTrain,] # training set
validation <- training[-inTrain,] #validation set
Create argument for trainControl function that specifies 10-fold cross validation repeated 10 times
tr_Control <- trainControl(## 10-fold CV
method = "repeatedcv",
number = 10,
## repeated ten times
repeats = 10)
Create a classification tree model using tr_control argument
modFit<-train(classe~.,method="rpart",data=training, trControl=tr_Control)
plot(modFit$finalModel,uniform=TRUE,main="Classification Tree")
text(modFit$finalModel,use.n=TRUE,all=TRUE,cex=.8)
modFit
## CART
##
## 13737 samples
## 52 predictor
## 5 classes: 'A', 'B', 'C', 'D', 'E'
##
## No pre-processing
## Resampling: Cross-Validated (10 fold, repeated 10 times)
## Summary of sample sizes: 12363, 12362, 12363, 12362, 12365, 12364, ...
## Resampling results across tuning parameters:
##
## cp Accuracy Kappa
## 0.03499135 0.5164940 0.37127783
## 0.06072627 0.4262535 0.22588438
## 0.11504425 0.3226953 0.05848621
##
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was cp = 0.03499135.
We can see accuracy is low. Try again with Random Forest model, this time without repeating cross-validation which is computation-intensive.
tr_ControlRF <- trainControl(## 10-fold CV
method = "cv",
number = 10)
modFitRF<-train(classe~.,method="rf",data=training)
## Loading required package: randomForest
## randomForest 4.6-12
## Type rfNews() to see new features/changes/bug fixes.
##
## Attaching package: 'randomForest'
## The following object is masked from 'package:ggplot2':
##
## margin
modFitRF
## Random Forest
##
## 13737 samples
## 52 predictor
## 5 classes: 'A', 'B', 'C', 'D', 'E'
##
## No pre-processing
## Resampling: Bootstrapped (25 reps)
## Summary of sample sizes: 13737, 13737, 13737, 13737, 13737, 13737, ...
## Resampling results across tuning parameters:
##
## mtry Accuracy Kappa
## 2 0.9893560 0.9865279
## 27 0.9886022 0.9855741
## 52 0.9808585 0.9757746
##
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.
Test the model on validation set:
pred<-predict(modFitRF,validation)
## Loading required package: randomForest
## randomForest 4.6-12
## Type rfNews() to see new features/changes/bug fixes.
##
## Attaching package: 'randomForest'
## The following object is masked from 'package:ggplot2':
##
## margin
Plot the prediction versus actual
qplot(validation$classe,pred,data=validation)
We can see the prediction is approximately a 45 degree line, so our prediction is accurate. Check the model statistics.
modFitRF$finalModel
##
## Call:
## randomForest(x = x, y = y, mtry = param$mtry)
## Type of random forest: classification
## Number of trees: 500
## No. of variables tried at each split: 2
##
## OOB estimate of error rate: 0.7%
## Confusion matrix:
## A B C D E class.error
## A 3903 3 0 0 0 0.0007680492
## B 15 2635 8 0 0 0.0086531226
## C 0 21 2373 2 0 0.0095993322
## D 0 0 40 2211 1 0.0182060391
## E 0 0 1 5 2519 0.0023762376
We can see the accuracy rate is very good. We expect the out of sample error rate to be (1 - Accuracy).
We can also check confusion matrix, which shows high accuracy
confusionMatrix(pred,validation$classe)
## Confusion Matrix and Statistics
##
## Reference
## Prediction A B C D E
## A 1171 2 0 0 0
## B 0 790 1 0 0
## C 0 0 729 5 1
## D 0 0 0 679 1
## E 0 0 0 1 713
##
## Overall Statistics
##
## Accuracy : 0.9973
## 95% CI : (0.9952, 0.9987)
## No Information Rate : 0.2861
## P-Value [Acc > NIR] : < 2.2e-16
##
## Kappa : 0.9966
## Mcnemar's Test P-Value : NA
##
## Statistics by Class:
##
## Class: A Class: B Class: C Class: D Class: E
## Sensitivity 1.0000 0.9975 0.9986 0.9912 0.9972
## Specificity 0.9993 0.9997 0.9982 0.9997 0.9997
## Pos Pred Value 0.9983 0.9987 0.9918 0.9985 0.9986
## Neg Pred Value 1.0000 0.9994 0.9997 0.9982 0.9994
## Prevalence 0.2861 0.1935 0.1784 0.1674 0.1747
## Detection Rate 0.2861 0.1930 0.1781 0.1659 0.1742
## Detection Prevalence 0.2866 0.1933 0.1796 0.1661 0.1744
## Balanced Accuracy 0.9997 0.9986 0.9984 0.9955 0.9985
accuracy:
1-confusionMatrix(pred,validation$class)$overall[[1]]
## [1] 0.002687515