🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Science & Analytics › Introduction to Machine Learning for Data Analytics › Lesson 4
TEC-DATA85-08 · Lesson 4 · 12 clock hours · lab

Decision Trees and Random Forests

Objective. Students will train, visualize, and compare a decision tree and a random forest classifier, explain overfitting using depth hyperparameters, and rank feature importances.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Decision Trees and Random Forests

How a Decision Tree Works

A decision tree is a flowchart-style model that splits data into smaller groups by asking a series of yes/no questions about feature values. At each internal node the algorithm chooses the feature and threshold that best separates the classes — in scikit-learn the default criterion for classification is Gini impurity, which measures how often a randomly chosen item would be mislabeled if it were randomly classified according to the distribution at that node. The tree keeps splitting until it reaches a leaf node, which returns a predicted class.

Because a tree can keep splitting until every training sample is correctly classified, an unpruned tree almost always achieves near-perfect training accuracy but performs poorly on new data. That gap between training performance and validation (or test) performance is called overfitting. The model has memorized the training set instead of learning general patterns.

Controlling Overfitting with Hyperparameters

The most direct way to limit overfitting in a single decision tree is to restrict how deep the tree can grow using the `max_depth` hyperparameter in scikit-learn. A shallow tree (for example, `max_depth=3`) forces the model to capture only the most important splits and tends to generalize better. You compare training accuracy versus validation accuracy across several depth values; when training accuracy climbs much faster than validation accuracy, the model is overfitting.

Other useful hyperparameters include `min_samples_split` (the minimum number of samples required to split a node) and `min_samples_leaf`. Adjusting these can also reduce overfitting without imposing a hard depth limit.

From One Tree to a Forest

A random forest is an ensemble of decision trees. It reduces the variance that makes a single tree unstable through two mechanisms:

1. Bootstrap aggregation (bagging): Each tree is trained on a random sample of the training data drawn with replacement. No single tree sees the full dataset.

2. Feature randomness: At every split, each tree considers only a random subset of features rather than all of them. This decorrelates the trees so their errors are not all in the same direction.

The final prediction is determined by a majority vote across all trees. Because individual trees err in different directions, averaging their votes cancels out much of the random noise, producing a model with lower variance than any single tree — even though each individual tree may still overfit its bootstrap sample.

Key hyperparameters for `RandomForestClassifier` in scikit-learn:

Feature Importances

Scikit-learn calculates feature importance for tree-based models by measuring the total reduction in impurity (Gini or entropy) that a feature produces across all splits and all trees, weighted by the number of samples that reach those splits. The values are normalized so they sum to 1.0. A higher value means that feature contributed more to splitting the data cleanly. Feature importances are a fast way to understand which variables drive the model's decisions and to communicate results to stakeholders.

Important caveat: tree-based importances can be biased toward high-cardinality features (features with many unique values). When you need rigorous feature attribution, complement this with permutation importance or SHAP values.

Validation Curves and Hyperparameter Tuning

A validation curve plots a performance metric (such as accuracy) on the y-axis against a hyperparameter value (such as `max_depth`) on the x-axis, showing separate lines for training and validation scores. The ideal operating point is where validation accuracy is highest before it begins to decline — the point just before the training-validation gap widens significantly.

A manual grid search means you loop over a list of hyperparameter combinations, train a model for each, record validation metrics, and select the combination with the best validation score. Scikit-learn's `GridSearchCV` automates this with cross-validation, but doing it manually in a loop first helps you understand exactly what is happening.

Responsible and Safe Data Practices

When working with medical or financial datasets — such as the Heart Disease UCI or Credit Approval UCI datasets used in this lab — you must follow data-handling protocols:

Connecting to the Credentials

Decision trees and random forests appear in the IBM Data Science Professional Certificate curriculum and are tested indirectly in CompTIA Data+ through questions on modeling concepts and data analysis techniques. Understanding variance, bias, and model validation is also foundational knowledge for the Google Data Analytics Certificate capstone and the data modeling content of Microsoft PL-300.

Key terms9

Gini impurityA measure of how often a randomly chosen element from a set would be incorrectly classified if it were randomly labeled according to the class distribution at a node; ranges from 0 (pure) to values below 1.
OverfittingA condition in which a model learns the training data too precisely — including its noise — and therefore performs significantly worse on new, unseen data than on the data it was trained on.
max_depthA hyperparameter in scikit-learn tree models that limits how many levels of splits the tree can make; lower values reduce complexity and can reduce overfitting.
Bootstrap aggregation (bagging)A technique in which each tree in an ensemble is trained on a different random sample of the training data drawn with replacement, so trees are exposed to different subsets of examples.
Feature importanceA score assigned to each input variable by a tree-based model, reflecting how much that variable reduced impurity across all splits and all trees, normalized so all scores sum to 1.0.
Validation curveA plot showing model performance (training and validation) on the y-axis against a hyperparameter value on the x-axis, used to identify the point where increasing model complexity begins to cause overfitting.
Ensemble methodA machine learning approach that combines predictions from multiple models — such as many decision trees — to produce a final prediction that is more accurate and stable than any single model alone.
Variance (in ML context)The tendency of a model to change significantly when trained on different subsets of the data; high-variance models overfit their training set. Random forests reduce variance by averaging across many trees.
n_estimatorsThe hyperparameter in RandomForestClassifier that controls how many decision trees are included in the forest; more trees generally improve stability but increase training time.

