Summary

Below, you cand find the background as described in the Coursera project :

“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)”

Getting and cleaning data

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.

Setting up workspace

setwd("D:/RWSPACE/pml-proj")
library(caret); library(rattle); library(rpart); library(rpart.plot)
## Loading required package: lattice
## Loading required package: ggplot2
## Warning: replacing previous import 'lme4::sigma' by 'stats::sigma' when
## loading 'pbkrtest'
## Rattle : une interface graphique gratuite pour l'exploration de données avec R.
## Version 4.1.0 Copyright (c) 2006-2015 Togaware Pty Ltd.
## Entrez 'rattle()' pour secouer, faire vibrer, et faire défiler vos données.
library(randomForest); library(repmis)
## 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
## Warning: package 'repmis' was built under R version 3.3.2

Download and import data

url_training <- "https://d396qusza40orc.cloudfront.net/predmachlearn/pml-training.csv"
dest_training <- "pml-training.csv"
#download.file(url=url_training, destfile=dest_training, method="curl")
url_testing <- "https://d396qusza40orc.cloudfront.net/predmachlearn/pml-testing.csv"
dest_testing <- "pml-testing.csv"
#download.file(url=url_testing, destfile=dest_testing, method="curl")

Loading data to our workspace

training <- read.csv("pml-training.csv", na.strings = c("NA", ""))
testing <- read.csv("pml-testing.csv", na.strings = c("NA", ""))
dim(training);dim(testing)
## [1] 19622   160
## [1]  20 160

Cleaning the data

1-Removing columns unuseful for prediction 2-Removing predictors with more than 70% of “NA” observations

Removing columns unuseful for prediction

#Create a copy of our original data sets
traindata <- training
testdata <- testing
#Remove the seven first variables as they're irrlevant for prediction
traindata <- traindata[,8:dim(traindata)[2]]
testdata <- testdata[,8:dim(testdata)[2]]

Removing predictors with more than 70% of “NA” observations

#create a vector with the number of NAs in each predictor
sumNA <- c()
for(i in 1:length(traindata)){
   sumNA[i] <- sum(is.na(traindata[,i]))   
}
#create a vector of offsets of columns to be removed
colNA <- c()
cut <- 0.7*dim(traindata)[1]
j <- 1
for(i in 1:length(sumNA)){
   if(sumNA[i] > cut){
   colNA[j] <- i
   j <- j+1
   }
}
#Remove the columns with resulting offsets
traindata <- traindata[,-colNA]
#Applying the transformation to the test set as well
testdata <- testdata[,-colNA]
#Display the final dimensions of our data
dim(testdata);dim(traindata)
## [1] 20 53
## [1] 19622    53

The number of observations in the training data set is enough to be splitted into a new training dataset (70%), and a “validation datasset” (30%)

Partitioning the training data set

inTrain <- createDataPartition(traindata$classe,p=0.6,list = FALSE)
myTrain <- traindata[inTrain,]
myValid <- traindata[-inTrain,]
dim(myTrain);dim(myValid)
## [1] 11776    53
## [1] 7846   53

Prediction algorithms

We use the classification trees and random forests for prediction

Classification trees

control <- trainControl(method = "cv", number = 5)
rpart_mod <- train(classe ~ ., data = myTrain, method = "rpart", 
                   trControl = control)
print(rpart_mod, digits = 4)
## CART 
## 
## 11776 samples
##    52 predictor
##     5 classes: 'A', 'B', 'C', 'D', 'E' 
## 
## No pre-processing
## Resampling: Cross-Validated (5 fold) 
## Summary of sample sizes: 9420, 9421, 9421, 9420, 9422 
## Resampling results across tuning parameters:
## 
##   cp       Accuracy  Kappa  
##   0.03571  0.5278    0.39218
##   0.05996  0.3900    0.16576
##   0.11462  0.3146    0.04637
## 
## Accuracy was used to select the optimal model using  the largest value.
## The final value used for the model was cp = 0.03571.
fancyRpartPlot(rpart_mod$finalModel)

# prediction using validation dataset
predict1 <- predict(rpart_mod, myValid)
# Results
ConfMatrix <- confusionMatrix(myValid$classe, predict1)
ConfMatrix$overall[1]
##  Accuracy 
## 0.4973235

The accuracy is 0.5419 which means that the classification trees don’t predict well the outcome

Random Forests

RF_mod <- train(classe ~ ., data = myTrain, method = "rf", 
                   trControl = control)
print(RF_mod, digits = 4)
## Random Forest 
## 
## 11776 samples
##    52 predictor
##     5 classes: 'A', 'B', 'C', 'D', 'E' 
## 
## No pre-processing
## Resampling: Cross-Validated (5 fold) 
## Summary of sample sizes: 9421, 9420, 9423, 9420, 9420 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy  Kappa 
##    2    0.9886    0.9856
##   27    0.9886    0.9856
##   52    0.9832    0.9787
## 
## Accuracy was used to select the optimal model using  the largest value.
## The final value used for the model was mtry = 27.
# prediction using validation dataset
predict2 <- predict(RF_mod, myValid)
# Results
ConfMatrix_RF <- confusionMatrix(myValid$classe, predict2)
ConfMatrix_RF$overall[1]
##  Accuracy 
## 0.9917155

Prediction is highly accurate using the random Forest method.

Prediction applied to testing set

predict(RF_mod,testdata)
##  [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