A classifier that scores 100% on its own training data has told you nothing. This lesson predicts breast cancer subtype with a random forest and measures its accuracy honestly, with cross-validation, balanced accuracy and a test set opened once.
This lesson follows Clustering, PCA and heatmaps, where the same breast tumours were explored without their labels.
Training, testing and overfitting
Unsupervised methods showed that the basal tumours stand apart and the others form a continuum. Supervised learning asks a sharper question: given a tumour's expression of 200 genes, can a model predict its subtype? The model is a classifier; the subtype it predicts is the label; the genes are its features. The useful question is never how well it fits the tumours it learned from, but how well it will do on tumours it has never seen.
The gap between those two is overfitting: a flexible model can memorise the quirks of its training data, noise included, and look perfect while predicting new data poorly. With far more genes than samples, as in most omics data, this is the normal state of affairs, not a rare accident. The defence is to measure performance only on data the model did not learn from. This lesson does that three ways: the forest's own out-of-bag estimate, cross-validation, and a separate test set.
The model is a random forest. It grows hundreds of decision trees, each a series of yes/no questions such as "is KDM4B below 5.2?" that ends in a predicted subtype. Each tree is grown on a bootstrap sample of the tumours, drawn with replacement as in Resampling: bootstrap and permutation, and at each split it may only choose among a random handful of genes. The trees therefore differ, and the forest predicts by majority vote.
library(mixOmics) library(randomForest) data(breast.TCGA) x <- breast.TCGA$data.train$mrna subtype <- breast.TCGA$data.train$subtype x_test <- breast.TCGA$data.test$mrna subtype_test <- breast.TCGA$data.test$subtype set.seed(42) rf <- randomForest(x = x, y = subtype, ntree = 500, importance = TRUE) rf mean(predict(rf, x) == subtype) # predicting the training data mean(predict(rf) == subtype) # out-of-bag predictions
What this does
x_testandsubtype_testare 70 further tumours (21 basal, 14 HER2-enriched, 35 luminal A) with the same 200 genes. They are loaded now and not touched again until the end of the lesson.set.seed(42)fixes the random bootstrap samples and gene choices, so the forest is the same each run.randomForest(x = x, y = subtype, ...)fits 500 trees. Becausesubtypeis a factor, it builds a classifier.importance = TRUEstores the gene importances used later.predict(rf, x)predicts the training tumours with every tree, including the trees that learned from them: accuracy 1, a perfect and worthless score.predict(rf)with no new data returns the out-of-bag (OOB) predictions. Each bootstrap sample leaves out about a third of the tumours, so each tumour is predicted only by the trees that never saw it. OOB accuracy is 92.7%, an error rate of 7.33%.
The OOB confusion matrix already shows where the difficulty lies. Every luminal A tumour is right and almost every basal one, but 9 of the 30 HER2-enriched tumours are misclassified, 6 of them as luminal A. That matches the overlap you saw on the PCA plot in Clustering, PCA and heatmaps.
Cross-validation by hand
The OOB estimate is specific to random forests. k-fold cross-validation (CV) works for any model. Split the training tumours into k groups, the folds. Train on all but one fold, predict the fold left out, and repeat until every fold has been left out once. Each tumour then has exactly one prediction from a model that never saw it. Writing the loop yourself, with the tools from Vectors, functions and loops, makes clear what any CV package does.
make_folds <- function(y, k) {
folds <- integer(length(y))
for (lev in levels(y)) {
rows <- which(y == lev)
folds[rows] <- sample(rep(1:k, length.out = length(rows)))
}
folds
}
set.seed(1)
folds <- make_folds(subtype, k = 5)
table(fold = folds, subtype)
pred_cv <- factor(rep(NA, nrow(x)), levels = levels(subtype))
for (f in 1:5) {
held_out <- folds == f
fit <- randomForest(x[!held_out, ], subtype[!held_out], ntree = 500)
pred_cv[held_out] <- predict(fit, x[held_out, ])
}What this does
make_folds()assigns fold numbers within each subtype separately. These are stratified folds: each has the same mix of subtypes as the whole set, 9, 6 and 15. With purely random folds, one fold could by chance hold very few HER2-enriched tumours.rep(1:k, length.out = ...)repeats 1 to 5 until it covers the subtype's tumours, andsample()shuffles that list.pred_cvstarts as an empty factor with the subtype levels, ready to be filled one fold at a time.- Inside the loop,
held_outis TRUE for the fold's 30 tumours. The forest learns from the other 120,!held_out, and predicts the 30 it did not see.
Five or ten folds are the usual choices. More folds means each model trains on more data, closer to the final model, but costs more time. CV estimates vary with the random split; here the five folds' accuracies were 1.000, 0.867, 0.967, 0.967 and 0.967. With 30 tumours per fold, one tumour is 3.3 percentage points, so that spread is mostly chance. Repeating the whole CV with different seeds and averaging gives a steadier figure, as the project at the end of this module does.
Confusion matrices and balanced accuracy
A confusion matrix cross-tabulates predicted against true labels. The diagonal holds the correct predictions. From it come two summaries that answer different questions.
scores <- function(pred, truth) {
cm <- table(predicted = pred, true = truth)
recall <- diag(cm) / colSums(cm)
list(confusion = cm,
recall = round(recall, 3),
accuracy = round(sum(diag(cm)) / sum(cm), 3),
balanced_accuracy = round(mean(recall), 3))
}
scores(pred_cv, subtype)
# baseline: always predict the largest class
scores(factor(rep("LumA", nrow(x)), levels = levels(subtype)), subtype)[c("accuracy", "balanced_accuracy")]Worked example · accuracy and balanced accuracy
recall: Basal 44 ÷ 45 = 0.978 · Her2 24 ÷ 30 = 0.800 · LumA 75 ÷ 75 = 1.000
balanced accuracy: (0.978 + 0.800 + 1.000) ÷ 3 = 0.926
Step by step. Accuracy counts every tumour equally. The recall (also called sensitivity) of a class is the fraction of its true members that were found: read down each column of the matrix. Balanced accuracy averages the recalls, so each subtype counts equally, however many tumours it has.
What the answer means. Luminal A is half the data. A "model" that always answers LumA scores 0.5 accuracy without learning anything, but its balanced accuracy is 0.333, the chance level for three classes. Balanced accuracy exposes models that ignore small classes, and here it shows that HER2-enriched tumours, with recall 0.800, are the weak point.
The CV estimate, 95.3% accuracy, and the OOB estimate, 92.7%, differ by four tumours. Both are honest estimates, from different random splits, and the difference is within the variation you saw between folds. Report one and say which.
Which errors matter depends on the use. Calling a HER2-enriched tumour luminal A could mean, in a clinical setting, missing a patient who might benefit from HER2-targeted treatment. HER2 status is in practice measured directly, but asking what each kind of error costs is the right habit.
Inside the forest: importance and tuning
A random forest has few settings that matter. ntree is the number of trees; more is never worse, only slower, and the OOB error here settles by about 100 trees (0.060 at 50 and 100 trees, 0.073 at 500, a difference of two tumours). mtry is the number of genes each split may choose among; for classification the default is the square root of the number of genes, rounded down, which for 200 genes is 14.
imp <- importance(rf)
round(head(imp[order(imp[, "MeanDecreaseAccuracy"], decreasing = TRUE),
c("MeanDecreaseAccuracy", "MeanDecreaseGini")], 8), 2)
for (m in c(2, 14, 50, 200)) {
set.seed(42)
fit <- randomForest(x, subtype, mtry = m, ntree = 500)
cat("mtry =", m, " OOB error =", round(fit$err.rate[500, "OOB"], 3), "\n")
}What this does
- MeanDecreaseAccuracy shuffles one gene's values among the out-of-bag tumours and measures how much the forest's accuracy drops, scaled by its standard error. A gene the forest relies on causes a large drop.
- MeanDecreaseGini adds up how much the splits on that gene made the tree's groups purer. It is quicker but tends to favour genes with many distinct values.
- The loop refits the forest with four values of
mtryand prints the OOB error after 500 trees. The default, 14, did best here, but 0.073 against 0.080 is one tumour.
Several top genes, including ZNF552, C4orf34, LRIG1 and KDM4B, also had large loadings on PC1 in Clustering, PCA and heatmaps. Importance is a property of this model, not a biological ranking: when two genes carry the same information, the forest may share credit between them or favour one by chance. Treat the list as a guide to what the classifier uses, not as a list of the genes that define the subtypes.
Data leakage: choosing genes inside the loop
Data leakage means information from the data used to judge a model seeped into building it. The classic case in omics: select the genes that best separate the classes using all the samples, then cross-validate a classifier on those genes. The held-out fold helped choose the genes, so it is no longer unseen. The example below shows how large the effect can be, using pure noise, where the true accuracy is 50%.
set.seed(2026)
noise <- matrix(rnorm(100 * 2000), nrow = 100,
dimnames = list(NULL, paste0("g", 1:2000)))
label <- factor(rep(c("A", "B"), each = 50))
top_genes <- function(x, y, n) {
f_stat <- apply(x, 2, function(g) oneway.test(g ~ y, var.equal = TRUE)$statistic)
names(sort(f_stat, decreasing = TRUE))[1:n]
}
cv_accuracy <- function(x, y, folds, select_inside, n = 20) {
if (!select_inside) keep <- top_genes(x, y, n) # leaky: uses every sample
pred <- factor(rep(NA, length(y)), levels = levels(y))
for (f in unique(folds)) {
held_out <- folds == f
if (select_inside) keep <- top_genes(x[!held_out, ], y[!held_out], n)
fit <- randomForest(x[!held_out, keep], y[!held_out], ntree = 300)
pred[held_out] <- predict(fit, x[held_out, keep])
}
mean(pred == y)
}
set.seed(3)
noise_folds <- make_folds(label, k = 5)
set.seed(4); cv_accuracy(noise, label, noise_folds, select_inside = FALSE)
set.seed(4); cv_accuracy(noise, label, noise_folds, select_inside = TRUE)What this does
noiseis 100 "samples" by 2,000 "genes" of random numbers, andlabelsplits the samples into two groups of 50. No gene has anything to do with the labels.top_genes()ranks genes by the one-way ANOVA F statistic, which compares the spread between the group means with the spread within groups, one gene at a time, and keeps the topn.- With
select_inside = FALSE, genes are chosen once from all 100 samples before the loop. WithTRUE, they are chosen again inside each fold from the training samples only.
The leaky version reports 74% accuracy on data with no signal at all. Among 2,000 random genes, some separate these particular 100 samples well by chance; once chosen with every sample, they keep separating the held-out ones. Selecting inside the loop gives 37%. Over five repeats with different folds, the leaky estimate ranged from 0.74 to 0.79 (mean 0.764), and the honest one from 0.36 to 0.51 (mean 0.432). Honest estimates on noise scatter around and somewhat below 50%, a known quirk of cross-validation on small data with no signal; the point is that none of them claims a real classifier.
The rule is general: every step that learns from the labels belongs inside the loop. That includes choosing genes, tuning mtry, and choosing a cut-off. Steps that ignore the labels, such as normalising each sample on its own, are safe outside it.
Common mistakes
- Reporting accuracy on the training data, or quoting the best of many CV runs.
- Selecting genes, or tuning settings, on all samples before cross-validation.
- Reporting accuracy alone when classes are unbalanced.
- Looking at the test set, adjusting the model, and looking again. Once used to make a choice, it is no longer a test set.
- Letting the same patient appear in both training and test data, for example through replicate samples.
The test set, once
All the choices are made: a random forest, default settings, all 200 genes. Only now is the test set used, once, to report how the finished model does on tumours it has never met.
pred_test <- predict(rf, x_test) scores(pred_test, subtype_test)
The forest classifies 67 of the 70 test tumours correctly, a balanced accuracy of 0.937, in line with the CV estimate of 0.926. Agreement like this is what honest estimation buys: the number you reported before seeing the test set turned out to be a fair guide. With 70 tumours each error is 1.4 percentage points, so the test result has its own uncertainty: binom.test(67, 70) gives a 95% confidence interval for the accuracy of 88.0% to 99.1%.
The test set here also comes from TCGA, processed the same way. A model that works on new tumours from the same study may still do worse in another hospital's data, measured on another platform. That is external validation, the strongest test of all, and what a clinical classifier ultimately needs.
Go deeper: nested cross-validation
If you use CV to choose a setting, such as how many genes to keep, the best CV score is itself optimistic: you picked the luckiest of several. Nested cross-validation wraps the whole procedure, choice included, in an outer CV loop. The inner loop chooses the setting from the outer training folds only, and the outer loop estimates how well the whole procedure, choice and all, performs.
With a separate test set, as here, the simpler route works: choose with CV on the training data, then report the test set. Varma & Simon 2006 (BMC Bioinformatics) show the size of the bias when the choice is left outside. Packages such as caret and tidymodels automate both designs, but the loop you wrote above is the same idea.
Random forests are described in Breiman 2001, "Random forests" (Machine Learning), and the R package in Liaw & Wiener 2002, "Classification and regression by randomForest" (R News). Ambroise & McLachlan 2002, "Selection bias in gene extraction on the basis of microarray gene-expression data" (PNAS), showed that selecting genes outside cross-validation gives near-perfect accuracy even on random data. Cite randomForest with citation("randomForest") and give its version.
Key point
A model's accuracy means something only on data it did not learn from, and only if nothing about those data helped build it. Use OOB or cross-validation to choose, keep every label-driven step inside the loop, report balanced accuracy when classes differ in size, and open the test set once.
Further reading · Module 5Ambroise & McLachlan 2002: how gene selection outside cross-validation creates accuracy from nothing. · All reading for this course
Check your understanding
1. What is the out-of-bag (OOB) prediction for a tumour in a random forest?
2. Half the tumours are luminal A. A model always predicting luminal A has 0.5 accuracy. What is its balanced accuracy with three subtypes?
3. Why must gene selection be repeated inside each cross-validation fold?