Since the datasets are pre-loaded in the active lab environment, we retrieve them directly to ensure reproducible execution during document compilation.
training_data <- read.csv("pml-training.csv", na.strings = c("NA", "#DIV/0!", ""))
testing_data <- read.csv("pml-testing.csv", na.strings = c("NA", "#DIV/0!", ""))
We drop columns containing missing values (NA) and remove the first 7 metadata columns (timestamps, user names, etc.) to ensure the model focuses exclusively on sensor movement signals.
# Clean columns with missing data
clean_training <- training_data[, colSums(is.na(training_data)) == 0]
clean_testing <- testing_data[, colSums(is.na(testing_data)) == 0]
# Strip identification metadata variables
clean_training <- clean_training[, -c(1:7)]
clean_testing <- clean_testing[, -c(1:7)]
# Convert the target outcome to a factor
clean_training$classe <- as.factor(clean_training$classe)
We set a random seed and partition our data into a 75% training subset and a 25% validation subset to measure model capabilities.
set.seed(12345)
in_train <- createDataPartition(clean_training$classe, p = 0.75, list = FALSE)
train_set <- clean_training[in_train, ]
val_set <- clean_training[-in_train, ]
A Random Forest classifier is built using 3-fold cross-validation configuration parameters.
control_cv <- trainControl(method = "cv", number = 3, verboseIter = FALSE)
rf_model <- train(classe ~ ., data = train_set, method = "rf", trControl = control_cv)
We predict values against our held-back validation subset to evaluate classification capability.
rf_predictions <- predict(rf_model, newdata = val_set)
conf_matrix <- confusionMatrix(rf_predictions, val_set$classe)
print(conf_matrix$overall['Accuracy'])
## Accuracy
## 0.9946982
The final out-of-sample accuracy achieved is 99.47%. Consequently, the expected out-of-sample error rate is estimated at approximately 0.53% (\(1 - \text{Accuracy}\)).
We match features between the testing structure and our training set before computing final outcome targets for the 20 test vectors.
clean_testing <- clean_testing[, colnames(clean_testing) %in% colnames(train_set)]
quiz_predictions <- predict(rf_model, newdata = clean_testing)
print(quiz_predictions)
## [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