Build a pipeline that predicts breast cancer subtype from a small gene panel, choose its size by cross-validation with selection inside every fold, and report a test set that played no part in any choice.
This project follows Survival analysis and brings together the whole of this module, above all Random forests and cross-validation.
Research question
How well can a small panel of genes predict a breast tumour's molecular subtype, and how sure can you be of that number before anyone else checks it?
The second half of the question is the real subject. Anyone can report a high accuracy; the skill is reporting one that holds up on new tumours. You will build a pipeline, a fixed sequence of steps from raw expression to predicted subtype, choose its one setting by cross-validation, and only then open the test set. The data are the TCGA breast tumours from Clustering, PCA and heatmaps: 150 training tumours and 70 test tumours, 200 genes each.
How to approach this
- Write one script, as in A reproducible workflow, that runs from
data(breast.TCGA)to the final table, with everyset.seed()in place, so anyone can rerun it and get your numbers. - Decide before you look. Write down now the sizes of gene panel you will compare, the measure you will use to choose (balanced accuracy, since the subtypes differ in size), and your rule for breaking near-ties. Then follow it.
- Treat the test set as sealed. Load it in task 1 to check its shape, then do not use it again until task 4. If you are tempted to peek "just to see", don't: any choice made after looking turns it into training data.
- Expect some slowness. Task 2 fits 75 random forests and ranks 200 genes 75 times; it takes a few minutes. That is normal for honest validation.
The pipeline has two steps. First, rank the genes by how well they separate the three subtypes, using a one-way ANOVA F statistic for each gene, and keep the top n. Second, fit a random forest on those n genes. The key point is that both steps learn from the labels, so both must be redone inside every cross-validation fold. Writing the pipeline as a pair of functions makes that easy to get right: whatever data you hand them, they never see anything else.
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]
}
fit_pipeline <- function(x, y, n) {
keep <- top_genes(x, y, n)
list(genes = keep, forest = randomForest(x[, keep], y, ntree = 500))
}
predict_pipeline <- function(model, newx) predict(model$forest, newx[, model$genes])fit_pipeline() returns a list holding the chosen genes and the fitted forest, so predict_pipeline() can pick the same genes out of any new data. Reuse make_folds() and scores() from Random forests and cross-validation. The checkpoints give the values from one run of the script; small differences in the third decimal place can come from a different seed or package version, but large ones usually mean a step has slipped outside the loop.
Check the data and set a baseline
Clustering, PCA and heatmaps and Random forests and cross-validation
- Load the training and test sets and check their dimensions, subtype counts, missing values and gene names.
- Check that no tumour appears in both sets, and compare the gene means of the two sets.
- Work out the accuracy and balanced accuracy of always predicting the largest class on the test set.
Hint. identical(colnames(x), colnames(x_test)) confirms the genes are the same and in the same order. intersect(rownames(x), rownames(x_test)) lists any tumour present in both. colMeans(x_test) - colMeans(x) gives each gene's shift between the sets; a summary of it is enough. A model trained on one distribution and tested on a very different one can fail for reasons that have nothing to do with biology.
Checkpoint: 150 and 70 tumours, 200 identical genes, no missing values and no shared tumours. The test set is 30% basal, 20% HER2-enriched and 50% luminal A, like the training set. Gene means differ little between the sets (median shift −0.02, range −0.44 to 1.01). Always predicting LumA scores 0.5 accuracy and 0.333 balanced accuracy: the bar any model must clear.
Choose the panel size by cross-validation
Random forests and cross-validation
- For panel sizes of 5, 10, 25, 50 and 200 genes, run 5-fold stratified cross-validation of the whole pipeline on the training set.
- Repeat with three different fold splits and report the mean and standard deviation of the balanced accuracy for each size.
Hint. Write a function cv_one(n, folds) that fills an empty factor of predictions fold by fold: inside the loop, call fit_pipeline() on the training folds and predict_pipeline() on the held-out fold. Then sapply() it over the sizes, and wrap that in another sapply() over three calls to make_folds(). Set one seed, set.seed(2026), before the repeats. With 200 genes, the selection step keeps every gene, so that row is the plain forest from Random forests and cross-validation.
Checkpoint: mean balanced accuracy of about 0.833 for 5 genes, 0.866 for 10, 0.906 for 25, 0.900 for 50 and 0.910 for 200, with standard deviations between repeats of 0.005 to 0.022. Accuracy rises up to about 25 genes and then flattens.
Pick a size, and measure the leak
Random forests and cross-validation
- Apply the rule you wrote down to choose a panel size.
- Then rerun task 2 the leaky way, choosing the genes once from all 150 training tumours before the loop, and compare.
Hint. A common rule is to take the smallest panel whose score is within about one standard deviation of the best, because a smaller panel is cheaper to measure and easier to interpret. For the leaky version, copy cv_one(), move the call to top_genes() above the loop, give it x and subtype, and fit the forest on those genes inside the loop. Use the same seed so the folds match.
Checkpoint: 25 genes (0.906) is within the noise of the best score (0.910 with all 200), so the rule picks 25. The leaky estimates are 0.849, 0.877, 0.902, 0.909 and 0.888: here, unlike the noise example, the leak barely shows, because the subtype signal is strong and the differences are within the variation between repeats.
Fit the final model and open the test set
Random forests and cross-validation
- Fit the pipeline with your chosen size on all 150 training tumours.
- Predict the 70 test tumours once, and report the confusion matrix, recall per subtype, accuracy and balanced accuracy.
- For the misclassified tumours, print the forest's vote shares with
type = "prob".
Hint. set.seed(7) before fit_pipeline(x, subtype, 25) fixes the forest. Selection now uses all 150 training tumours, which is correct: the test set is the held-out data. predict(final$forest, x_test[, final$genes], type = "prob") gives, for each tumour, the fraction of trees voting for each subtype.
Checkpoint: 65 of 70 correct: accuracy 0.929, balanced accuracy 0.897, against a CV estimate of 0.906. Recall is 0.905 for basal, 0.786 for HER2-enriched and 1.000 for luminal A. All five errors involve HER2-enriched tumours, either predicted as one or mistaken for another subtype, and several were close votes: one basal tumour received 0.46 of the votes for basal and 0.46 for HER2-enriched.
Which genes, and a short report
Clustering, PCA and heatmaps and A reproducible workflow
- List the final panel's genes and their importance, and check how stable the selection is across cross-validation folds.
- Write a methods paragraph and a results paragraph, with two limitations.
Hint. For stability, run top_genes() on the training part of each of five folds and count, with table(unlist(...)), how often each gene is chosen. Genes chosen in every fold are robust; genes that come and go are near the cut-off. Plot or tabulate the top gene by subtype to see what the forest is using. The methods should name the data, every step of the pipeline in order, the CV design, the selection rule, the seeds and the package versions.
Checkpoint: 38 different genes are chosen across the five folds and 17 of them in every fold; all 17 are in the final panel. The top genes by Gini importance include KDM4B, ZNF552, C4orf34 and CCNA2. ZNF552 has median expression 3.54 in basal, 5.35 in HER2-enriched and 6.44 in luminal A tumours: the same ordering as PC1. Your limitations mention that the 200 genes were pre-filtered by the data's authors and that both sets come from one study.
What the project shows
If your numbers match the checkpoints, you have done what many published classifiers skip: chosen the model with cross-validation alone, then reported a test set that played no part in any choice. The CV estimate (0.906) and the test result (0.897) agree to within one tumour's worth, which is the sign of an honest process. A leaky one typically gives a CV score far above the test score.
The test set will tempt you. The plain forest on all 200 genes from Random forests and cross-validation scored 0.937 on the same test set, higher than the 25-gene panel. It would be wrong to switch now. Cross-validation could not tell the two apart (0.910 against 0.906), the gap on the test set is two tumours, and choosing the winner after seeing the test results would make 0.937 an optimistic number again. Report the pipeline you chose, and mention the comparison as what it is: a second look, not a basis for the choice.
Task 3 deserves a careful reading. On the real data the leaky and honest estimates hardly differed, while on noise in Random forests and cross-validation leakage turned chance into 76%. Leakage does the most harm exactly where it is hardest to spot: weak signals, many genes and few samples, the usual situation in a new omics study. The habit of keeping every label-driven step inside the loop costs a few minutes here and protects you there. One leak remains outside your control: the package authors chose these 200 genes from a larger set, and if they used the subtypes to do so, every estimate in this project is a little optimistic. The help page does not say, which is why it belongs in your limitations.
The errors also tell a coherent story. Every misclassified tumour involves the HER2-enriched subtype, the one that sat between the others on the PCA plot. Some of these tumours may be genuinely intermediate rather than mislabelled; a classifier's vote shares, like the 0.46 against 0.46 above, are a more honest output for such tumours than a single forced label. This data set has no follow-up times, so a survival analysis does not fit here; with clinical data, the next question would be whether predicted subtype relates to outcome, using the Kaplan–Meier and Cox methods from Survival analysis.
Where this leads next
Every tumour in this module was measured as a whole: a bulk sample, averaging millions of cells of many kinds. Module 6, Single-cell with Seurat, measures cells one at a time. The tools you built here come straight back. PCA reduces thousands of genes to a few dozen components; clustering groups cells, not tumours, into putative cell types; and the questions about whether clusters are real, how many there are and which genes define them return at a much larger scale, with tens of thousands of cells instead of 150 tumours.
Go deeper: reporting a prediction model
Clinical prediction models have a reporting guideline, TRIPOD (Collins et al. 2015), recently extended as TRIPOD+AI for machine learning methods. It asks, among other things, for the source of the data, how the predictors were chosen, how missing data were handled, how performance was estimated and on what data, and how the model can be obtained.
Even outside clinical work, its checklist is a useful test of your methods paragraph: could a reader repeat each step, and could they tell which numbers came from data the model never saw?
Take it further
The training set also holds miRNA and protein data for the same tumours, and the test set holds miRNA. Repeat the project with the 184 miRNAs, then with mRNA and miRNA together, and compare the CV estimates before you look at the test results. Does adding a second kind of measurement help, or are the subtypes already captured by the mRNAs?
You could also swap the classifier, for example to a penalised logistic regression with the glmnet package, keeping the folds, the selection rule and the sealed test set exactly as they are. Because the pipeline is a pair of functions, only fit_pipeline() and predict_pipeline() need to change.
Further reading · Module 5Varma & Simon 2006: why choosing settings by cross-validation needs its own honest check. · All reading for this course
Check your understanding
1. Cross-validation gives 0.906 for a 25-gene panel and 0.910 for all 200 genes, with variation of about 0.01 between repeats. Which choice follows a rule of preferring the smaller panel within the noise?
2. After testing, the 200-gene forest scores higher on the test set than your chosen 25-gene panel. What should you do?
3. In this project the leaky and honest cross-validation estimates were very similar. What is the right conclusion?