Worked examples4

1. A decision tree trained on 150 samples achieves 99% training accuracy and 74% validation accuracy. A second tree with max_depth=4 achieves 88% training accuracy and 85% validation accuracy. Calculate the overfitting gap for each model.
  1. Overfitting gap = Training accuracy − Validation accuracy.
  2. Unpruned tree gap: 99% − 74% = 25 percentage points.
  3. Pruned tree (max_depth=4) gap: 88% − 85% = 3 percentage points.
  4. Compare: the unpruned tree has a gap of 25 pp versus 3 pp for the pruned tree, confirming the pruned tree generalizes far better.
Answer: Unpruned gap = 25 percentage points; pruned gap = 3 percentage points. The pruned tree is the better choice for deployment.
2. A random forest returns raw feature importances for five features: Age = 0.35, Cholesterol = 0.28, BloodPressure = 0.20, Glucose = 0.12, Smoking = 0.05. Verify they are normalized correctly and rank them.
  1. Sum all importances: 0.35 + 0.28 + 0.20 + 0.12 + 0.05 = 1.00.
  2. The sum equals 1.00, confirming normalization is correct.
  3. Rank by descending importance: 1st Age (0.35), 2nd Cholesterol (0.28), 3rd BloodPressure (0.20), 4th Glucose (0.12), 5th Smoking (0.05).
Answer: Sum = 1.00 (normalized). Ranking: Age > Cholesterol > BloodPressure > Glucose > Smoking.
3. You run a manual grid search over n_estimators ∈ {50, 100, 200} and max_depth ∈ {3, 5, None}. That produces 9 combinations. If each model is evaluated with 5-fold cross-validation, how many total model fits are performed?
  1. Number of hyperparameter combinations = 3 (n_estimators) × 3 (max_depth) = 9.
  2. Each combination is fit once per fold: 9 × 5 = 45 fits.
  3. Optionally, a final model is refit on the full training set after selecting the best combination, adding 1 more fit for a total of 46 — but the standard count for the search itself is 45.
Answer: 45 model fits are performed during the grid search (9 combinations × 5 folds).
4. A random forest with 100 trees votes on a binary classification (class 0 or class 1). 63 trees vote class 1 and 37 trees vote class 0. What is the predicted class and the estimated probability of class 1?
  1. Majority vote: 63 > 37, so the predicted class is class 1.
  2. Estimated probability of class 1 = votes for class 1 ÷ total trees = 63 ÷ 100 = 0.63.
  3. Estimated probability of class 0 = 37 ÷ 100 = 0.37.
Answer: Predicted class = 1; estimated probability of class 1 = 0.63.

The math in this lesson1

Learners compute overfitting gaps as training minus validation accuracy in percentage points.
N-Q.3
Brush up in the math halls at newSchoolWorks.com:
In class: Instructor demo: grow an unpruned decision tree on the Iris dataset, visualize it with sklearn.tree.plot_tree, observe overfit on training data vs. validation data; then repeat with max_depth restricted and compare metrics. · Lab: students train a RandomForestClassifier on a provided medical or financial dataset, run a manual grid search over n_estimators and max_depth, plot validation curves, and produce a bar chart of the top 10 feature importances. · Reflection journal entry (minimum 150 words): student explains in plain language why averaging many trees reduces variance and how they would explain random forests to a hiring manager unfamiliar with ML.
Materials: Jupyter Lab, scikit-learn, matplotlib, Géron ch. 6–7, provided dataset (e.g., Heart Disease UCI or Credit Approval UCI)
Check: Lab notebook must include validation curve plot showing overfitting trend, a tuned model with documented best hyperparameters, and feature importance chart; all three artifacts required plus ≥ 70% rubric score.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Machine learning concepts / IBM Data Science Professional
1. In scikit-learn, what does the default Gini impurity criterion measure at each decision tree node?
Data analysis and modeling / CompTIA Data+
2. A model achieves 97% training accuracy and 71% validation accuracy. Which term best describes this situation?
Machine learning concepts / IBM Data Science Professional
3. Which two mechanisms does a random forest use to reduce the correlation among its individual trees?
Data analysis and modeling / CompTIA Data+
4. You are plotting a validation curve for max_depth from 1 to 20. At max_depth=8, training accuracy is 94% and validation accuracy is 91%. At max_depth=15, training accuracy is 99% and validation accuracy is 83%. What is the best max_depth to select?
Data analysis and modeling / IBM Data Science Professional
5. A random forest's feature_importances_ array sums to 0.98 instead of 1.0. What is the most likely explanation?
Data governance and ethics / CompTIA Data+
6. When working with the Heart Disease UCI dataset in a classroom environment, which practice is most important for responsible data handling?
Data analysis and modeling / Google Data Analytics
7. You set random_state=42 in your RandomForestClassifier. What is the primary reason for doing this?
Machine learning concepts / IBM Data Science Professional
8. A stakeholder asks why adding more trees to a random forest eventually stops improving validation accuracy. Which explanation is most accurate?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.