What you will be able to do
- Explain how adding model complexity lowers bias and raises variance, using decision trees and k-nearest neighbors as examples
- Tell underfitting from overfitting by comparing training error with validation error
- Pick the setting that reduces or adds complexity for a given model: tree depth, leaf size, regularization strength, neighbor count
- Read a depth sweep against a validation metric and choose the level of complexity that generalizes best
Key concept
Bias-variance tradeoff — A model's error on unseen data comes from bias (assumptions too simple to capture the real pattern), variance (sensitivity to the particular training sample) and noise that no model can remove. Adding complexity lowers bias but raises variance, so the best model sits at the level of complexity where validation error is lowest, not where training error is lowest.
1.Model complexity sets the balance between bias and variance
Every supervised model makes two kinds of avoidable error, and model complexity trades one for the other. Bias is error from assumptions that are too rigid. A straight line fitted to a curved relationship misses it the same way on every sample you could draw. Variance is error from being too sensitive to the training sample itself. A very flexible model bends to fit the quirks and noise of the rows it saw, so retraining it on a slightly different sample gives noticeably different predictions. A third part, irreducible noise in the target, stays no matter what model you choose. Expected error on new data is roughly bias squared plus variance plus that noise.
Complexity is how much freedom the model has to fit the data. Raising it lowers bias, because the model can represent more shapes, and raises variance, because it can also represent the noise. A decision tree with no depth limit keeps splitting until its leaves are nearly pure. It can reach close to 100% training accuracy by memorizing individual rows, and that memorization does not carry over to new data. A tree limited to two levels can only draw a few coarse boundaries. It barely changes when the data changes, but it may be too blunt to capture the signal.
In k-nearest neighbors, complexity goes the opposite way from what the number suggests. With n_neighbors=1, each prediction copies the label of the single closest training point. The decision boundary wraps around every individual training row, so training accuracy is perfect and removing one point near the boundary can flip predictions in that region. That is maximum complexity and high variance. Raising n_neighbors averages over more points. The boundary smooths, sensitivity to any single row falls, and bias rises. If k approaches the size of the dataset, every prediction becomes the majority class.
More complexity is therefore not automatically better. In one sweep of tree depth for a classifier, the runs with shallower trees scored the higher AUC: lower values for max_depth gave higher values for the validation metric. Deeper trees fit the training data better and generalized worse.
Checkpoint 1 of 7· Check yourself
A k-nearest neighbors classifier with n_neighbors=1 scores 100% on its training rows but much lower on validation data. Which diagnosis and fix is correct?
With one neighbor, each prediction copies a single training label, so the model memorizes the training set: maximum complexity and high variance. Raising n_neighbors averages over more points, which lowers variance and raises bias.
“a model that would just repeat the labels of the samples that it has just seen would have a perfect score”Source: scikit-learn.org
Checkpoint 2 of 7· Exam question
A data scientist sets n_neighbors=1 for a k-nearest neighbors classifier and observes that predictions change drastically when a single training point near the decision boundary is removed. Which statement best explains this behavior and how to address it?
Correct answer: A — With n_neighbors=1, model complexity is effectively maximized because each prediction depends on one nearby point, producing high variance; increasing n_neighbors trades some variance for bias.
- A. A single-neighbor classifier draws a highly irregular decision boundary that hugs each individual training point, so removing or adding one point can flip nearby predictions — the hallmark of high variance. Increasing
n_neighborsaverages over more points, smoothing the boundary and accepting some bias in exchange for lower variance. - B. With only one neighbor there is no averaging happening at all, so this describes the opposite regime from what
n_neighbors=1actually produces. Decreasingn_neighborsbelow 1 is not possible and would not smooth anything even if it were. - C. Feature scaling affects which points are considered nearest, but it does not remove the fundamental instability caused by basing every prediction on a single neighbor. Even on perfectly scaled features, a one-neighbor model remains maximally sensitive to individual training points.
- D. k-nearest neighbors is a classic example of a non-parametric method, and
n_neighborsis precisely the hyperparameter that controls its effective complexity. The observed instability is expected behavior for this setting, not evidence of a pipeline defect.
2.Diagnosing underfitting and overfitting from training and validation error
You diagnose the bias-variance balance from two numbers: the score on the training data and the score on held-out validation data. Training error alone can't do it, because a model can always lower its training error by memorizing. A model that scores well on the rows it learned from and poorly on unseen rows is overfitting. Keep the validation data separate from the final test set, which stays untouched until the end.
A large gap means high variance (overfitting). Take an unconstrained decision tree at 99% training accuracy and 61% validation accuracy. It has learned noise that exists only in the training rows. The fix is less complexity: cap max_depth, raise min_samples_leaf so no leaf rests on a handful of rows, prune, or add regularization. More training data also reduces variance. Several fixes don't address the gap. A stratified resplit or a larger validation set gives a more reliable estimate of the same systematic gap without closing it. Adding features or polynomial terms makes the model more complex and usually widens the gap.
Low scores on both sets that sit close together mean high bias (underfitting). Take a linear regression on data with clearly curved relationships, with training R-squared 0.34 and validation R-squared 0.33. The model is consistent, but consistently wrong, because a straight line can't express the pattern. The fix is more complexity: polynomial or interaction features, a tree-based model, or weaker regularization. Several fixes don't help here. Reshuffling the split with a new seed changes nothing, because a linear model has the same blind spot on every split. Adding more rows doesn't cure bias either. Outliers don't explain low scores that match this closely on both sets. To pick a better-suited model family in the first place, see algorithm selection.
High bias. The training and validation errors are close, so variance is small, but both are far from the target. Increase complexity: deeper trees, more boosting rounds, richer features or weaker regularization. Then watch validation error to see whether a gap starts to open.
Checkpoint 3 of 7· Check yourself
Your unconstrained decision tree scores 99% accuracy on training rows and 61% on validation rows. Which change addresses the cause of this result?
A large train/validation gap means high variance: the tree has memorized noise in its training rows, so the fix is less complexity. Extra features add complexity and widen the gap. Resplitting, a new seed or a bigger validation set only measures the same gap again without changing the model.
“In this example, the runs highlighted in the black boxes suggest that lower values for max_depth result in higher values for the metric auc.”Source: docs.databricks.com
Checkpoint 4 of 7· Exam question
A data scientist trains a decision tree classifier on a churn dataset without setting max_depth, achieving 99% training accuracy but only 61% accuracy on a held-out validation set. Which explanation and next step best addresses this gap?
Correct answer: A — The tree has grown deep enough to memorize noise in the training data, producing high variance; limiting max_depth or increasing min_samples_leaf will reduce complexity and close the gap.
- A. An unconstrained tree can keep splitting until each leaf fits individual training points, which drives training accuracy toward 100% while variance on unseen data grows. Reducing
max_depthor raisingmin_samples_leafcaps this complexity and typically narrows the accuracy gap. - B. A 99% training accuracy rules out underfitting; a high-bias model would perform poorly on both the training and validation sets, not just the validation set. Adding more feature interactions would only make an already-overcomplex tree fit training noise even more closely.
- C. A distribution mismatch between splits is a data problem, not a complexity problem, and nothing in the scenario suggests the splits were drawn unevenly. The described pattern — near-perfect training accuracy with much weaker validation accuracy — is the textbook signature of excess model complexity, not a split issue.
- D. Enlarging the validation set changes how precisely the gap is measured, but it does not change the tree's tendency to memorize training data. The underlying cause is the model's unconstrained complexity, which must be reduced directly.
Checkpoint 5 of 7· Exam question
A team fits an ordinary linear regression model to predict house prices from a dataset with clearly nonlinear relationships between features and price. Both training R-squared (0.34) and validation R-squared (0.33) are low and close to each other. What does this pattern indicate, and what should the team try next?
Correct answer: A — The model has high bias because it is too simple to capture the nonlinear relationships; increasing complexity by adding polynomial features or switching to a tree-based model should improve both scores.
- A. Low training and validation scores that sit close together indicate the model is too simple to represent the underlying nonlinear pattern, which is the definition of high bias. Raising complexity through polynomial features or a model class that captures nonlinearity, such as a tree-based method, addresses the true source of the poor fit.
- B. High variance shows up as a large gap between a high training score and a much lower validation score, not as two scores that are both low and close together. Reducing complexity further would only make an already underfit model fit the data even worse.
- C. Outliers can degrade R-squared, but they do not typically produce training and validation scores that are both uniformly low and nearly identical, which instead points to a systematic capacity limitation. Abandoning regression outright ignores that the real fix is matching the model's complexity to the data's nonlinearity.
- D. A flawed split would usually produce a mismatch between training and validation performance rather than two consistently low scores that agree with each other. The consistency between the scores points to the model's limited capacity, not to how the data was partitioned.
3.Settings that raise or lower complexity
Most of a model's hyperparameters move complexity in a known direction. Learn which way each one moves it, so a diagnosis translates directly into a change. Tree models expose structural limits: maximum depth, minimum rows or weight per leaf, and the minimum loss reduction required to make a split. Boosted ensembles add the number of rounds, where more rounds fit the training data more closely, and row or column subsampling, which adds randomness that damps variance. Linear models expose a regularization strength that shrinks coefficients toward zero. In Spark ML that is regParam, with elasticNetParam choosing between L2 (ridge) and L1 (lasso) penalties. In a GLM the same pair appears as lambda and alpha.
def objective(trial):
params = {
"tree_method": "hist",
"device": "cuda",
"objective": "binary:logistic",
"eval_metric": "logloss",
"max_depth": trial.suggest_int("max_depth", 3, 10),
"learning_rate": trial.suggest_float("learning_rate", 1e-3, 0.3, log=True),
"subsample": trial.suggest_float("subsample", 0.5, 1.0),
"colsample_bytree": trial.suggest_float("colsample_bytree", 0.5, 1.0),
"min_child_weight": trial.suggest_int("min_child_weight", 1, 10),
"gamma": trial.suggest_float("gamma", 1e-8, 1.0, log=True),
"reg_alpha": trial.suggest_float("reg_alpha", 1e-8, 10.0, log=True),
"reg_lambda": trial.suggest_float("reg_lambda", 1e-8, 10.0, log=True),
}| Setting | To reduce variance (overfitting) | To reduce bias (underfitting) |
|---|---|---|
| max_depth | Lower it | Raise it |
| min_child_weight | Raise it | Lower it |
| gamma | Raise it | Lower it |
| reg_alpha / reg_lambda | Raise them | Lower them |
| subsample / colsample_bytree | Lower them | Raise them toward 1.0 |
| n_estimators | Use fewer rounds | Use more rounds |
Some settings run the opposite way to their names. In a support vector machine, the regularization parameter C is an inverse strength: a larger C penalizes training mistakes more heavily, which means less regularization, a more complex boundary and higher variance. A smaller C regularizes harder. scikit-learn's LogisticRegression uses C the same inverse way, while regParam, lambda, reg_alpha and reg_lambda all regularize more as they grow. Before you turn a setting up, check whether it is a strength or an inverse strength.
Checkpoint 6 of 7· Check yourself
Training logloss for an XGBoost model is far below its validation logloss. Which set of changes moves every setting toward less complexity?
A large train/validation gap means high variance, so every setting should reduce complexity: shallower trees, more weight required per leaf and a larger minimum loss reduction per split. Lowering the L1/L2 penalties, using all rows and columns, or adding rounds each raises complexity.
“suggest that lower values for max_depth result in higher values for the metric auc.”Source: docs.databricks.com
4.Choosing complexity from a validation sweep
You choose the right amount of complexity by measuring it, not by guessing. Train the same model at several settings of a complexity control, score each run on validation data, and look at the curve. Training error keeps falling as complexity grows. Validation error falls while bias is shrinking, bottoms out, and then rises once variance takes over. The best setting is at the bottom of the validation curve. How you generate the settings is covered under hyperparameter search. How cross-validation steadies each estimate is covered there too.
A parallel coordinates chart in the MLflow UI makes this sweep visible. Each run is a line connecting its parameter values to its metric, and runs with good scores bunch together at particular settings. When the high-AUC lines all pass through shallow depths, the deep trees were overfitting. When the best lines sit at the top of the depth range you searched, the model may still be underfitting, so widen the range before you settle on a value.
The data you choose on matters as much as the setting you choose. Compare complexity settings on validation data and keep the test set out of the loop. If you pick the depth that scores best on the test set, you have tuned to that set, and its score no longer measures generalization.
Checkpoint 7 of 7· Check yourself
During a max_depth sweep, an engineer scores every run on the held-out test set, picks the depth with the best test AUC and reports that AUC as the model's expected performance. What is wrong with this?
Choosing a setting by its test score leaks knowledge of the test set into the model, so that score stops reporting generalization. Compare settings on validation data and keep the test set for the final evaluation. Training error can't pick a setting, because it keeps falling as complexity grows.
“there is still a risk of overfitting on the test set because the parameters can be tweaked until the estimator performs optimally.”Source: scikit-learn.org
Sources
(5)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://scikit-learn.org/stable/modules/cross_validation.htmlSecondary source
“would have a perfect score but would fail to predict anything useful on yet-unseen data”
↩︎ Model complexity sets the balance between bias and variance“This situation is called overfitting.”
↩︎ Diagnosing underfitting and overfitting from training and validation error“there is still a risk of overfitting on the test set because the parameters can be tweaked until the estimator performs optimally”
↩︎ Choosing complexity from a validation sweep“would have a perfect score but would fail to predict anything useful on yet-unseen data”
↩︎ Key concept“would have a perfect score but would fail to predict anything useful on yet-unseen data”
↩︎ Exam trap 1“would have a perfect score but would fail to predict anything useful on yet-unseen data”
↩︎ Exam trap 2“a model that would just repeat the labels of the samples that it has just seen would have a perfect score”
↩︎ Checkpoint“there is still a risk of overfitting on the test set because the parameters can be tweaked until the estimator performs optimally.”
↩︎ Checkpoint - 2.
“lower values for max_depth result in higher values for the metric auc”
↩︎ Model complexity sets the balance between bias and variance“A parallel coordinates plot is useful in understanding the effect of parameter settings on model performance”
↩︎ Choosing complexity from a validation sweep“In this example, the runs highlighted in the black boxes suggest that lower values for max_depth result in higher values for the metric auc.”
↩︎ Checkpoint“suggest that lower values for max_depth result in higher values for the metric auc.”
↩︎ Checkpoint“lower values for max_depth result in higher values for the metric auc”
↩︎ Prediction - 3.https://docs.databricks.com/aws/en/machine-learning/ai-runtime/examples/tutorials/sgc-xgboost-optuna-tuningOfficial docs
“Evaluate and prune on the validation set; the test set is reserved for the final evaluation.”
↩︎ Diagnosing underfitting and overfitting from training and validation error - 4.
“lambda: Numeric, Regularization parameter”
↩︎ Settings that raise or lower complexity - 5.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-spark-mlflow-integrationOfficial docs
“The objective is to find the best value for the regularization parameter C.”
↩︎ Settings that raise or lower complexity“The objective is to find the best value for the regularization parameter C.”
↩︎ Exam trap 3