Question: Use a simulation to show tree bias with different granularities.
Here granularity means the number of distinct values a predictor can take. I simulate a continuous outcome independent of all predictors, so none has a real association with the outcome. The predictors have 2, 5, 10, 20, or effectively continuous values. I fit a one-split CART tree in 300 independent simulations and count which predictor supplies the first split.
set.seed(820)
levelsToTry <- c(2, 5, 10, 20, 0)
granularityNames <- c("2 values", "5 values", "10 values",
"20 values", "Continuous")
selected <- character(300)
for (b in seq_along(selected)) {
x <- data.frame(
G2 = sample(1:2, 300, replace = TRUE),
G5 = sample(1:5, 300, replace = TRUE),
G10 = sample(1:10, 300, replace = TRUE),
G20 = sample(1:20, 300, replace = TRUE),
Continuous = runif(300)
)
x$y <- rnorm(300)
stump <- rpart::rpart(
y ~ ., data = x, method = "anova",
control = rpart::rpart.control(cp = 0, maxdepth = 1,
minsplit = 20, xval = 0)
)
selected[b] <- as.character(stump$frame$var[1])
}
selectionCounts <- table(factor(selected,
levels = c("G2", "G5", "G10", "G20", "Continuous")))
granularityResults <- data.frame(
Granularity = granularityNames,
First_split_count = as.integer(selectionCounts),
Percent = 100 * as.integer(selectionCounts) / length(selected)
)
knitr::kable(granularityResults, digits = 1, row.names = FALSE)
| Granularity | First_split_count | Percent |
|---|---|---|
| 2 values | 7 | 2.3 |
| 5 values | 29 | 9.7 |
| 10 values | 45 | 15.0 |
| 20 values | 61 | 20.3 |
| Continuous | 158 | 52.7 |
barplot(granularityResults$Percent, names.arg = granularityNames,
col = "steelblue", ylab = "Percent selected at first split",
main = "CART split selection when all predictors are noise")
abline(h = 20, lty = 2)
Answer: The most frequently selected granularity was Continuous, selected in 52.7% of simulations. The dashed line is the 20% equal-selection reference. Predictors with more distinct values offer more candidate cutpoints, giving CART more chances to find a favorable split by chance. The experiment demonstrates split-selection bias, not a genuine relationship or a formal test of equal selection.
Question: Why does the model with bagging fraction 0.9 and learning rate 0.9 focus on fewer predictors than the model using 0.1 for both?
Answer: A learning rate of 0.9 takes large steps. The first few strong predictors can account for much of the improvement quickly, concentrating the accumulated split-improvement scores. Using 90% of the observations per tree also makes the fitting process less stochastic. With learning rate 0.1, each tree contributes less, and a 10% bagging fraction creates more variation in the observations used to fit each tree. Across many trees this can give more predictors opportunities to contribute. This explains the figure’s pattern; neither parameter guarantees that importance will always be concentrated or spread out.
Question: Which of the two models is more likely to generalize?
Answer: I would initially expect the model with the smaller learning rate to generalize better, provided it has enough trees. Small updates can reduce overfitting. However, a bagging fraction of 0.1 leaves little data for each tree, which can also hurt performance. I would not select a model from its importance plot alone. I would tune the number of trees, depth, learning rate, and bagging fraction using resampling, then compare held-out prediction error.
Question: How might deeper trees change the decline in ranked importance scores?
Answer: Deeper trees allow predictors to enter through interactions and within smaller regions of the data. This can spread importance across more predictors and flatten a ranked importance curve, especially when important interactions exist. But it is not a guaranteed change: deeper trees can also reuse the same strong predictors and overfit. I would check the importance profiles and resampling error rather than assuming a particular slope.
The dataset, split seed, and preprocessing follow the HW7/HW8 step-by-step files: 80% training, 20% test, seed 6243, removal of constant predictors, median imputation, centering, and scaling. Preprocessing is fitted within each training fold. Scaling is not normally necessary for trees, but I retain the previous workflow for comparability.
data("ChemicalManufacturingProcess", package = "AppliedPredictiveModeling")
manufacturing <- ChemicalManufacturingProcess
x_mfg <- manufacturing[, names(manufacturing) != "Yield"]
y_mfg <- manufacturing$Yield
set.seed(6243)
trainRows <- sort(sample.int(nrow(x_mfg), floor(0.8 * nrow(x_mfg))))
xTrain <- x_mfg[trainRows, ]
xTest <- x_mfg[-trainRows, ]
yTrain <- y_mfg[trainRows]
yTest <- y_mfg[-trainRows]
set.seed(16243)
folds <- createFolds(yTrain, k = 10, returnTrain = TRUE)
ctrl <- trainControl(method = "cv", number = 10, index = folds,
allowParallel = FALSE)
prep <- c("zv", "medianImpute", "center", "scale")
c(Training = length(yTrain), Test = length(yTest),
Missing_predictor_cells = sum(is.na(x_mfg)))
## Training Test Missing_predictor_cells
## 140 36 106
Question: Which tree-based regression model has the best resampling and test performance?
I tune CART, random forest, gradient boosting, and Cubist using the
chapter’s caret::train() approach with common folds. RMSE
is measured in percentage points of yield. I select the overall
tree-based winner using CV RMSE, not the test-set ranking.
set.seed(870)
cartFit <- train(
x = xTrain, y = yTrain, method = "rpart", preProcess = prep,
tuneGrid = data.frame(cp = c(0, 0.005, 0.01, 0.02, 0.05, 0.1)),
trControl = ctrl, metric = "RMSE"
)
cartFit$bestTune
## cp
## 4 0.02
set.seed(871)
rfFit <- train(
x = xTrain, y = yTrain, method = "rf", preProcess = prep,
tuneGrid = data.frame(mtry = c(5, 15, 30, 45)),
ntree = 500, importance = TRUE, trControl = ctrl, metric = "RMSE"
)
rfFit$bestTune
## mtry
## 3 30
boostGrid <- expand.grid(
interaction.depth = c(1, 3),
n.trees = c(100, 300, 500),
shrinkage = c(0.01, 0.05),
n.minobsinnode = 5
)
set.seed(872)
gbmFit <- train(
x = xTrain, y = yTrain, method = "gbm", preProcess = prep,
tuneGrid = boostGrid, bag.fraction = 0.7, verbose = FALSE,
trControl = ctrl, metric = "RMSE"
)
gbmFit$bestTune
## n.trees interaction.depth shrinkage n.minobsinnode
## 6 500 3 0.01 5
set.seed(873)
cubistFit <- train(
x = xTrain, y = yTrain, method = "cubist", preProcess = prep,
tuneGrid = expand.grid(committees = c(1, 10, 25), neighbors = c(0, 5)),
trControl = ctrl, metric = "RMSE"
)
cubistFit$bestTune
## committees neighbors
## 6 25 5
treeModels <- list(CART = cartFit, Random_forest = rfFit,
Boosting = gbmFit, Cubist = cubistFit)
treeResults <- data.frame()
for (name in names(treeModels)) {
fit <- treeModels[[name]]
testScore <- postResample(pred = predict(fit, newdata = xTest), obs = yTest)
treeResults <- rbind(treeResults, data.frame(
Model = name, CV_RMSE = min(fit$results$RMSE),
Test_RMSE = testScore[["RMSE"]], Test_R2 = testScore[["Rsquared"]]
))
}
knitr::kable(treeResults, digits = 3, row.names = FALSE)
| Model | CV_RMSE | Test_RMSE | Test_R2 |
|---|---|---|---|
| CART | 1.532 | 1.521 | 0.320 |
| Random_forest | 1.175 | 1.236 | 0.619 |
| Boosting | 1.154 | 1.150 | 0.669 |
| Cubist | 0.997 | 0.842 | 0.808 |
winnerName <- treeResults$Model[which.min(treeResults$CV_RMSE)]
testWinner <- treeResults$Model[which.min(treeResults$Test_RMSE)]
winner <- treeModels[[winnerName]]
Answer: Cubist has the lowest resampled RMSE (0.997). The lowest held-out RMSE is from Cubist (0.842). These rankings can differ because there are only 36 test runs. The test R² is caret’s squared correlation, so I also examine RMSE rather than relying on R² alone.
Question: Which predictors are most important in the winning tree-based model, which type dominates, and how do its top ten compare with ridge and radial SVM?
I refit the previous ridge and radial SVM grids using the same split
and folds. The radial SVM was HW8’s best nonlinear model. For the
tree-based winner I use varImp(), following the chapter.
Ridge uses absolute standardized coefficients. For SVM I reuse HW8’s
training-only permutation ranking. The different importance scores are
not directly comparable in magnitude, so the comparison below uses
ranked names.
ridgeGrid <- expand.grid(alpha = 0, lambda = 10^seq(-3, 2, length.out = 26))
set.seed(16243)
ridgeFit <- train(
x = xTrain, y = yTrain, method = "glmnet", preProcess = prep,
tuneGrid = ridgeGrid, trControl = ctrl, metric = "RMSE",
standardize = FALSE, lambda = sort(ridgeGrid$lambda, decreasing = TRUE)
)
set.seed(6243)
svmFit <- train(
x = xTrain, y = yTrain, method = "svmRadial", preProcess = prep,
tuneGrid = expand.grid(sigma = c(0.005, 0.01, 0.025), C = c(0.5, 2, 8)),
trControl = ctrl, metric = "RMSE"
)
set.seed(71)
importanceFolds <- createFolds(yTrain, k = 5)
foldIncrease <- matrix(0, nrow = 5, ncol = ncol(xTrain))
for (i in seq_along(importanceFolds)) {
valid <- importanceFolds[[i]]
foldModel <- train(
x = xTrain[-valid, ], y = yTrain[-valid], method = "svmRadial",
preProcess = prep, tuneGrid = svmFit$bestTune,
trControl = trainControl(method = "none")
)
validation <- xTrain[valid, ]
baseline <- sqrt(mean((predict(foldModel, validation) - yTrain[valid])^2))
for (j in seq_len(ncol(validation))) {
shuffled <- validation
shuffled[[j]] <- sample(shuffled[[j]])
foldIncrease[i, j] <- sqrt(mean(
(predict(foldModel, shuffled) - yTrain[valid])^2)) - baseline
}
}
svmImportance <- setNames(colMeans(foldIncrease), names(xTrain))
treeImportance <- caret::varImp(winner, scale = FALSE)$importance
ridgeImportance <- caret::varImp(ridgeFit, scale = FALSE)$importance
topTree <- head(rownames(treeImportance)[order(-treeImportance$Overall)], 10)
topRidge <- head(rownames(ridgeImportance)[order(-ridgeImportance$Overall)], 10)
topSvm <- head(names(sort(svmImportance, decreasing = TRUE)), 10)
knitr::kable(data.frame(
Rank = 1:10, Tree_based = topTree, Ridge = topRidge, Radial_SVM = topSvm
), row.names = FALSE)
| Rank | Tree_based | Ridge | Radial_SVM |
|---|---|---|---|
| 1 | ManufacturingProcess32 | ManufacturingProcess32 | ManufacturingProcess32 |
| 2 | BiologicalMaterial06 | ManufacturingProcess09 | ManufacturingProcess04 |
| 3 | ManufacturingProcess17 | ManufacturingProcess13 | ManufacturingProcess09 |
| 4 | ManufacturingProcess04 | ManufacturingProcess36 | ManufacturingProcess36 |
| 5 | ManufacturingProcess09 | ManufacturingProcess17 | ManufacturingProcess37 |
| 6 | ManufacturingProcess33 | ManufacturingProcess33 | ManufacturingProcess11 |
| 7 | ManufacturingProcess39 | ManufacturingProcess12 | ManufacturingProcess28 |
| 8 | ManufacturingProcess13 | ManufacturingProcess06 | ManufacturingProcess17 |
| 9 | ManufacturingProcess29 | ManufacturingProcess37 | ManufacturingProcess12 |
| 10 | ManufacturingProcess31 | ManufacturingProcess34 | ManufacturingProcess13 |
nProcess <- sum(grepl("^ManufacturingProcess", topTree))
Answer: The top ten tree-based predictors contain 9 process predictors and 1 biological predictors. Process variables dominate by count. The tree-based list overlaps with ridge on 5 predictors and with radial SVM on 5 predictors. This is model importance, not a causal ranking; correlated predictors can share credit, and there are more process predictors in the original dataset.
Question: Does viewing the best single tree with yield distributions in its leaves give more insight?
The best single tree here is the tuned CART model, even if an
ensemble wins overall. The CART fit uses standardized predictors, so I
first show the training means and standard deviations for the split
variables. A split value z corresponds to approximately
mean + z * sd in original units. The medians, means, and
standard deviations come only from training observations.
plotData <- predict(cartFit$preProcess, newdata = xTrain)
plotData$Yield <- yTrain
splitVariables <- unique(as.character(cartFit$finalModel$frame$var))
splitVariables <- setdiff(splitVariables, "<leaf>")
if (length(splitVariables) > 0) {
knitr::kable(data.frame(
Predictor = splitVariables,
Training_center = unname(cartFit$preProcess$mean[splitVariables]),
Training_scale = unname(cartFit$preProcess$std[splitVariables])
), digits = 3, row.names = FALSE)
}
| Predictor | Training_center | Training_scale |
|---|---|---|
| ManufacturingProcess32 | 158.700 | 5.272 |
| BiologicalMaterial11 | 147.141 | 4.889 |
| ManufacturingProcess39 | 6.816 | 1.576 |
| ManufacturingProcess17 | 34.271 | 1.175 |
| BiologicalMaterial06 | 49.209 | 3.882 |
| ManufacturingProcess43 | 0.900 | 0.929 |
| ManufacturingProcess05 | 1000.730 | 27.894 |
| ManufacturingProcess09 | 45.768 | 1.480 |
# Supply the response with the same name used by caret's final rpart model.
partyData <- plotData
names(partyData)[names(partyData) == "Yield"] <- ".outcome"
plotTree <- cartFit$finalModel
plotTree$model <- model.frame(plotTree$terms, data = partyData,
na.action = na.pass)
cartParty <- partykit::as.party(plotTree)
plot(cartParty, gp = grid::gpar(fontsize = 8),
inner_panel = partykit::node_inner(cartParty, gp = grid::gpar(fontsize = 8)),
terminal_panel = partykit::node_boxplot(cartParty, id = FALSE,
gp = grid::gpar(fontsize = 7)),
main = "Tuned CART: yield distributions in terminal nodes")
# Route the imputed and scaled training observations to the fitted tree.
# 'where' corresponds to the training rows used in the final model.
leafNode <- as.integer(rownames(cartFit$finalModel$frame))[
cartFit$finalModel$where
]
leafSummary <- aggregate(yTrain, by = list(Node = leafNode),
FUN = function(z) c(n = length(z), mean = mean(z),
sd = sd(z), median = median(z)))
leafSummary <- data.frame(Node = leafSummary$Node, leafSummary$x)
knitr::kable(leafSummary, digits = 3, row.names = FALSE)
| Node | n | mean | sd | median |
|---|---|---|---|---|
| 8 | 25 | 38.245 | 0.794 | 38.05 |
| 9 | 11 | 39.348 | 0.740 | 39.58 |
| 10 | 21 | 39.457 | 0.682 | 39.53 |
| 11 | 13 | 40.893 | 1.077 | 40.87 |
| 13 | 11 | 41.970 | 1.327 | 42.15 |
| 15 | 8 | 43.629 | 1.197 | 43.41 |
| 24 | 21 | 39.807 | 1.015 | 39.79 |
| 25 | 8 | 41.653 | 0.926 | 41.66 |
| 28 | 15 | 41.469 | 0.889 | 41.49 |
| 29 | 7 | 42.884 | 0.586 | 42.69 |
Answer: The tree splits on ManufacturingProcess32, BiologicalMaterial11, ManufacturingProcess39, ManufacturingProcess17, BiologicalMaterial06, ManufacturingProcess43, ManufacturingProcess05, ManufacturingProcess09. Its 10 leaves show groups with different average yields, while the boxplots show the variation within those groups. A sequence of splits can reveal combinations of biological or process measurements associated with higher or lower yield. Wide or overlapping distributions show that the rules are not precise guarantees. I would investigate promising process settings in controlled trials, not change production based only on this observational tree.
In this fit, the first split on ManufacturingProcess32 separates a lower-average-yield branch from a higher-average-yield branch. Different biological measurements enter within those branches: BiologicalMaterial11 on the left and BiologicalMaterial06 on the right. This suggests that the relationship with raw-material measurements can depend on the process region, which a single importance rank does not show.
Kuhn, M., & Johnson, K. (2013). Applied Predictive Modeling. Springer. Chapter 8, Exercises 8.1, 8.2, 8.3, and 8.7, pp. 218–220.
The simulation and model calls follow the exercises and Chapter 8 companion R code. Tuning grids, seeds, comparisons, and explanatory text are adapted for this assignment.