Sub topic 2
Why diversity matters more than count
This chapter assumes you know k-fold cross-validation, the bias-variance trade-off, and basic scikit-learn usage. It explains why the models you combine should make different mistakes. Adding more copies of the same kind of model helps very little.
The effect of correlated errors
Suppose you average the predictions of n models. Each model's prediction has variance σ², and every pair of models has error correlation ρ. The variance of the average is:
σ² × (ρ + (1 − ρ) / n)
The term (1 − ρ) / n shrinks as you add models. The term ρ does not. It sets a floor that no number of extra models can lower. The table uses σ² = 1.
| Error correlation ρ | n = 1 | n = 5 | n = 50 |
|---|---|---|---|
| 0.9 | 1.000 | 0.920 | 0.902 |
| 0.6 | 1.000 | 0.680 | 0.608 |
| 0.3 | 1.000 | 0.440 | 0.314 |
Going from 5 to 50 highly correlated models (ρ = 0.9) lowers the variance by about 0.018. Replacing them with 5 models at ρ = 0.3 lowers it by 0.48. The size of the ensemble matters much less than how correlated its members are.
This is a simplified model. It describes averaging of variance. It does not say how a trained meta-learner will weight the models, and it assumes each model has similar quality. The lesson still holds: errors that coincide cannot cancel each other.
What counts as a different model
Diversity means the models disagree on some examples, and the disagreements are not random noise. A model that is wrong in different places than the others is useful, as long as it is also reasonably accurate. There are several ways to get this.
- Different algorithm families. Trees, linear models, nearest neighbors, and neural networks have different inductive biases. A random forest splits on axis-aligned thresholds. Logistic regression draws one linear boundary. K-nearest neighbors relies on local distance.
- Different feature views. One model gets raw features. Another gets scaled or binned features, polynomial terms, or a feature subset. The scaling step in a k-nearest neighbors pipeline already changes what the model sees.
- Different hyperparameters. A shallow tree and a deep tree behave differently. This source is cheap, but it usually gives less diversity than switching algorithms.
- Different training samples. Bagging trains each model on a bootstrap sample. This is how random forests get their diversity, and it is why they work well inside a single algorithm family.
- Different seeds. Changing only the random seed gives the least diversity, particularly for deterministic or low-variance learners. It helps mostly for high-variance models such as neural networks.
The ordering in the diagram is a rule of thumb, not a law. A random forest and an extremely randomized trees model are different algorithms, but both are tree ensembles on the same features. Their errors are often strongly correlated. A random forest and a scaled logistic regression usually differ more.
Measuring diversity
You can measure diversity before building any stack. Collect out-of-fold predictions from each candidate model, then compare where they err. Out-of-fold means each prediction comes from a model that did not train on that row. The next chapters cover that technique in detail. Here it is just a way to get honest predictions from the training data without touching the test set.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_predict, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=2000, n_features=20, n_informative=8, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
models = {
"rf": RandomForestClassifier(n_estimators=200, random_state=0),
"et": ExtraTreesClassifier(n_estimators=200, random_state=0),
"logreg": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
"knn": make_pipeline(StandardScaler(), KNeighborsClassifier()),
}
names = list(models)
error_flags = []
for name in names:
proba = cross_val_predict(models[name], X_train, y_train, cv=5, method="predict_proba")[:, 1]
wrong = ((proba > 0.5).astype(int) != y_train).astype(float)
error_flags.append(wrong)
print(f"{name:7s} out-of-fold error rate: {wrong.mean():.3f}")
corr = np.corrcoef(np.array(error_flags))
print("\nError correlation (rows and columns:", names, ")")
print(np.round(corr, 2))The script scores each model with 5-fold cross-validation on the training set only. It builds a 0/1 vector that marks the rows each model got wrong, then correlates those vectors. The test set stays untouched.
Read the matrix like this:
- Values near 1 mean two models fail on the same rows. Keeping both adds little.
- Lower values mean the models fail on different rows. Their combination has room to improve.
- Compare the pair
rfandetwith the pairrfandlogreg. You should expect the two tree ensembles to be more correlated with each other than either is with the linear model or the nearest neighbor model. Check this on your own run, because the exact numbers depend on the data.
Accuracy still matters
Diversity does not excuse a bad model. A model that is much weaker than the others can be completely uncorrelated with them and still add nothing, because its predictions are mostly noise. The aim is models that are individually good and different from each other.
Two practical rules follow:
- Drop candidates that are clearly worse than your best model, unless they add a distinct signal. A model at random-guess accuracy is not diverse in a useful way.
- Between two models with similar accuracy, prefer the one with lower error correlation to the models you already have.
Diversity in the stack itself
A meta-learner trained on near-duplicate inputs also has a numerical problem. If two meta-features are almost identical, a linear meta-learner can assign large opposite weights to them, and its coefficients become unstable. Regularization helps with this, and a later chapter covers it. Diversity reduces the problem at the source, because fewer redundant models means fewer redundant meta-features.
A small set of well-chosen models usually beats a large pool. Three to six models from different families is a common starting point. Adding a seventh model that is a variant of one already present rarely pays for its training time.
Summary of the decision rule
When you consider adding a base learner to an ensemble, ask three questions:
- Is it accurate enough on its own? Check its out-of-fold score.
- Does it err on different rows than the models already included? Check the error correlation.
- Is the extra cost of training and serving it acceptable?
If the answer to the first two is yes, the model is a good candidate. If its errors are highly correlated with an existing member, you can usually skip it.
Exercise
You have five models with a pairwise error correlation of 0.8. A colleague proposes adding 45 more models of the same kind, trained with different random seeds. Using the variance formula σ² × (ρ + (1 − ρ) / n) with σ² = 1 and ρ = 0.8, how much does the variance of the averaged prediction drop, and what would you try instead?
Show answer
With n = 5 the variance is 0.8 + 0.2 / 5 = 0.84. With n = 50 it is 0.8 + 0.2 / 50 = 0.804. The drop is only 0.036, because the floor of 0.8 set by the correlation cannot be lowered by adding more copies. A better use of effort is to add a few models from different families, such as a linear model or a nearest neighbor model on scaled features, and to check their out-of-fold error correlation with the existing members.
Exercise
In the diversity-measuring script, why is the error correlation computed from out-of-fold predictions on the training set instead of predictions on the test set?
Show answer
Selecting or discarding models based on test-set errors makes the test set part of model selection, so the final test score becomes optimistically biased. Out-of-fold predictions give honest error estimates using only the training data, and the test set stays reserved for the final evaluation.