Purpose: This tutorial explains Random Forest Regression from scratch. Every important term is defined the first time it appears, all code runs without external files, and a glossary and cheat sheet at the end make for quick review.
0. The 60-Second Refresher
Regression is a machine learning task where we predict a number, such as a house price, salary, or temperature.
A decision tree makes predictions by asking questions about the input and sending each observation down a sequence of branches.
A random forest builds many decision trees using different random samples of the training data.
Each tree makes its own prediction. The random forest averages the predictions to produce the final prediction.
Combining many trees often makes predictions more stable than relying on one tree.
In scikit-learn, we use RandomForestRegressor fromsklearn.ensemble.
The central idea: Instead of trusting one decision tree, let many trees make predictions and combine their answers.
1. Where This Fits
Machine learning problems are often divided into two broad categories:
Supervised learning: We train a model using examples that include both the inputs and the correct answers.
Unsupervised learning: We give a model data without target answers and ask it to discover patterns or structure.
Regression is a type of supervised learning. In regression, the model learns a relationship between input information and a numerical target. For example:
House size (square feet)
House price
800
$100,000
1,000
$130,000
1,500
$190,000
2,000
$250,000
We give the model the house sizes and their known prices. After learning from these examples, we can ask it to predict the price of another house.
Random Forest Regression is one way to solve this problem.
Models covered in this learning sequence
Simple Linear Regression
Multiple Linear Regression
Polynomial Regression
Support Vector Regression (SVR)
Decision Tree Regression
Random Forest Regression
Random Forest Regression builds on the idea behind Decision Tree Regression. Before learning about the forest, we need to understand the tree.
2. The Problem We're Solving
Let’s use the familiar Truth or Bluff salary example. Imagine you are hiring a new employee. During the interview, the candidate says their previous salary was $160,000.
Is that believable?
To check, you collect salary information for every position level (1 to 10) at the candidate’s previous company, using sources such as Glassdoor. The result is the table below.
Position
Level
Salary
Business Analyst
1
$45,000
Junior Consultant
2
$50,000
Senior Consultant
3
$60,000
Manager
4
$80,000
Country Manager
5
$110,000
Region Manager
6
$150,000
Partner
7
$200,000
Senior Partner
8
$300,000
C-level
9
$500,000
CEO
10
$1,000,000
2.1 Understanding the input and output
Before training a machine learning model, we must identify two things:
Feature (X): The information we give the model to make a prediction. Here: Level.
Target (y): The value we want the model to predict. Here: Salary.
Position: A text label for information already captured by Level, so we drop it.
Our task: Given a position level, predict the corresponding salary.
2.2 Why predict position level 6.5?
According to the candidate’s employment information, they worked as a Regional Manager, which is position level 6 in the table.
But they held that role for two years. After two years in a role, a person’s salary has usually grown beyond the starting pay for that level. So their salary was probably somewhere between level 6 ($150K) and level 7 ($200K).
That is why we use level 6.5 as the input. It represents “about two years into level 6, partway toward level 7”.
We train a model on the table and ask:
“What salary does the model predict for position level 6.5?”
If the prediction is close to the candidate’s claimed $160,000, the claim looks believable. If it is far off, the claim may be a bluff. That is where the “Truth or Bluff” title of the plot comes from.
The value 6.5 does not appear in the training data, so the model is predicting for an input it has never seen. Because 6.5 lies inside the range of training inputs (1 to 10), this is called interpolation.
Important distinction: A random forest does not draw a smooth line between level 6 and level 7. Its trees make piecewise-constant (step-like) predictions, and the forest averages them. So the answer at 6.5 is not guaranteed to be halfway between $150K and $200K. We’ll see why when we study decision trees.
2.3 A limitation of this example
This is a tiny teaching dataset: 10 rows, one feature. It’s useful for understanding the algorithm, but not enough for a reliable salary prediction system.
Also, level 6.5 is our own assumption about where the candidate sat, and the salary data comes from public sites. A real model would need far more relevant information (location, experience, industry, company size, responsibilities, compensation structure) and proper evaluation on unseen data.
3. Building Block 1: Decision Tree Regression
A random forest is made of decision trees, so let’s first understand how one tree makes a prediction.
3.1 What is a decision tree?
A decision tree is a model that predicts by asking a sequence of questions about the input. Think of it as an upside-down flowchart. For example, a tree predicting salary from position level:
Is Level <= 4.5?
/ \
Yes No
| |
Predict $60,000 Is Level <= 7.5?
/ \
Yes No
| |
Predict $200,000 Predict $600,000
This is an illustrative tree to explain the idea. It is not the exact tree scikit-learn would learn.
The tree asks a question, follows the appropriate branch, and continues until it reaches a final answer.
3.2 Nodes, branches, and leaves
Node: A point in the tree where a question is asked.
Branch: The path followed depending on the answer.
Imagine a doctor sorting patients into diagnoses. The doctor asks, "Is the fever above 38°C?" Depending on the answer, the patient goes down one line of questioning or another. The doctor may ask more questions until the patient reaches a final diagnosis.
The questions are decision nodes. The lines of questioning are branches. The final diagnoses are leaves.
Note: Diagnosis is a classification task (predicting a category), while our task is regression (predicting a number). The analogy illustrates the mechanics of nodes, branches, and leaves, not the type of prediction. A numeric medical example would be estimating a patient's dosage or predicted recovery time.
3.3 How does a leaf make a prediction?
For a regression tree, a leaf generally predicts the average of the target values of the training examples that reached that leaf.
Suppose a leaf contains two training examples, $150,000 and $250,000. The prediction is:
(150,000 + 250,000) / 2 = 200,000
Everyone who reaches that leaf gets the same prediction. The tree does not draw a line between examples. This is why tree predictions look like steps.
3.4 Walking through a prediction
Using the illustrative tree above, a new employee with Level = 6:
Is Level <= 4.5? No → go right.
Is Level <= 7.5? Yes → go left.
We reach a leaf and return its stored average ($200,000 in this illustration).
3.5 Why can one decision tree be unreliable?
A single decision tree can be sensitive to its training data. Imagine training a tree on a dataset. Then you slightly change the dataset by adding or removing a few observations. Those changes may cause the tree to choose different questions and split points. Its structure and predictions can change considerably.
This sensitivity is one reason a single tree can have high variance.
Variance (in this context) describes how much a model’s predictions change when it is trained on different samples of data. A high-variance model may learn patterns that are too specific to its particular training sample.
This leads to the main idea: combine multiple trees instead of relying on one.
4. Building Block 2: Ensemble Learning
4.1 What is ensemble learning?
Ensemble learning means combining the predictions of multiple models to produce one final prediction. The individual models are called base models or estimators. They can be different types of models, or many versions of the same type.
Random Forest is an ensemble of decision trees. Another popular ensemble family is gradient boosting, which is studied separately.
4.2 The “Guess the Number in the Jar” analogy
At fairs and malls, there is a game: a jar full of marbles. Guess the number inside, and the closest guess wins a big prize.
Here is a clever way to beat the game without counting anything:
Stand next to the organizer with a pen and paper.
Each time someone finishes guessing and walks away, ask: "What number did you guess?" (They usually seal their guess in an envelope, so they don't know if they were right, and they'll happily tell you.)
Write each number down. Keep going until you have a lot of guesses: maybe 100, maybe a couple of hundred, or even thousands if you're determined and the contest is popular.
Take the average of all the guesses. Or take the median if you don't want silly outliers (like someone guessing "1" or "5 million") to distort the result. You can also just throw the outliers out first.
Why does this work?
Each person's guess is noisy. Some guess too high, some too low. But human visual estimates tend to be spread roughly in a bell curve (normal distribution) around the true number. The errors in both directions largely cancel out, so the middle of the crowd is often closer to the truth than most individual guesses.
A small numeric example:
Person
Guess
Person 1
400
Person 2
500
Person 3
550
Person 4
450
Person 5
600
(400 + 500 + 550 + 450 + 600) / 5 = 500
Caveat: The crowd's average is often closer than most individual guesses, but there is no guarantee. If most people are biased in the same direction (for example, everyone underestimates a tall jar), averaging won't fix that shared bias. The same is true of trees trained on the same data.
4.3 Connecting the analogy to random forests
Jar guessing
Random forest
One person’s guess
One decision tree’s prediction
Many people’s guesses
Many decision trees’ predictions
Average of the guesses
Average of the tree predictions
Final estimate
Final model prediction
The analogy is not perfect: trees trained on the same data are not fully independent like strangers at a fair, so their errors can be related. But it gives the central intuition:
Several models can produce a more stable combined prediction than one model alone, especially when their errors are not all the same.
5. How Random Forest Regression Works
Now we can put the two building blocks together. A random forest is a collection of decision trees. Each tree is trained with some randomness so that the trees are not all identical.
5.1 The algorithm, step by step
A simplified random forest regression process looks like this:
Start with the training dataset.
Randomly create a sample of training rows for the first tree.
Train a decision tree on that sample.
Repeat to create as many trees as requested, each on its own sample.
When a new input arrives, send it through every tree.
Collect each tree’s prediction.
Average those predictions.
Return the average as the forest’s final prediction.
Training data
|
+--------------+--------------+
| | |
Random sample Random sample Random sample
| | |
Tree 1 Tree 2 Tree 3
| | |
Prediction 1 Prediction 2 Prediction 3
| | |
+--------------+--------------+
|
AVERAGE
|
Final prediction
A forest can contain 10, 100, 500, or more trees.
5.2 A worked prediction example
Suppose we want to predict the salary for position level 6.5. Imagine four trees make these predictions:
Forest prediction = (sum of all tree predictions) / (number of trees)
5.3 What is bootstrap sampling?
We said each tree gets a random sample of the training data. The specific method random forests use is bootstrap sampling: randomly selecting rows with replacement.
Imagine a dataset of five rows: A, B, C, D, E. One bootstrap sample might be:
A, C, C, E, B
Notice:
Row C appears twice.
Row D does not appear at all.
The sample still has five selections.
Because we sample with replacement, a row can be selected more than once, while another row might not be selected at all. Each tree receives a different bootstrap sample, so the trees can learn
different patterns.
In scikit-learn, RandomForestRegressor uses bootstrap sampling by default because bootstrap=True is the default setting. You do not need to write the sampling code yourself. The estimator handles it.
5.4 What are out-of-bag (OOB) samples?
Because bootstrap sampling selects rows with replacement, some training rows are left out of a particular tree’s bootstrap sample. These unused rows are called out-of-bag (OOB) samples for that tree.
They can be used to estimate model performance without creating a separate validation set in some situations.
In scikit-learn, you can request this estimate with oob_score=True, provided bootstrap sampling is enabled.
Caution: OOB scoring needs enough rows per tree to be meaningful. On our 10-row salary dataset it is unreliable, treat it as a demonstration of the syntax only.
For now, remember:
Bootstrap rows are used to train a particular tree.
Out-of-bag rows were not selected for that tree.
OOB evaluation can provide an additional estimate of generalization performance.
We will focus on the main training workflow first.
5.5 What about randomness in the features?
Random forests can introduce randomness in two ways:
Randomly sampling training rows for each tree.
Randomly limiting which features a split may consider, controlled by max_features.
For example, imagine a house-price dataset with these features:
House size
Number of bedrooms
Number of bathrooms
Property age
Distance from the city center
If a tree considers only a subset of features when choosing a split, it may choose a different split from another tree. This can make the trees less similar and help their errors differ.
Important scikit-learn detail: For RandomForestRegressor, the default max_features is 1.0, meaning all features are considered when searching for the best split. This differs from the common classification default. You can lower max_features when you want more feature-level randomness.
In our salary example, there is only one feature (Level), so there is no meaningful subset of different features to choose from. The main source of variation between trees is bootstrap sampling.
5.6 Why can a forest perform better than one tree?
1. It is often more stable. One tree may change considerably when the training data changes.
Averaging many trees generally reduces the effect of any one tree’s unusual prediction.
2. It can reduce variance. If trees make different errors, averaging can cancel out some of those
errors. This is one of the main statistical reasons random forests can work well.
3. It can generalize better.Generalization means how well a model performs on new data it didn’t train on. A forest may perform better on unseen data than a single deep tree because it is less dependent on the quirks of one training sample.
A random forest is not guaranteed to be more accurate on every dataset. Averaging often reduces variance, but performance still depends on the data, features, and model settings.
6. Python Implementation: Step by Step
We’ll check the candidate’s claim using the salary dataset. We create the data directly in Python, so there’s no CSV to download and no Google Drive to mount.
Step 1: Import the libraries
import numpy as npimport matplotlib.pyplot as pltimport pandas as pd
Library
Purpose
NumPy
Numerical operations and arrays
Matplotlib
Creating plots
Pandas
Loading and handling datasets
A library is a collection of reusable code that helps us perform common tasks without writing everything ourselves.
pd.DataFrame(...) builds a table from a dictionary: each key is a column name, each list holds that column’s values. All lists must have the same length (10).
head(10) displays the first 10 rows.
Aside: With a real dataset you would load a CSV instead: dataset = pd.read_csv("position_salaries.csv"). Hard-coding the data only makes sense because this table is tiny.
Step 3: Separate features (X) and target (y)
We need to tell the model which information it should use as input and which value it should learn to predict.
X = dataset[["Level"]].valuesy = dataset["Salary"].values
dataset[["Level"]] selects the Level column as a DataFrame (2D). The double square brackets are what keep it 2D.
dataset["Salary"] selects the salary column as a Series (1D).
.values converts each to a NumPy array.
The shapes are:
X -> 2D array: 10 rows x 1 feature
y -> 1D array: 10 salary values
Rows are observations (samples), and columns are features. Even with one feature, X must be 2D.
Step 4: Create and train the model
RandomForestRegressor is scikit-learn’s implementation of random forest for predicting numerical values.
from sklearn.ensemble import RandomForestRegressorregressor = RandomForestRegressor( random_state=0, n_estimators=100)
n_estimators=100
An estimator is a model that makes predictions. In a random forest, each tree is one estimator, so this builds 100 trees, and the final prediction is the average of their 100 predictions. You could choose 10, 50, 200, 500, etc. More trees generally make the average more stable but cost more computation. More trees do not guarantee better accuracy every time.
random_state=0
Random forests use randomness when creating bootstrap samples and building trees. Without controlling it, results may differ between runs. random_state sets the random seed so the process is reproducible. The value 0 is not special; 42 or 10 would work too. Just use the same seed when you want the same result.
Train the model:
regressor.fit(X, y)
fit() trains a scikit-learn estimator: X is the input, y the correct answers.
Step 5: Predict a new result
Now ask the question from Section 2: what salary does the model predict for level 6.5?
With n_estimators=100 and random_state=0, this prints:
[163000]
The exact value depends on the configuration and data. With the fixed seed, it is reproducible in the same scikit-learn environment.
Caveat: This is a demonstration on 10 artificial rows. Do not treat $163,000 as a real salary estimate or as proof about the candidate. The exact number can also vary slightly across scikit-learn versions; the important point is the workflow, not the digit
Why double square brackets?
predict() expects a 2D array (rows = samples, columns = features). [[6.5]] means “1 row × 1 feature”. By contrast, [6.5] is 1D and normally causes a shape error.
The model’s output is not a guaranteed estimate of the candidate’s actual salary. It is the prediction learned from our small artificial dataset.
A prediction near $160,000 does not prove that the candidate’s claim is true. We would need more relevant data and a properly evaluated model to make a meaningful judgment.
Also remember that the forest averages tree predictions. It does not simply look at the two nearest salary rows and calculate their midpoint.
Step 7: Visualize the results
Let’s visualize the original observations and the random forest’s predictions.
# Create many input values between the minimum and maximum levels.X_grid = np.arange(X.min(), X.max(), 0.1)X_grid = X_grid.reshape(len(X_grid), 1)# Plot the original observations.plt.scatter(X, y, color="red")# Plot the random forest predictions.plt.plot(X_grid, regressor.predict(X_grid), color="blue")plt.title("Truth or Bluff (Random Forest Regression)")plt.xlabel("Position Level")plt.ylabel("Salary")plt.show()
What does each part do?
X_grid = np.arange(X.min(), X.max(), 0.1)
Creates many values between the minimum and maximum levels: 1.0, 1.1, 1.2, 1.3, ..., 9.9.
Why? If we plotted predictions only for the original 10 data points, we would see only 10 predicted points. Using more values lets us see how the model behaves between the training levels.
X_grid = X_grid.reshape(len(X_grid), 1)
Turns the values into a 2D column array, which is the shape expected by predict(). Writing reshape(-1, 1) does the same thing.
The result is usually a step-like line rather than a smooth curve. We will explain why in the next section.
7. Reading the Plot: Why Does It Look Like a Staircase?
A random forest plot often looks like a staircase. This is expected for tree-based regression, not a plotting mistake.
7.1 Why does one decision tree produce steps?
A regression tree divides the input space into regions using split points. Within each region (leaf), the prediction is a constant: the average target of the training rows there. For example, a tree might produce regions like this (the values below are illustrative, not computed from our data):
The prediction stays the same while the input remains in the same region. When the input crosses a split point, it enters another leaf and the prediction changes. That creates a staircase shape.
7.2 Why does the forest also look like steps?
Every tree is piecewise constant, and the forest averages them. Different trees have different split points and leaf values, so the average can produce a more detailed staircase than one tree. It is still generally piecewise constant.
7.3 Does adding more trees make the line smoother?
Not necessarily. More trees generally make the average more stable, but they don’t guarantee a smooth curve. The shape depends on the data, the split points, the number of trees, and other settings.
Tree-based models often look underwhelming on tiny one-feature datasets. They shine on datasets with many features.
8. Random Forest vs. Decision Tree
Feature
Decision Tree
Random Forest
Number of trees
One
Many
Training
One tree is trained
Many trees are trained
Prediction
One tree’s prediction
Average of tree predictions
Stability
Can be sensitive to training data
Generally more stable
Overfitting
A deep tree can overfit
Often reduces overfitting vs. one deep tree
Training time
Usually faster
Usually slower
Interpretability
Easier to inspect
Harder to interpret
What is overfitting?
Overfitting happens when a model learns the training data too closely, including noise or accidental patterns that don’t generalize.
Analogy: A student memorizes the exact answers to practice questions. They score perfectly on those, but struggle when the exam has new questions.
An overfit model performs very well on training data but poorly on new data. Random forests often reduce overfitting compared with a single deep tree (because averaging reduces variance), but they do not eliminate it.
9. Important Random Forest Parameters
You do not need to memorize every parameter immediately. Start with the ones that most directly affect the model.
Parameter
What it controls
Beginner-friendly explanation
n_estimators
Number of trees
How many decision trees the forest builds
max_depth
Maximum tree depth
How many levels of questions a tree can make
min_samples_split
Minimum samples required to split a node
How many training rows a node must contain before it can be divided
min_samples_leaf
Minimum samples in a leaf
The minimum number of training rows allowed in a final leaf
max_features
Features considered when searching for a split
How many features a tree can consider at each split
bootstrap
Whether bootstrap samples are used
Whether each tree receives a sample drawn with replacement
This configuration builds 200 trees, limits each tree’s depth to 10, and fixes the random seed.
These values are examples, not universally best settings. The right configuration depends on the dataset and should be selected using validation or cross-validation.
10. Do We Need Feature Scaling?
Feature scaling means transforming numerical features to comparable ranges (e.g., standardization or normalization). It matters for algorithms sensitive to scale. For example, a dataset with:
Age: 18 to 70
Annual income: 10,000 to 200,000
House area: 500 to 5,000
Some algorithms are sensitive to these differences in scale.
Random forests generally do not need feature scaling. A tree splits on whether a feature is above or below a threshold. Changing units (say, square feet to square meters) changes the threshold’s number but not the ordering of observations, so the splits are essentially equivalent.
11. Strengths and Limitations
Strengths
Handles nonlinear relationships. It doesn’t require a straight-line relationship between features and target.
Works with multiple features. For example, house price from size, bedrooms, bathrooms, age, and location features.
Often provides a strong baseline. It can perform reasonably well without scaling or heavy preprocessing. (A baseline is a starting model used as a performance reference before trying fancier approaches.)
Often more stable than a single tree. Averaging reduces the influence of one tree’s unusual prediction.
Limitations
Step-like predictions. Output is piecewise constant, not a smooth curve.
Poor extrapolation. It generally can’t continue a trend beyond the target values in its training data.
More computation. Hundreds of trees need more time and memory than one.
Harder to interpret. One small tree can be read as a sequence of questions; hundreds of trees can’t.
Not automatically accurate. It can’t compensate for poor data, missing important features, data leakage, or an unsuitable target.
Why is extrapolation difficult?
Interpolation: predicting within the range of training inputs.
Extrapolation: predicting outside that range.
With training levels 1 to 10:
Level 6.5 is inside the range → interpolation.
Level 15 is outside the range → extrapolation.
A tree sends level 15 down the same branches it learned from the data, lands in a leaf (the one for the highest levels), and returns that leaf’s stored value. It has no rule that naturally continues the upward salary trend.
A linear model can extend its fitted line beyond the training range, although extrapolation can be unreliable for any model.
12. A Note About Evaluating Regression Models
A model producing a prediction is not the same as a model performing well. To judge usefulness, we compare predictions against actual values the model hasn’t learned from.
Warning about our salary dataset: With only 10 rows, a train/test split leaves almost nothing to train or evaluate on. The metrics below would be unstable and shouldn't be treated as evidence that the model suits real salary prediction. The code shows the workflow for a sufficiently large dataset. It is not a meaningful assessment of this toy example.
For a realistic demo, use a larger dataset such as scikit-learn's built-in California housing data:
from sklearn.datasets import fetch_california_housingdata = fetch_california_housing()X, y = data.data, data.target
X is already 2D (one row per district, several feature columns), so it plugs directly into the workflow below.
12.1 Training data and test data
Training data: examples used to train the model.
Test data: separate examples used to evaluate the trained model on unseen data.
With a sufficiently large dataset:
from sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_scorefrom sklearn.ensemble import RandomForestRegressorimport numpy as npX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, # 20% test, 80% train random_state=42)# A fresh model, so we don't overwrite the one trained in Section 6.eval_model = RandomForestRegressor( n_estimators=100, random_state=42)eval_model.fit(X_train, y_train)y_pred = eval_model.predict(X_test)mae = mean_absolute_error(y_test, y_pred)mse = mean_squared_error(y_test, y_pred)rmse = np.sqrt(mse)r2 = r2_score(y_test, y_pred)print("MAE:", mae)print("MSE:", mse)print("RMSE:", rmse)print("R²:", r2)
12.2 What do these metrics mean?
MAE (Mean Absolute Error): the average absolute difference between actual and predicted values.
MAE = (1/n) * sum(|actual - predicted|)
If MAE is 10,000, predictions are off by 10,000 units on average.
MSE (Mean Squared Error): the average of squared errors.
MSE = (1/n) * sum((actual - predicted)^2)
Squaring makes large errors count more heavily.
RMSE (Root Mean Squared Error): the square root of MSE.
RMSE = sqrt(MSE)
It’s in the same units as the target, so it’s easier to interpret than MSE.
R² (R-squared): compares the model’s predictions against a simple baseline that always predicts the mean target. Closer to 1 often means a better fit, but interpretation depends on the data and setup. R² can be negative when the model does worse than the mean-prediction baseline.
13. Complete Code in One Place
# ==========================================# 1. Importing the libraries# ==========================================import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn.ensemble import RandomForestRegressor# ==========================================# 2. Creating the dataset# ==========================================dataset = pd.DataFrame({ "Position": [ "Business Analyst", "Junior Consultant", "Senior Consultant", "Manager", "Country Manager", "Region Manager", "Partner", "Senior Partner", "C-level", "CEO" ], "Level": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], "Salary": [ 45000, 50000, 60000, 80000, 110000, 150000, 200000, 300000, 500000, 1000000 ]})# ==========================================# 3. Separating features and target# ==========================================X = dataset[["Level"]].valuesy = dataset["Salary"].values# ==========================================# 4. Creating and training the model# ==========================================regressor = RandomForestRegressor( n_estimators=100, random_state=0)regressor.fit(X, y)# ==========================================# 5. Predicting the salary for level 6.5# ==========================================prediction = regressor.predict([[6.5]])print("Predicted salary:", prediction[0])# ==========================================# 6. Visualizing the results# ==========================================# Create many input values between the minimum and maximum levels.X_grid = np.arange(X.min(), X.max(), 0.1)X_grid = X_grid.reshape(len(X_grid), 1)# Plot the original observations.plt.scatter(X, y, color="red")# Plot the random forest predictions.plt.plot(X_grid, regressor.predict(X_grid), color="blue")plt.title("Truth or Bluff (Random Forest Regression)")plt.xlabel("Position Level")plt.ylabel("Salary")plt.show()
14. Glossary
Term
Plain-English meaning
Regression
Predicting a numerical value
Supervised learning
Learning from examples that include the correct target
Feature (X)
An input variable used to make a prediction
Target (y)
The value the model is trained to predict
Sample / observation
One row or example in a dataset
DataFrame
A pandas table made of named columns
Decision tree
A model that predicts by asking a sequence of questions
Node
A point in a tree where a decision is made
Branch
A path followed after a decision
Leaf
A final point in a tree; predicts the average target of the rows in it
Ensemble learning
Combining multiple models to produce a prediction
Estimator
A model that learns from data and makes predictions; here, one tree
Random forest
An ensemble of decision trees
Bootstrap sampling
Random sampling with replacement
Out-of-bag sample
A training row not selected for a particular tree’s bootstrap sample
n_estimators
Number of trees in the forest
max_features
Number or proportion of features considered at each split
Random seed
A value that makes random processes reproducible
Variance
How much a model’s predictions change across different training samples
Overfitting
Learning training data too closely, including patterns that don’t generalize
Generalization
How well a model performs on new, unseen data
Interpolation
Predicting within the range of training inputs (e.g., level 6.5)
Extrapolation
Predicting outside the range of training inputs (e.g., level 15)
Feature scaling
Transforming features to comparable numerical ranges
Baseline
A simple starting model used as a performance reference
Training data
Data used to fit a model
Test data
Separate data used to evaluate a trained model
MAE
Average absolute prediction error
MSE
Average squared prediction error
RMSE
Square root of MSE; same units as the target
R²
A score comparing predictions with a mean-target baseline
15. Cheat Sheet
Essential code
from sklearn.ensemble import RandomForestRegressorregressor = RandomForestRegressor( n_estimators=100, random_state=0)regressor.fit(X, y) # Train the modelregressor.predict([[6.5]]) # Predict one sample with one feature
Core idea: train many decision trees and average their predictions
n_estimators: number of trees
random_state: makes the random process reproducible
bootstrap=True: bootstrap samples are used by default
max_features=1.0: the regressor considers all features by default
.fit(X, y): trains the model
.predict(X_new): predicts for new samples; input must be 2D
Feature scaling: generally not needed
Main benefit: often more stable than one decision tree
Main limitation: poor extrapolation beyond the training input range
Evaluation: use a separate test set or cross-validation on a sufficiently large dataset
Small datasets: can be created directly with pd.DataFrame({...})
The scenario: candidate claims $160K; Regional Manager (level 6) for two years, so we test level 6.5
The algorithm at a glance
Training data
|
v
Create different bootstrap samples
|
v
Train one decision tree on each sample
|
v
Give a new input to every tree
|
v
Collect all tree predictions
|
v
Calculate their average
|
v
Final random forest prediction
Final Takeaway
A decision tree predicts by asking questions about the input. The input follows branches until it reaches a leaf, and that leaf provides the prediction.
A single tree can be sensitive to its training data: small changes can lead to different splits and predictions.
A random forest addresses some of that instability by building many trees on randomized samples of the training data. When a new input arrives:
Every tree makes a prediction.
The forest collects those predictions.
It calculates their average.
That average becomes the final prediction.
The most important idea to remember:
Many varied decision trees, combined through averaging, often produce a more stable prediction than one decision tree alone.
Random forests are useful for learning nonlinear patterns in tabular data, especially with multiple relevant features. But they are not automatically accurate, and they are generally poor at extrapolating beyond the range of their training data.