Skip to main content

Problem Set 9: Random Forests & Neural Networks

PLS 206 — Applied Multivariate Modeling

Author

Grey Monroe

Published

January 1, 2026

Note

Due: Monday, November 30, 1:10 PM (start of class) — submitted through Canvas.

Everything here uses Monday’s lecture on decision trees, random forests and neural networks (there is no Wednesday lecture this week). Monday’s live script, Week9_live_1_forests.R, has working code for every step, and the slides show what each output means.

Stuck? Every question has a hint. Open it: most hints contain a code skeleton where you only fill in the blanks (___) and say what your output should look like.


Submission Instructions

Upload two files to Canvas:

  1. Written answers — a .pdf document with your written responses, interpretations, and figures.
  2. R script — a .R file with all the code you used to produce your answers.

List the first and last names of any collaborators in both files.

Naming convention: HW9emailID.R (code) and HW9emailID.pdf (written answers), where emailID is the part of your UC Davis email before the @.

Example: Grey Monroe would submit HW9gmonroe.R and HW9gmonroe.pdf.

Feel free to use Google, StackOverflow, and other resources if you are stuck with code, and post questions on Slack if anything is unclear.


The data

Pistachio. The pistachio orchard from Problem Set 3: 300 trees of three genotypes (chaparillo, kerman, t41), each scored for disease (1 = diseased, 0 = healthy), with canopy greenness (NDVI) measured from the air in March, June and August. In PS3 you predicted disease with logistic regression. This week we ask whether trees, forests and neural networks do any better, and what they can tell us.

Train and test. Every model is fit to 200 trees and scored on the other 100, which it never sees while it is being fit. Accuracy on the 100 test trees is the honest score. Run this block once at the top of your script, exactly as written, so your split matches everyone else’s.

library(ggplot2)
library(rpart)          # single decision trees
library(rpart.plot)     # draws them
library(randomForest)   # random forests
library(neuralnet)      # neural networks
# install.packages(c("rpart.plot", "randomForest", "neuralnet"))

pistachio <- read.csv("https://greymonroe.github.io/PLS_206/data/pistachio.csv")
pistachio$disease  <- factor(pistachio$disease)    # a class (0/1), not a number
pistachio$genotype <- factor(pistachio$genotype)

set.seed(206)
test_id <- sample(nrow(pistachio), 100)
train <- pistachio[-test_id, ]                     # 200 trees to fit models
test  <- pistachio[test_id, ]                      # 100 trees to score them

f <- disease ~ genotype + NDVI_march + NDVI_june + NDVI_august

accuracy <- function(predicted, observed) mean(as.character(predicted) == as.character(observed))

accuracy() returns the share of trees whose predicted class matches the truth, between 0 and 1. For reference, 56 of the 100 test trees are diseased, so a “model” that calls every tree diseased already scores 0.56.

Seeds. Random forests and neural networks start from random numbers. Put set.seed(206) right before every randomForest() and neuralnet() call and your numbers will match the key.


Part 1: Trees and Forests

Q1. Fit a single decision tree of f to the training trees with rpart(). Plot it. In one sentence, read the first split: which variable, which cut-off, and what the tree predicts on each side. Then report the tree’s accuracy on the training trees and on the test trees.

tree <- rpart(f, data = train)
rpart.plot(tree)                                       # same as in lecture
accuracy(predict(tree, train, type = "class"), train$disease)
accuracy(predict(tree, ___,   type = "class"), ___$disease)

The top of the plot is the first question the tree asks; if the condition printed there is true, go left (the “yes” side). Each box shows the predicted class (0 or 1), the share of diseased trees in that box, and the % of all trees that landed there. print(tree) shows the same splits as text. Live script section 1 does exactly this for the cattle; the slides “Keep splitting: the tree” show how to read the boxes.

Q2. Fit a random forest of f to the training trees (ntree = 500). Report three accuracies: (a) on the training trees with predict(rf, train), (b) the out-of-bag (OOB) accuracy, 1 − the OOB error printed by rf, and (c) on the test trees. One of the three is far too optimistic. Which, and why? Which of the other two would you trust if you had no test set?

