-
Notifications
You must be signed in to change notification settings - Fork 0
/
PML_Project
76 lines (58 loc) · 2.15 KB
/
PML_Project
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
#R Programming work for Practical Machine Learning
#Dan Goodman, 22 June 2014
library(caret)
library(rpart.plot)
library(rattle)
library(AppliedPredictiveModeling)
library(ggplot2)
setwd("~/R/Coursera")
#Get data and clean up column types
training <- read.csv("pml-training.csv")
training$classe <- factor(training$classe)
testing <- read.csv("pml-testing.csv")
testing$var_accel_forearm <- as.numeric(testing$var_accel_forearm)
testing$var_total_accel_belt <- as.numeric(testing$var_total_accel_belt)
testing$var_accel_arm <- as.numeric(testing$var_accel_arm)
testing$var_accel_dumbbell <- as.numeric(testing$var_accel_dumbbell)
ColFilter <- as.list(apply(training, 2, function(x)length(unique(x))))
Keep <- names(which(ColFilter>2))
training <- subset(training, select = Keep)
ColFilterTest <- as.list(apply(training, 2, function(x)length(unique(x))))
KeepTest <- Keep
KeepTest[153]="problem_id"
testing <- subset(testing, select = KeepTest)
#Split Training Set
inTrain = createDataPartition(training$classe, p = 0.7)[[1]]
TrainSet = training[ inTrain,]
TestSet = training[-inTrain,]
#Data is Messy, Focus on Accelerometers only
#Just Use Accelerometer Values
Accel <- grep("^accel", names(TrainSet))
AccelTrain <- TrainSet[,c(Accel,which(names(TrainSet)=="classe"))]
AccelTest <- TestSet[,c(Accel,which(names(TestSet)=="classe"))]
#Try a Tree Model
ModelCart <- train(classe~., method="rpart", data=AccelTrain)
print(ModelCart)
fancyRpartPlot(ModelCart$finalModel)
#Predict on TestSet
AccelPredict <- predict(ModelCart, newdata = AccelTest)
print(confusionMatrix(AccelPredict,AccelTest$classe))
## Get Values for Test Set
testing <- testing[,c(Accel,which(names(testing)=="problem_id"))]
Predictions <- predict(ModelCart, newdata = testing)
#Create Output Files
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 (Predictions)
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)
}
}