-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathProject 2 Group Work.Rmd
311 lines (239 loc) · 7.67 KB
/
Project 2 Group Work.Rmd
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
---
title: "DATA 624 Final Project"
date: "`r Sys.Date()`"
output:
rmdformats::readthedown:
highlight: kate
toc_depth: 3
code_folding: "show"
---
# R Libraries
```{r, echo = T, results = 'hide'}
library(caret)
library(tidyverse)
library(corrplot)
library(kableExtra)
library(mlbench)
library(dplyr)
library(readxl)
library(VIM)
library(psych)
library(xgboost)
library(Matrix)
library(writexl)
seed <- 12345
```
# Exploratory Data Analysis and PreProcessing
## Data Loading
```{r}
train <- read_excel("StudentData.xlsx")
test <- read_excel("StudentEvaluation.xlsx")
```
## Data Statistics
```{r}
dim(train)
dim(test)
```
#### Complete observations
```{r}
nrow(train[complete.cases(train),])
```
#### All predictors are numeric except for "Brand Code, 1st Variable)
```{r}
summary(train)
summary(test)
```
## Handling missing values (Train and Test sets)
```{r, warning=FALSE}
# Response
train <- train %>% drop_na(PH)
#Predictors
train <- kNN(train, imp_var=FALSE)
```
## Correlation Analysis
```{r}
# Analyze Correlations with the response variable
names <- colnames(train[,-26])
pairs.panels(train[, c("PH", names[1:8])])
pairs.panels(train[, c("PH", names[9:17])])
pairs.panels(train[, c("PH", names[18:26])])
pairs.panels(train[, c("PH", names[27:32])])
```
Top correlated features to PH:
- Mnf Flow (-0.45)
- Bowl Setpoint (0.35)
- Filler Level (0.32)
- Usage Cont (-0.32)
- Pressure Setpoint (-0.31)
- Hyd Pressure3 (-0.24)
- Pressure Vacuum (0.22)
- Hyd Pressure2 (-0.20)
```{r}
train2 <- train %>% dplyr::select(-'Brand Code')
mydata.cor = cor(train2, method = c("spearman"))
corrplot(mydata.cor,cl.cex = 0.7,tl.cex = .7,diag = TRUE)
```
## Correlated Predictors
```{r}
corr <- cor(train[,-c(1,26)], use='complete.obs')
topcorr <- findCorrelation(corr) #top correlated predictors that could be removed to improve modeling
colnames(train[,topcorr])
corrplot(cor(train[,topcorr], use='complete.obs'))
```
## Near Zero Variance Predictors
```{r}
nzv <- nearZeroVar(train)
colnames(train[,nzv])
```
"Hyd Pressure1" should be removed from the dataset as it is constant across observations
## Data Distribution & Variability
```{r}
boxplot(train[, c(names[2:6])])
boxplot(train[, c(names[7:11])])
boxplot(train[, c(names[12:15])])
boxplot(train[, c(names[16:20])])
boxplot(train[, c(names[21:26])])
boxplot(train[, c(names[27:32])])
############ Look at some Decision Trees ##################
source("https://raw.githubusercontent.com/crarnouts/Data_605_Final/master/RandomForestNulls_testing.R")
colnames(train)<- make.names(colnames(train), unique=TRUE)
colnames(test)<- make.names(colnames(test), unique=TRUE)
train <- as.data.frame(train)
test <- as.data.frame(test)
test <- RF_with_Nulls(train,test,"PH",.5,5,10,.01,5,1)
```
## Data Split
```{r}
set.seed(seed)
train_index <- createDataPartition(train$PH, p = .7, list = FALSE, times = 1)
training <- train[train_index,]
testing <- train[-train_index,]
# Preparing test set for validation
Xtest <- testing[,-grep("PH", colnames(testing))]
```
# Modeling & Evaluation
## Linear Regression
```{r}
set.seed(seed)
lm <- lm(PH~.,data = training)
summary(lm)
```
## Bagged Tree
```{r, warning=FALSE}
set.seed(seed)
bagControl = bagControl(fit = ctreeBag$fit, predict = ctreeBag$pred, aggregate = ctreeBag$aggregate)
bag_model <- train(PH ~.,
data = training, method="bag", bagControl = bagControl,
center = TRUE,
scale = TRUE,
trControl = trainControl("cv", number = 5),
tuneLength = 25)
bag_model
bag_pred <- predict(bag_model, newdata = Xtest)
postResample(obs = testing$PH, pred=bag_pred)
varImp(bag_model)
```
## XGBoost (Extreme Gradient Boosting)
```{r}
# Converting datasets to matrices
training2 <- training %>% drop_na(`Brand.Code`)
testing2 <- testing %>% drop_na(`Brand.Code`)
trainingmx<-model.matrix(~.+0,data=training2[,names(training2) != c("PH")])
testingmx<-model.matrix(~.+0,data=testing2[,names(testing2) != c("PH")])
trainingdmx <- xgb.DMatrix(data = trainingmx, label=training2$PH)
testingdmx <- xgb.DMatrix(data = testingmx, label=testing2$PH)
# Default parameters
params <- list(booster = "gbtree", objective = "reg:linear", eta=0.3, gamma=0, max_depth=6, min_child_weight=1, subsample=1, colsample_bytree=1)
# Determine the best nround parameter (It controls the maximum number of iterations. For classification, it is similar to the number of trees to grow.)
xgbcv <- xgb.cv( params = params, data = trainingdmx, nrounds = 300, nfold = 5, showsd = T, stratified = T, print_every_n = 10, early_stop_rounds = 20, maximize = F)
# Best at 260 iterations:
```
```{r}
set.seed(seed)
xgb_model1 <- xgb.train (params = params, data = trainingdmx, nrounds = 260, watchlist = list(val=testingdmx,train=trainingdmx), print_every_n = 10, early_stop_round = 10, maximize = F)
# Best result at iteration 211 for training and validation sets:
```
```{r}
mat <- xgb.importance (feature_names = colnames(trainingmx),model = xgb_model1)
xgb.plot.importance (importance_matrix = mat)
```
## SVM
```{r}
ctrl = trainControl(method='cv', number = 10)
set.seed(seed)
svmRad <- train(PH ~.,
data=training,
method = "svmRadial",
preProc = c("center", "scale"),
tuneLength = 14,
trControl = ctrl)
svmRad
svm_pred <- predict(svmRad, newdata = Xtest)
postResample(obs = testing$PH, pred=svm_pred)
varImp(svmRad)
```
## Cubist
```{r}
set.seed(seed)
cubist <- train(PH ~.,
data = training,
method='cubist')
cubist #display model performance
varImp(cubist) #display variable importance
cubist_pred <- predict(cubist, newdata=Xtest) # generate preds
postResample(obs=testing$PH, pred=cubist_pred) # evaluate model over test set
```
## Random Forest
```{r}
ctrl = trainControl(method='cv', number = 10, allowParallel = TRUE)
set.seed(seed)
rforest <- train(PH ~.,
data = training,
method = "ranger",
importance = "permutation",
tuneLength = 10,
trControl = ctrl
)
rforest #display model performance
varImp(rforest) #display variable importance
rf_pred <- predict(rforest, newdata = Xtest) # generate preds
postResample(obs = testing$PH, pred=rf_pred) # Evaluate model over test set
```
#### Training Random Forest over Individual Brand Codes
```{r brand_ranger_rf}
for (brand_code in unique(training$Brand.Code)){
print(paste("Brand Code", brand_code))
temp_df <- training %>%
filter(Brand.Code == brand_code) %>%
select(-Brand.Code)
set.seed(seed)
temp_rf <- train(PH ~ ., data = temp_df, method = "ranger", importance = "permutation", trControl = ctrl)
print(temp_rf)
print(varImp(temp_rf))
temp_test <- testing %>%
filter(Brand.Code == brand_code) %>%
select(-Brand.Code)
temp_predictions <- predict(temp_rf, temp_test)
print(postResample(pred = temp_predictions, obs = temp_test$PH))
}
```
# Predicting New Data w/Random Forest
```{r, warning=FALSE}
pfile <- read_excel("StudentEvaluation.xlsx")
#Preparing the dataset we will ultimately predict PH on
test <- pfile[,-grep("PH", colnames(pfile))]
test <- kNN(test, imp_var=FALSE)
colnames(test)<- make.names(colnames(test), unique=TRUE)
ctrl = trainControl(method='cv', number = 10)
set.seed(seed)
rf_model <- train(PH ~.,
data = train,
method = "ranger",
importance = "permutation",
tuneLength = 10,
trControl = ctrl
)
final_rf_pred <- predict(rf_model, newdata=as.data.frame(test))
pfile$PH <- final_rf_pred # applying predictions to unimputed dataset
write_xlsx(pfile, "Predictions_file.xlsx") # write to excel
```