Introduction

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. The goal of this project is to use data from accelerometers on the belt, forearm, arm, and dumbbell of 6 participants as they perform barbell lifts correctly and incorrectly 5 different ways.

The data for this project come from this source http://groupware.les.inf.puc-rio.br/har. The training data for this project are available at https://d396qusza40orc.cloudfront.net/predmachlearn/pml-training.csv and the test data are available at https://d396qusza40orc.cloudfront.net/predmachlearn/pml-testing.csv.

Analysis

All the required packages are loaded in R.

library(caret)
library(rpart)
library(rpart.plot)
library(RColorBrewer)
library(rattle)
library(e1071)
library(randomForest)

The seed is set in order to allow the reproducibility of the results.

set.seed(1)

Data are firstly downloaded.

train_url <- 'https://d396qusza40orc.cloudfront.net/predmachlearn/pml-training.csv'
test_url <- 'https://d396qusza40orc.cloudfront.net/predmachlearn/pml-testing.csv'

train_file <- file.path(paste(getwd(), '/', sep = ''), 'machine-train-data.csv')
download.file(train_url, destfile = train_file)

test_file <- file.path(paste(getwd(), '/', sep = ''), 'machine-test-data.csv')
download.file(test_url, destfile = test_file)

Then data are uploaded in R (missing data are marked alternatively as ‘NA’, ‘#DIV/0!’ and ’’)

train_data <- read.csv(train_file, na.strings = c('NA', '#DIV/0!', ''))
test_data <- read.csv(test_file, na.strings = c('NA', '#DIV/0!', ''))

Data are cleaned in order to remove columns with NA values. Moreover, unuseful columns are also removed.

train_data <- train_data[, !apply(train_data, 2, anyNA)] 
test_data <- test_data[, !apply(test_data, 2, anyNA)] 
train_data <- train_data[, -c(1:7)]
test_data <- test_data[, -c(1:7)]

The training data set is divided into two sets: the training set (with 60% of the data) wand the validation set (with the remaining 40% of the data).

in_training <- createDataPartition(train_data$classe, p = 0.60, list = FALSE)
train_data <- train_data[in_training, ]
validation_data <- train_data[-in_training, ]

Now, the training data set is used in order to fit a Random Forest model.

ctrl_parms <- trainControl(method = 'cv', 5)
rf_model <- train(classe ~ ., data = train_data, method = 'rf', trControl = ctrl_parms, ntree = 10)
print(rf_model)
## 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, 9420, 9423, 9420 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy   Kappa    
##    2    0.9696843  0.9616350
##   27    0.9826769  0.9780838
##   52    0.9776674  0.9717437
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 27.

Then model fit is tested against the validation data.

rf_pred <- predict(rf_model, validation_data)
print(confusionMatrix(as.factor(validation_data$classe), rf_pred))
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction    A    B    C    D    E
##          A 1332    0    0    0    0
##          B    0  920    0    0    0
##          C    0    1  832    0    0
##          D    0    0    0  766    0
##          E    0    0    0    0  852
## 
## Overall Statistics
##                                      
##                Accuracy : 0.9998     
##                  95% CI : (0.9988, 1)
##     No Information Rate : 0.2832     
##     P-Value [Acc > NIR] : < 2.2e-16  
##                                      
##                   Kappa : 0.9997     
##                                      
##  Mcnemar's Test P-Value : NA         
## 
## Statistics by Class:
## 
##                      Class: A Class: B Class: C Class: D Class: E
## Sensitivity            1.0000   0.9989   1.0000   1.0000   1.0000
## Specificity            1.0000   1.0000   0.9997   1.0000   1.0000
## Pos Pred Value         1.0000   1.0000   0.9988   1.0000   1.0000
## Neg Pred Value         1.0000   0.9997   1.0000   1.0000   1.0000
## Prevalence             0.2832   0.1958   0.1769   0.1629   0.1812
## Detection Rate         0.2832   0.1956   0.1769   0.1629   0.1812
## Detection Prevalence   0.2832   0.1956   0.1771   0.1629   0.1812
## Balanced Accuracy      1.0000   0.9995   0.9999   1.0000   1.0000
accuracy <- postResample(rf_pred, as.factor(validation_data$classe))
accuracy_out <- accuracy[1]

overall_out <- 1 - as.numeric(confusionMatrix(as.factor(validation_data$classe), rf_pred)$overall[1])

Finally, the model is applied to the test data and the result is printed.

result <- predict(rf_model, test_data[, -length(names(test_data))])
print(result)
##  [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

Below the decision tree visualization.

tree_model <- rpart(classe ~ ., data = train_data, method = 'class')
fancyRpartPlot(tree_model)