|
|
A machine learning method called Gradient Boosting creates an ensemble by combining several weak prediction models. Decision trees, which are sequentially trained to reduce errors and increase accuracy, are commonly used as these weak models. Gradient boosting can efficiently capture intricate correlations between features by combining several decision tree regressors or decision tree classifiers.
Gradient boosting's capacity to iteratively minimize the loss function is one of its main advantages. One loss function used to assess how well a machine learning model matches actual data is Mean Squared Error (MSE). MSE determines the mean of the squared discrepancies between the observed and expected values.

Let's see how Gradient Boosting works for regression problems. (Complete Home Price Prediction Calculation)
10 observations • 3 independent variables • 3 decision trees
We want to predict a home's price using three independent variables.
| House | X₁ Size (sq ft) | X₂ Bedrooms | X₃ Age | Y Price ($000s) |
|---|---|---|---|---|
| 1 | 1000 | 2 | 30 | 180 |
| 2 | 1200 | 2 | 20 | 210 |
| 3 | 1500 | 3 | 15 | 260 |
| 4 | 1800 | 3 | 10 | 320 |
| 5 | 2000 | 4 | 8 | 360 |
| 6 | 2200 | 4 | 5 | 400 |
| 7 | 2500 | 4 | 3 | 450 |
| 8 | 2800 | 5 | 2 | 510 |
| 9 | 3000 | 5 | 1 | 550 |
| 10 | 3200 | 5 | 0 | 590 |
Gradient Boosting builds decision trees sequentially. Each new tree tries to correct the errors made by the previous model.
For squared-error regression, the initial prediction is the mean of all target values.
Our prices are:
180 + 210 + 260 + 320 + 360 + 400 + 450 + 510 + 550 + 590
$383,000
Because F₀ = 383, every house initially receives the same prediction.
| House | Actual Y | Initial Prediction F₀ |
|---|---|---|
| 1 | 180 | 383 |
| 2 | 210 | 383 |
| 3 | 260 | 383 |
| 4 | 320 | 383 |
| 5 | 360 | 383 |
| 6 | 400 | 383 |
| 7 | 450 | 383 |
| 8 | 510 | 383 |
| 9 | 550 | 383 |
| 10 | 590 | 383 |
The residual tells us how far our prediction is from the actual value.
The model predicted $203,000 too high.
The model predicted $207,000 too low.
| House | Actual | F₀ | Residual |
|---|---|---|---|
| 1 | 180 | 383 | −203 |
| 2 | 210 | 383 | −173 |
| 3 | 260 | 383 | −123 |
| 4 | 320 | 383 | −63 |
| 5 | 360 | 383 | −23 |
| 6 | 400 | 383 | +17 |
| 7 | 450 | 383 | +67 |
| 8 | 510 | 383 | +127 |
| 9 | 550 | 383 | +167 |
| 10 | 590 | 383 | +207 |
Tree 1 uses the house-size variable X₁.
For this teaching example, we use the split:
This means: Is the house size less than or equal to 2,100 square feet?
Houses 1–5 have residuals:
A regression tree predicts the average residual in the leaf.
Houses 6–10 have residuals:
We use a learning rate:
The learning rate controls how much of the tree's correction is added to the model.
| House | Actual | F₀ | Tree 1 | 0.5 × Tree 1 | F₁ |
|---|---|---|---|---|---|
| 1 | 180 | 383 | −117 | −58.5 | 324.5 |
| 2 | 210 | 383 | −117 | −58.5 | 324.5 |
| 3 | 260 | 383 | −117 | −58.5 | 324.5 |
| 4 | 320 | 383 | −117 | −58.5 | 324.5 |
| 5 | 360 | 383 | −117 | −58.5 | 324.5 |
| 6 | 400 | 383 | 117 | 58.5 | 441.5 |
| 7 | 450 | 383 | 117 | 58.5 | 441.5 |
| 8 | 510 | 383 | 117 | 58.5 | 441.5 |
| 9 | 550 | 383 | 117 | 58.5 | 441.5 |
| 10 | 590 | 383 | 117 | 58.5 | 441.5 |
We now calculate errors using the new predictions.
| House | Actual | F₁ | New Residual |
|---|---|---|---|
| 1 | 180 | 324.5 | −144.5 |
| 2 | 210 | 324.5 | −114.5 |
| 3 | 260 | 324.5 | −64.5 |
| 4 | 320 | 324.5 | −4.5 |
| 5 | 360 | 324.5 | +35.5 |
| 6 | 400 | 441.5 | −41.5 |
| 7 | 450 | 441.5 | +8.5 |
| 8 | 510 | 441.5 | +68.5 |
| 9 | 550 | 441.5 | +108.5 |
| 10 | 590 | 441.5 | +148.5 |
Tree 2 uses:
We use the split:
| House | Actual | F₂ | Residual |
|---|---|---|---|
| 1 | 180 | 283.5 | −103.5 |
| 2 | 210 | 283.5 | −73.5 |
| 3 | 260 | 283.5 | −23.5 |
| 4 | 320 | 283.5 | +36.5 |
| 5 | 360 | 468.833 | −108.833 |
| 6 | 400 | 468.833 | −68.833 |
| 7 | 450 | 468.833 | −18.833 |
| 8 | 510 | 468.833 | +41.167 |
| 9 | 550 | 468.833 | +81.167 |
| 10 | 590 | 468.833 | +121.167 |
Tree 3 uses the third independent variable:
We use:
| House | Actual | F₀ | Tree 1 | Tree 2 | Tree 3 | Final F₃ |
|---|---|---|---|---|---|---|
| 1 | 180 | 383 | −117 | −82 | −41 | 263.00 |
| 2 | 210 | 383 | −117 | −82 | −41 | 263.00 |
| 3 | 260 | 383 | −117 | −82 | −41 | 263.00 |
| 4 | 320 | 383 | −117 | −82 | −41 | 263.00 |
| 5 | 360 | 383 | 117 | 54.667 | 7.833 | 472.75 |
| 6 | 400 | 383 | 117 | 54.667 | 7.833 | 472.75 |
| 7 | 450 | 383 | 117 | 54.667 | 7.833 | 472.75 |
| 8 | 510 | 383 | 117 | 54.667 | 7.833 | 472.75 |
| 9 | 550 | 383 | 117 | 54.667 | 7.833 | 472.75 |
| 10 | 590 | 383 | 117 | 54.667 | 7.833 | 472.75 |
House 8 has:
Since:
Tree 1 gives:
Therefore:
Therefore:
Actual Price = $510,000
Error = $37,250
| House | Actual | Prediction | Error |
|---|---|---|---|
| 1 | 180 | 263.00 | −83.00 |
| 2 | 210 | 263.00 | −53.00 |
| 3 | 260 | 263.00 | −3.00 |
| 4 | 320 | 263.00 | +57.00 |
| 5 | 360 | 472.75 | −112.75 |
| 6 | 400 | 472.75 | −72.75 |
| 7 | 450 | 472.75 | −22.75 |
| 8 | 510 | 472.75 | +37.25 |
| 9 | 550 | 472.75 | +77.25 |
| 10 | 590 | 472.75 | +117.25 |
Mean Squared Error measures the average squared prediction error.
Sum of squared errors:
Approximately $72,510
In our example: F₀ = 383
Start with a simple prediction.
↓
Find the errors.
↓
Build a tree to correct those errors.
↓
Apply only part of the correction using the learning rate.
↓
Find the remaining errors.
↓
Build another tree.
↓
Continue until the model has enough trees.
Tree 2 does NOT learn the original errors. It learns the errors remaining after Tree 1.
Tree 3 does NOT learn the original errors either. It learns the errors remaining after Tree 1 and Tree 2.
This sequential correction is the core idea behind Gradient Boosting.
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_absolute_error, r2_score # ----------------------------------- # 1. Load data from Excel # ----------------------------------- data = pd.read_excel("product_data.xlsx") print("Dataset Preview:") print(data.head()) # ----------------------------------- # 2. Define features and target # ----------------------------------- X = data[['Production_Cost', 'Advertising_Spend', 'Demand_Level']] y = data['Product_Price'] # ----------------------------------- # 3. Split into training and testing # ----------------------------------- X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=42 ) ## What is random_state? #train_test_split randomly shuffles the dataset before splitting. #Without random_state: #Each run → different split #Model performance changes slightly #With random_state=42: #Same rows go to train/test every time #Results are reproducible # ----------------------------------- # 4: Train the Gradient Boosting model # ----------------------------------- model = GradientBoostingRegressor( n_estimators=200, learning_rate=0.05, max_depth=3, random_state=42 ) model.fit(X_train, y_train) # ----------------------------------- # 5: Make predictions & evaluate # ----------------------------------- y_pred = model.predict(X_test) print("MAE:", mean_absolute_error(y_test, y_pred)) print("R² score:", r2_score(y_test, y_pred)) # ----------------------------------- # 6. Predict price for a new product # ----------------------------------- new_product = [[65, 18, 275]] # Production Cost, Advertising Spend, Demand Level predicted_price = model.predict(new_product) print("Predicted Product Price:", predicted_price[0])
USE CASE 2: Use Gradient Boosting with scikit-learn to predict the Student Grade. The 'Hours_Studied, 'Attendance_%', 'Previous_Score' are the independent variables.
import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_absolute_error, r2_score # ----------------------------------- # 1. Load data from Excel # ----------------------------------- #sample data can be exported to #excel from the URL # https://pythonPlaza.com/linear_school_grade_data.html data = pd.read_excel("student_data.xlsx") print("Dataset Preview:") print(data.head()) # ----------------------------------- # 2. Define features and target # ----------------------------------- X = data[['Hours_Studied', 'Attendance_%', 'Previous_Score']] y = data['Final_Grade'] # ----------------------------------- # 3. Split into training and testing # ----------------------------------- X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=42 ) ## What is random_state? #train_test_split randomly shuffles the dataset before splitting. #Without random_state: #Each run → different split #Model performance changes slightly #With random_state=42: #Same rows go to train/test every time #Results are reproducible # ----------------------------------- # 4: Train the Gradient Boosting model # ----------------------------------- model = GradientBoostingRegressor( n_estimators=200, learning_rate=0.05, max_depth=3, random_state=42 ) model.fit(X_train, y_train) # ----------------------------------- # 5: Make predictions & evaluate # ----------------------------------- y_pred = model.predict(X_test) print("MAE:", mean_absolute_error(y_test, y_pred)) print("R² score:", r2_score(y_test, y_pred)) Example: Predict a new student’s grade # New student: [hours_studied, attendance %, previous_score] new_student = np.array([[6, 85, 78]]) predicted_grade = model.predict(new_student) print("Predicted final grade:", predicted_grade[0])
USE CASE 3: Use Gradient Boosting with scikit-learn to predict the Profit Optimization. The Price (P), Advertising (A), Units Sold (Q) are the independent variables, and Profit is the dependent variable.
import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_absolute_error, r2_score # ----------------------------------- # 1. Load data from Excel # ----------------------------------- #sample data can be exported to #excel from the URL Get the Profit Optimization data in Excel data = pd.read_excel("profit_optimization.xlsx") print("Dataset Preview:") print(data.head()) # ----------------------------------- # 2. Define features and target Price (P) # ----------------------------------- X = data[['Price', 'Advertising', 'Units_Sold']] y = data['Profit'] # ----------------------------------- # 3. Split into training and testing # ----------------------------------- X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=42 ) ## What is random_state? #train_test_split randomly shuffles the dataset before splitting. #Without random_state: #Each run → different split #Model performance changes slightly #With random_state=42: #Same rows go to train/test every time #Results are reproducible # ----------------------------------- # 4: Train the Gradient Boosting model # ----------------------------------- model = GradientBoostingRegressor( n_estimators=200, learning_rate=0.05, max_depth=3, random_state=42 ) model.fit(X_train, y_train) # ----------------------------------- # 5: Make predictions & evaluate # ----------------------------------- y_pred = model.predict(X_test) print("MAE:", mean_absolute_error(y_test, y_pred)) print("R² score:", r2_score(y_test, y_pred)) #Predict profit for a new business strategy # Example: Price = 15, Advertising = 165, Units Sold = 460 new_strategy = np.array([[15, 165, 460]]) predicted_profit = model.predict(new_strategy) print("Predicted profit:", predicted_profit[0])
USE CASE 4: Use Gradient Boosting with scikit-learn to predict the Patient Response. The Dosage (mg), Age (yrs), Weight (lbs) are the independent variables, and Patient Response is the dependent variable.
import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_absolute_error, r2_score # ----------------------------------- # 1. Load data from Excel # ----------------------------------- #sample data can be exported to #excel from the URL Get the Patient Response Data in Excel data = pd.read_excel("patient_dosage_response.xlsx") print("Dataset Preview:") print(data.head()) # ----------------------------------- # 2. Define features and target Price (P) # ----------------------------------- X = data[['Dosage', 'Age', 'Weight']] y = data['Patient_Response'] # ----------------------------------- # 3. Split into training and testing # ----------------------------------- X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=42 ) ## What is random_state? #train_test_split randomly shuffles the dataset before splitting. #Without random_state: #Each run → different split #Model performance changes slightly #With random_state=42: #Same rows go to train/test every time #Results are reproducible # ----------------------------------- # 4: Train the Gradient Boosting model # ----------------------------------- model = GradientBoostingRegressor( n_estimators=200, learning_rate=0.05, max_depth=3, random_state=42 ) model.fit(X_train, y_train) # ----------------------------------- # 5: Make predictions & evaluate # ----------------------------------- y_pred = model.predict(X_test) print("MAE:", mean_absolute_error(y_test, y_pred)) print("R² score:", r2_score(y_test, y_pred)) #Predict response for a new patient # New patient: Dosage=72mg, Age=36yrs, Weight=172lbs new_patient = np.array([[72, 36, 172]]) #predicted_response = model.predict(new_patient) print("Predicted patient response:", predicted_response[0])