library(AppliedPredictiveModeling) # chemical manufacturing data
library(mlbench) # friedman simulated data
library(caret)
library(randomForest) # random forest
library(party)
library(gbm) # boosted trees
library(Cubist)
library(rpart) # single trees
library(ipred) # bagged trees
library(kernlab)
library(glmnet) # lasso
library(RANN) # for knn imputation
Same simulated data as 7.2. Only V1 to V5 are used to make y. V6 to V10 are just noise.
#book starter code
set.seed(200)
simulated <- mlbench.friedman1(200, sd = 1)
simulated <- cbind(simulated$x, simulated$y)
simulated <- as.data.frame(simulated)
colnames(simulated)[ncol(simulated)] <- "y"
# lets fit a random forest and get the importance measure
set.seed(200)
model1 <- randomForest(y ~ ., data = simulated, importance = TRUE, ntree = 1000)
rfImp1 <- varImp(model1, scale = FALSE)
round(rfImp1, 2)
## Overall
## V1 8.68
## V2 6.49
## V3 0.77
## V4 7.78
## V5 2.39
## V6 0.01
## V7 0.01
## V8 -0.11
## V9 -0.03
## V10 -0.04
No, it didn’t really use V6 to V10 as they were basically 0 (the biggest one is 0.11), while V1, V2 and V4 are the tops ones.Out of the real ones, V3 is the weakest but its still above noise.
# conditional inference trees with the same data and two copies
set.seed(200)
cfModel <- party::cforest(y ~ ., data = simulated, controls = cforest_unbiased(ntree = 500))
# regular importance and the conditional version from Strobl et al.
cf_regular <- party::varimp(cfModel, conditional = FALSE)
cf_conditional <- party::varimp(cfModel, conditional = TRUE)
cf_table <- data.frame(regular = cf_regular[vars], conditional = cf_conditional[vars], row.names = vars)
round(cf_table, 2)
## regular conditional
## V1 5.84 2.49
## V2 5.92 4.55
## V3 0.02 0.04
## V4 7.47 5.66
## V5 1.71 0.93
## V6 0.04 0.03
## V7 0.06 -0.03
## V8 -0.03 -0.01
## V9 0.01 0.02
## V10 -0.04 -0.02
## duplicate1 2.44 0.76
## duplicate2 1.40 0.32
Basically the same pattern. V4, V2 and V1 remain the top ones, the noisy variables are still near 0, and V1 is still sharing its importance amongts the two copies. The conditional version just makes everything smaller and it pulls V1 and the copies down the most because it adjusts itself for predictors that are correlated with each other. So copies look less important, but V1 doesn’t get its score back.
x_sim <- simulated[, vars]
# boosted trees
set.seed(200)
gbmModel <- gbm(y ~ ., data = simulated, distribution = "gaussian",
n.trees = 1000, interaction.depth = 3, shrinkage = 0.1)
gbm_imp <- summary(gbmModel, plotit = FALSE)
# cubist with 100 committees
cubModel <- cubist(x = x_sim, y = simulated$y, committees = 100)
cub_imp <- varImp(cubModel)
other_table <- data.frame(boosted = gbm_imp[vars, "rel.inf"],
cubist = cub_imp[vars, "Overall"],
row.names = vars)
round(other_table, 1)
## boosted cubist
## V1 12.6 68.5
## V2 20.8 59.0
## V3 7.2 48.0
## V4 28.3 47.5
## V5 11.7 27.5
## V6 2.5 9.5
## V7 2.4 0.0
## V8 1.5 2.0
## V9 1.5 0.0
## V10 1.0 0.0
## duplicate1 7.5 2.0
## duplicate2 3.1 0.0
Boosted trees show similar pattern. V4 and V2 are on top, the noisy variables are low, and V1 is sharing its importance with the two copies. Cubist is different. It keeps V1 near the top and gives the copies very little, so it wasn’t thrown off by the correlated predictors the way the tree ensembles were.
The idea is that trees favor and split of predictors that have many diffirent values, even when the predictor happens to not have any use. To show this idea I made four predictors that have nothing to do with y at all with theonly difference between them is being how many different values they have 2, 10, 50, or all different. Then I grew a tree with just one split and checked which predictor it picked, and repeated that same proccess 500 times.
set.seed(624)
n <- 200
reps <- 500
first_split <- character(reps)
for (i in 1:reps) {
# y is just straight noise, so no predictor should be better than the others
d <- data.frame(y = rnorm(n),
x2 = sample(1:2, n, replace = TRUE), # 2 different values
x10 = sample(1:10, n, replace = TRUE), # 10 different values
x50 = sample(1:50, n, replace = TRUE), # 50 different values
xcont = rnorm(n)) # all different values
# tree with a single split
fit <- rpart(y ~ ., data = d, maxdepth = 1, cp = 0)
# save which predictor was used for the split
first_split[i] <- as.character(fit$frame$var[1])
}
# how oftenly each predictor was picked
split_pct <- prop.table(table(factor(first_split, levels = c("x2", "x10", "x50", "xcont"))))
round(split_pct, 2)
##
## x2 x10 x50 xcont
## 0.04 0.16 0.34 0.46
barplot(split_pct, ylab = "Share of first splits", xlab = "Predictor",
main = "Which noise predictor gets picked first")
Assuming the tree was fair, each predictor would’ve gotten picked about 25% of the time since none of them matter however the one with only 2 values got picked 4% of the time and the continuous one got picked 46% of the time. The more different values a predictor has, the more spots there there is to split it, so it has more chances to look good just by luck. That is the bias.
This one is about Figure 8.24. The left plot has the bagging fraction and learning rate both at 0.1, and the right plot has both at 0.9.
When the learning rate is high (0.9), every tree contributes nearly all of its prediction. So that’s why early trees account for the bulk of the error using powerful predictors. Since each tree uses essentially the same data when the bagging fraction is set to 0.9, the same predictors get selected by each individual tree. This results in the vast majority of importance being put on a small number of those predictors.
On the left, each tree contributes only 10% of its prediction and also only uses a randomly chosen 10% of the data that’s available however it does need many more trees to accomplish the same result as above, and because each tree uses different data, different features will be selected during the process. Therefore, importance is distributed across multiple predictors.
The left one (both at 0.1). This approach learns slowly and uses a different small sample for each tree to evade an overfitting to the training data. The right one is greedy and focuses on a few predictors so I would expect it to perform worse on new data.
A higher interaction depth sticks to more splits within each tree and therefore a larger number of predictors used with each tree. From this the consequence would be that the slope for both models would be less steep.
Same steps as before. The sensor failure zeros get treated as missing, missing values are filled in with the 5 nearest neighbors and then a 75/25 split. Trees do not need centering and scaling, so the only other step is dropping the near zero variance predictor.
data(ChemicalManufacturingProcess)
cmp <- ChemicalManufacturingProcess
pred_names <- setdiff(names(cmp), "Yield")
# one 0 in a column where everything else is far from 0 is a sensor failureand we make it NA
for (v in pred_names) {
x <- cmp[[v]]
nz <- x[!is.na(x) & x != 0]
if (sum(x == 0, na.rm = TRUE) == 1 && length(nz) > 2 && mean(nz) / sd(nz) > 5) cmp[[v]][x == 0] <- NA
}
# fill missing values using the 5 most similar runs
imp <- preProcess(cmp[, pred_names], method = "knnImpute", k = 5)
X <- predict(imp, cmp[, pred_names])
X <- sweep(sweep(X, 2, imp$std, "*"), 2, imp$mean, "+") # back to original units
cmp <- data.frame(Yield = cmp$Yield, X)
# 75/25 split
set.seed(624)
idx <- createDataPartition(cmp$Yield, p = 0.75, list = FALSE)
train <- cmp[idx, ]
test <- cmp[-idx, ]
# 10-fold CV repeated 5 times, same folds will happen for every model
ctrl <- trainControl(method = "repeatedcv", number = 10, repeats = 5,
index = createMultiFolds(train$Yield, k = 10, times = 5))
# drop the near zero variance predictors
nzv <- nearZeroVar(train)
names(train)[nzv]
## [1] "BiologicalMaterial07"
train <- train[, -nzv]
test <- test[, -nzv]
# predictors by themselves
trainX <- train[, names(train) != "Yield"]
testX <- test[, names(test) != "Yield"]
# single tree, tune how deep it goes
set.seed(624)
tree7 <- train(x = trainX, y = train$Yield, method = "rpart2", tuneLength = 10, trControl = ctrl)
# bagged trees, nothing to tune
set.seed(624)
bag7 <- train(x = trainX, y = train$Yield, method = "treebag", nbagg = 50, trControl = ctrl)
# random forest and tuning how many predictors are attempted at each split
set.seed(624)
rf7 <- train(x = trainX, y = train$Yield, method = "rf", tuneLength = 5, ntree = 500, trControl = ctrl)
# boosted trees, tune depth, number of trees and learning rate
set.seed(624)
gbm7 <- train(x = trainX, y = train$Yield, method = "gbm",
tuneGrid = expand.grid(interaction.depth = c(1, 3, 5),
n.trees = seq(100, 1000, by = 100),
shrinkage = c(0.01, 0.1),
n.minobsinnode = 10),
verbose = FALSE, trControl = ctrl)
# cubist, tune committees and neighbors
set.seed(624)
cub7 <- train(x = trainX, y = train$Yield, method = "cubist",
tuneGrid = expand.grid(committees = c(1, 10, 50, 100), neighbors = c(0, 1, 5, 9)),
trControl = ctrl)
models7 <- list(Tree = tree7, Bagged = bag7, RandomForest = rf7, Boosted = gbm7, Cubist = cub7)
# cross validation and test results side by side
cv7 <- t(sapply(models7, function(m) unlist(getTrainPerf(m)[1:2])))
test7 <- t(sapply(models7, function(m) postResample(predict(m, testX), test$Yield)))
results7 <- cbind(cv7, test7[, 1:2])
colnames(results7) <- c("CV RMSE", "CV R2", "Test RMSE", "Test R2")
round(results7, 2)
## CV RMSE CV R2 Test RMSE Test R2
## Tree 1.32 0.47 1.75 0.33
## Bagged 1.12 0.63 1.48 0.51
## RandomForest 1.08 0.66 1.41 0.57
## Boosted 1.05 0.67 1.36 0.59
## Cubist 0.93 0.72 1.20 0.68
# best model by each measure
best_cv <- rownames(results7)[which.min(results7[, "CV RMSE"])]
best_test <- rownames(results7)[which.min(results7[, "Test RMSE"])]
cub7$bestTune
## committees neighbors
## 10 50 1
The best one in after cross-validation proccess was Cubist with an RMSE of 0.93, and the best one on the test is Cubist with an RMSE of 1.2 and an R-squared of 0.68. So Cubist is the best tree model on both. Theworst one ended up being the single tree which makes sense since one tree is pretty rough. Bagging, random forest and boosting each do a little better than the one before, but none of them match up to Cubist.
cub_imp7 <- varImp(cub7)
plot(cub_imp7, top = 10)
# top ten names
cub_top10 <- rownames(cub_imp7$importance)[order(-cub_imp7$importance$Overall)][1:10]
# how many are biological and how many are process
table(substr(cub_top10, 1, 3))
##
## Bio Man
## 3 7
ManufacturingProcess32 is the most important one by a lot. The top ten has 7 process variables and 3 biological ones, so the process variables dominate the list basically. Now the top ten from the best linear model (the lasso from Homework 7) and the best nonlinear model (the SVM from Homework 8), fit on the same split.
# helper to get the model is top ten names
top10 <- function(m) {
vi <- varImp(m)$importance
rownames(vi)[order(-vi$Overall)][1:10]
}
# these two need centering and scaling
pp <- c("center", "scale")
# lasso from Homework 7
lin7 <- train(Yield ~ ., data = train, method = "glmnet",
tuneGrid = expand.grid(alpha = seq(0, 1, by = 0.1),
lambda = 10^seq(-3, 0.5, length = 30)),
preProcess = pp, trControl = ctrl)
# SVM from Homework 8
set.seed(624)
svm7 <- train(Yield ~ ., data = train, method = "svmRadial", tuneLength = 10,
preProcess = pp, trControl = ctrl)
lin_top10 <- top10(lin7)
svm_top10 <- top10(svm7)
# the three lists side by side
data.frame(Cubist = cub_top10, Lasso = lin_top10, SVM = svm_top10)
## Cubist Lasso SVM
## 1 ManufacturingProcess32 ManufacturingProcess32 ManufacturingProcess32
## 2 BiologicalMaterial06 ManufacturingProcess33 BiologicalMaterial06
## 3 BiologicalMaterial02 ManufacturingProcess09 BiologicalMaterial03
## 4 BiologicalMaterial03 BiologicalMaterial03 ManufacturingProcess31
## 5 ManufacturingProcess09 ManufacturingProcess37 ManufacturingProcess13
## 6 ManufacturingProcess33 ManufacturingProcess06 ManufacturingProcess36
## 7 ManufacturingProcess17 ManufacturingProcess04 ManufacturingProcess09
## 8 ManufacturingProcess04 ManufacturingProcess29 BiologicalMaterial12
## 9 ManufacturingProcess13 ManufacturingProcess17 BiologicalMaterial02
## 10 ManufacturingProcess29 ManufacturingProcess39 ManufacturingProcess11
intersect(cub_top10, lin_top10) # in both the Cubist and lasso lists
## [1] "ManufacturingProcess32" "BiologicalMaterial03" "ManufacturingProcess09"
## [4] "ManufacturingProcess33" "ManufacturingProcess17" "ManufacturingProcess04"
## [7] "ManufacturingProcess29"
intersect(cub_top10, svm_top10) # in both the Cubist and SVM lists
## [1] "ManufacturingProcess32" "BiologicalMaterial06" "BiologicalMaterial02"
## [4] "BiologicalMaterial03" "ManufacturingProcess09" "ManufacturingProcess13"
ManufacturingProcess32 is the top one in all three. The Cubist list shares 7 predictors with the lasso list and 6 with the SVM list so it looks a lot more like the linear model which it does make sense to me because Cubist puts small linear models inside its rules. The SVM list has more biological variables since that ranking looks at each predictor by itself.
# refit the single tree with the above is tuned depth
tree7$bestTune
## maxdepth
## 2 2
best_tree <- rpart(Yield ~ ., data = train,
control = rpart.control(maxdepth = tree7$bestTune$maxdepth, cp = 0))
# plot it with a boxplot of yield in each end node
plot(partykit::as.party(best_tree))
Yes, it does help a little bit as we can see the first split is on ManufacturingProcess32, and the runs on the higher side of it clearly have higher yield. On the low side, the next split is on BiologicalMaterial12, and the runs with low values of it have the lowest yield of all. On the high side, the next split is ManufacturingProcess06 where most of the runs land in the node with the highest yield.
So the takeaway is that the process variables matter first, and the biological material matters more when the process side isn’t properley set up. Thit is useful because the process variables can be changed and the biological ones can only be checked before a run. It is still just one small tree though, and it was the worst model in part a, however I would not read too much into the exact cutoffs.