set.seed(206)
rf <- randomForest(f, data = train, ntree = 500, importance = TRUE)
rf                                              # "OOB estimate of error rate"
accuracy(predict(rf, train), train$disease)     # (a) every tree votes, including trees that saw this row
accuracy(predict(rf), train$disease)            # (b) OOB: each row is predicted only by trees that never saw it
accuracy(predict(rf, ___), ___$disease)         # (c) test trees

Each tree in the forest is grown on a bootstrap sample of the 200 trees and grown deep enough to fit its own sample almost perfectly. About a third of the rows are left out of each bootstrap sample: those are that tree’s “out of bag” rows. So: which of (a), (b), (c) lets trees score rows they were grown on? Expect one accuracy near 1 and two much lower ones that roughly agree. Live script section 2; slides “Free test data: out-of-bag”.

Q3. How many trees does the forest need? Plot the OOB error against the number of trees. Report the OOB error with 1, 10, 50 and 500 trees, and say roughly where adding more trees stops helping.

plot(rf)                                       # black line = overall OOB error
rf$err.rate[c(1, 10, 50, 500), "OOB"]          # row k = the forest with k trees

More trees never make a random forest overfit; they only cost computing time. The curve tells you when the extra time stops buying anything. plot(rf) for a classification forest also draws one coloured line per class; the black line is the overall OOB error, the one to report. Expect a jumpy start and a flat line later; compare the slide “How many trees? Every forest in this lecture”.

Q4. mtry is the number of predictors a forest is allowed to choose from at each split (the default for classification is the square root of the number of predictors, rounded down: 2 here). Refit the forest with mtry = 1, 2, 3 and 4 and report the OOB error for each. Does mtry matter much on these data? What is special about mtry = 4?

oob <- sapply(1:4, function(m) {
  set.seed(206)
  fit <- randomForest(f, data = train, ntree = 500, mtry = m)
  fit$err.rate[500, "OOB"]
})
oob

We have 4 predictors. With mtry = 4 every split may consider every predictor, so the only randomness left is the bootstrap sample. That method has its own name (see the slides “Many trees, averaged” and “The ‘random’ in random forest”). Remember that mtry is a fresh random draw at every split, not one subset per tree. Differences of a percentage point or so between settings are noise: 200 training trees means one tree is half a percentage point.

Q5. Which predictors does the forest lean on? Show the importance plot (varImpPlot()) and name the most important predictor. Then draw the partial dependence plot for that predictor (for the diseased class) and describe the shape of its effect in one sentence of plant biology.

varImpPlot(rf)
importance(rf)
partialPlot(rf, pred.data = train, x.var = "___", which.class = "1",
            xlab = "NDVI", main = "Partial dependence: diseased")

varImpPlot(rf) draws two panels. Use the left one, MeanDecreaseAccuracy: the shuffle test from lecture, how much worse the OOB predictions get when that predictor’s values are shuffled. The right one, MeanDecreaseGini, is split credit; lecture showed why it is a poor guide for inference. x.var takes the predictor’s name in quotes, and which.class = "1" asks for the diseased class. The partial dependence y axis is on a log-odds-like scale (randomForest halves the logit for two classes): higher means a higher chance of disease, holding the other predictors at their observed values. Look at where the curve is flat and where it drops.

Q6. The three NDVI months are strongly correlated. Report their correlation matrix. Then fit a second forest with only genotype + NDVI_june and compare June’s importance (mean decrease in accuracy) in the two forests. Explain the difference. What does this mean for reading importance scores when predictors are correlated?

round(cor(train[, c("NDVI_march", "NDVI_june", "NDVI_august")]), 2)
set.seed(206)
rf_june <- randomForest(disease ~ genotype + ___, data = train, ntree = 500, importance = TRUE)
importance(rf_june)[, "MeanDecreaseAccuracy"]
importance(rf)[, "MeanDecreaseAccuracy"]

Shuffling June destroys June’s information, but if March and August carry much of the same information, the forest loses less. This is the NDVI/EVI example from the slides (“Correlated predictors share the credit”). You met the same problem with regression coefficients in Week 5 (collinearity).


