-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLoad_data.R
More file actions
76 lines (58 loc) · 2.6 KB
/
Copy pathLoad_data.R
File metadata and controls
76 lines (58 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
library(caret);library(kernlab)
set.seed(32323)
# Load the test file:
dataset <- read.csv("pml-training.csv", na.strings=c("NA",""), strip.white=TRUE)
dim(dataset)
# Cleaning the data:
isNA <- apply(dataset, 2, function(x) { sum(is.na(x)) })
dataset <- subset(dataset[, which(isNA == 0)],
select=-c(X, user_name, new_window, num_window,
raw_timestamp_part_1, raw_timestamp_part_2,
cvtd_timestamp))
dim(dataset)
# Spliting the dataset:
inTrain <- createDataPartition(dataset$classe, p=0.75, list=FALSE)
train_set <- dataset[inTrain,]
valid_set <- dataset[-inTrain,]
folds <- createFolds(y=dataset$classe,k=10,
list=TRUE,returnTrain=TRUE)
sapply(folds,length)
# Test 1: Random forest classifier using cross validation contol
ctrl <- trainControl(allowParallel=TRUE, method="cv", number=4)
model <- train(classe ~ ., data=train_set, model="rf", trControl=ctrl)
predictor <- predict(model, newdata=valid_set)
# Error on valid_set:
sum(predictor == valid_set$classe) / length(predictor)
confusionMatrix(valid_set$classe, predictor)$table
# Classification for test_set:
dataset_test <- read.csv("pml-testing.csv", na.strings=c("NA",""), strip.white=T)
dataset_test <- subset(dataset_test[, which(isNA == 0)],
select=-c(X, user_name, new_window, num_window,
raw_timestamp_part_1, raw_timestamp_part_2,
cvtd_timestamp))
predict(model, newdata=dataset_test)
# Test 2: SVM:
# Most important variable for the ramdom forest predictor:
varImp(model)
# Let us train the SVM on the dataset reduce to those ten variables
dataset_small <- subset(dataset,
select=c(roll_belt, pitch_forearm, yaw_belt,
magnet_dumbbell_y, pitch_belt,
magnet_dumbbell_z, roll_forearm,
accel_dumbbell_y, roll_dumbbell,
magnet_dumbbell_x,classe))
svm <- train(classe ~ ., data=dataset_small[inTrain,], model="svm", trControl=ctrl)
predictor_svm <- predict(svm, newdata=valid_set)
# Error on valid_set:
sum(predictor_svm == valid_set$classe) / length(predictor_svm)
confusionMatrix(valid_set$classe, predictor_svm)$table
# Classification for test_set:
results <- predict(model, newdata=dataset_test)
pml_write_files = function(x){
n = length(x)
for(i in 1:n){
filename = paste0("problem_id_",i,".txt")
write.table(x[i],file=filename,quote=FALSE,row.names=FALSE,col.names=FALSE)
}
}
pml_write_files(results)