Part 2: Neural Networks

Q7. Fit a neural network of the same model with one hidden layer of 2 nodes, from 5 random starts. neuralnet() needs numbers, not factors, and works best when the predictors are on the same scale, so the block below builds the model matrix and scales the NDVI columns with the training means and SDs. Report the error of each of the 5 starts. Why do they differ? Plot the best one and report its test accuracy.

nn_data <- function(d) {                       # genotype -> 0/1 columns, disease -> 0/1 number
  mm <- model.matrix(~ genotype + NDVI_march + NDVI_june + NDVI_august, d)[, -1]
  data.frame(mm, disease = as.numeric(as.character(d$disease)))
}
ndvi <- c("NDVI_march", "NDVI_june", "NDVI_august")
train_nn <- nn_data(train); test_nn <- nn_data(test)
mu <- colMeans(train_nn[ndvi]); s <- apply(train_nn[ndvi], 2, sd)
train_nn[ndvi] <- scale(train_nn[ndvi], mu, s)   # scale both with the TRAINING means and SDs
test_nn[ndvi]  <- scale(test_nn[ndvi],  mu, s)

nn_formula <- disease ~ genotypekerman + genotypet41 + NDVI_march + NDVI_june + NDVI_august
set.seed(206)
nn <- neuralnet(nn_formula, data = train_nn, hidden = 2, rep = 5,
                linear.output = FALSE, stepmax = 1e5)
nn$result.matrix["error", ]                    # one error per start
best <- which.min(nn$result.matrix["error", ])
plot(nn, rep = best)
p_nn <- predict(nn, test_nn, rep = best)[, 1]   # predicted probability of disease
accuracy(as.numeric(p_nn > 0.5), test$disease)

Each start draws its weights and biases at random and then walks downhill on the error. Does that remind you of nstart in k-means? (Slides “How a network learns: walk downhill” and “Random starts: keep the best”.) linear.output = FALSE passes the output through the logistic curve, so predictions are probabilities between 0 and 1. In plot(nn, rep = best) every line is one fitted weight; the blue “1” nodes are the constant inputs whose weights are the biases. If R warns that the algorithm did not converge, raise stepmax (for example to 1e6).

Q8. Make the network bigger: one hidden layer of 5 nodes (hidden = 5), otherwise the same. Report the training and test accuracy of the best start for both networks (2 and 5 nodes). Did the extra nodes help? Explain what you see in terms of overfitting.

set.seed(206)
nn5 <- neuralnet(nn_formula, data = train_nn, hidden = ___, rep = 5,
                 linear.output = FALSE, stepmax = 1e5)
best5 <- which.min(nn5$result.matrix["error", ])
accuracy(as.numeric(predict(nn5, train_nn, rep = best5)[, 1] > 0.5), train$disease)
accuracy(as.numeric(predict(nn5, test_nn,  rep = best5)[, 1] > 0.5), test$disease)
# ...and the same two lines for nn (rep = best)

Count the numbers each network fits: with 5 inputs, 2 hidden nodes is 5×2 + 2 weights plus 3 biases = 15; work out the count for 5 hidden nodes the same way (slides “Our network, fitted”). A model can always fit its own training data better by adding parameters. The question is whether that improvement shows up on trees it has never seen.


Part 3: Which Model?

Q9. Fit a logistic regression of f to the training trees (as in PS3) and report its test accuracy. Make a small table of test accuracy for the single tree (Q1), the random forest (Q2), the 2-node network (Q7) and the logistic regression. With 100 test trees, one tree is one percentage point: are any of the differences big enough to matter? Which model would you report in a paper, and why? Give one thing the logistic regression tells you that the forest and the network cannot.

g <- glm(f, family = binomial, data = train)
summary(g)
p_glm <- predict(g, test, type = "response")   # probability of disease
accuracy(as.numeric(p_glm > ___), test$disease)

Use 0.5 as the cut-off: above it, call the tree diseased. Think about how many parameters each model has, whether you can write it down, and what a reviewer would ask about the effect of NDVI on disease (the slide “Which model?” compares them). Look at the June coefficient in summary(g): Q6 is happening here too.