Bird
Raised Fist0
ML Pythonml~20 mins

Bagging concept in ML Python - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Bagging concept
Problem:You have a classification task using the Iris dataset. The current model is a single decision tree that achieves 98% accuracy on training data but only 85% on validation data.
Current Metrics:Training accuracy: 98%, Validation accuracy: 85%
Issue:The model overfits the training data, causing lower accuracy on unseen validation data.
Your Task
Reduce overfitting by using bagging to improve validation accuracy to at least 90% while keeping training accuracy below 95%.
Use the Iris dataset only.
Use decision trees as base learners.
Implement bagging with scikit-learn's BaggingClassifier.
Do not change the dataset or use other models.
Hint 1
Hint 2
Hint 3
Solution
ML Python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn.metrics import accuracy_score

# Load data
iris = load_iris()
X, y = iris.data, iris.target

# Split data
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=42)

# Single decision tree model
single_tree = DecisionTreeClassifier(random_state=42)
single_tree.fit(X_train, y_train)
train_acc_single = accuracy_score(y_train, single_tree.predict(X_train))
val_acc_single = accuracy_score(y_val, single_tree.predict(X_val))

# Bagging with decision trees
bagging_model = BaggingClassifier(
    base_estimator=DecisionTreeClassifier(random_state=42),
    n_estimators=50,
    random_state=42
)
bagging_model.fit(X_train, y_train)
train_acc_bagging = accuracy_score(y_train, bagging_model.predict(X_train))
val_acc_bagging = accuracy_score(y_val, bagging_model.predict(X_val))

print(f"Single Tree - Training Accuracy: {train_acc_single:.2f}, Validation Accuracy: {val_acc_single:.2f}")
print(f"Bagging - Training Accuracy: {train_acc_bagging:.2f}, Validation Accuracy: {val_acc_bagging:.2f}")
Replaced single decision tree with BaggingClassifier using 50 decision trees.
Each tree trained on random subsets of training data to reduce overfitting.
Kept random_state fixed for reproducibility.
Added random_state=42 to base DecisionTreeClassifier for reproducibility.
Results Interpretation

Before Bagging: Training accuracy was very high (98%) but validation accuracy was lower (85%), showing overfitting.

After Bagging: Training accuracy decreased slightly (~93%), but validation accuracy improved (~92%), showing better generalization.

Bagging reduces overfitting by averaging many models trained on different data samples, improving validation accuracy and model stability.
Bonus Experiment
Try increasing the number of trees in the bagging ensemble to 100 and observe the effect on validation accuracy.
💡 Hint
More trees usually improve stability but increase training time. Watch for diminishing returns.

Practice

(1/5)
1. What is the main idea behind bagging in machine learning?
easy
A. Training multiple models on random samples and combining their results
B. Using a single model with all data to avoid randomness
C. Reducing the number of features to simplify the model
D. Increasing the depth of a decision tree to improve accuracy

Solution

  1. Step 1: Understand bagging concept

    Bagging stands for Bootstrap Aggregating, which means training many models on different random samples of the data.
  2. Step 2: Identify the purpose of bagging

    It combines the results of these models to make predictions more stable and accurate.
  3. Final Answer:

    Training multiple models on random samples and combining their results -> Option A
  4. Quick Check:

    Bagging = multiple models + random samples + combine results [OK]
Hint: Bagging = many models + random data + combine predictions [OK]
Common Mistakes:
  • Thinking bagging uses only one model
  • Confusing bagging with feature selection
  • Believing bagging increases model complexity by depth
2. Which of the following is the correct way to create a bagging classifier in Python using scikit-learn?
easy
A. BaggingClassifier(tree=DecisionTreeClassifier(), count=10)
B. BaggingClassifier(base_estimator=DecisionTreeClassifier(), n_estimators=10)
C. BaggingClassifier(estimators=10, base=DecisionTree())
D. Bagging(base=DecisionTree(), estimators=10)

Solution

  1. Step 1: Recall scikit-learn bagging syntax

    The correct class is BaggingClassifier, and it takes base_estimator and n_estimators as parameters.
  2. Step 2: Match parameters to options

    BaggingClassifier(base_estimator=DecisionTreeClassifier(), n_estimators=10) uses base_estimator=DecisionTreeClassifier() and n_estimators=10, which is correct syntax.
  3. Final Answer:

    BaggingClassifier(base_estimator=DecisionTreeClassifier(), n_estimators=10) -> Option B
  4. Quick Check:

    BaggingClassifier + base_estimator + n_estimators = D [OK]
Hint: Use BaggingClassifier(base_estimator, n_estimators) in sklearn [OK]
Common Mistakes:
  • Using wrong parameter names like 'base' or 'estimators'
  • Confusing BaggingClassifier with Bagging
  • Passing parameters in wrong order or with wrong names
3. Consider this Python code using bagging with decision trees:
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier

iris = load_iris()
X, y = iris.data, iris.target

bagging = BaggingClassifier(base_estimator=DecisionTreeClassifier(max_depth=2), n_estimators=5, random_state=42)
bagging.fit(X, y)
predictions = bagging.predict(X)
print(sum(predictions == y))
What does the printed number represent?
medium
A. Number of correct predictions on the training data
B. Number of incorrect predictions on the training data
C. Total number of samples in the dataset
D. Number of decision trees used in the bagging

Solution

  1. Step 1: Understand the code output

    The code prints sum(predictions == y), which counts how many predicted labels match the true labels.
  2. Step 2: Interpret the printed value meaning

    This count is the number of correct predictions on the training data.
  3. Final Answer:

    Number of correct predictions on the training data -> Option A
  4. Quick Check:

    sum(predictions == y) = correct predictions [OK]
Hint: sum(predictions == y) counts correct predictions [OK]
Common Mistakes:
  • Thinking it counts incorrect predictions
  • Confusing it with dataset size
  • Assuming it prints number of trees
4. You wrote this code but get an error:
from sklearn.ensemble import BaggingClassifier
bagging = BaggingClassifier(base_estimator=DecisionTreeClassifier(), n_estimators='10')
bagging.fit(X_train, y_train)
What is the likely cause of the error?
medium
A. BaggingClassifier does not have a fit method
B. base_estimator must be a string, not a model instance
C. n_estimators should be an integer, not a string
D. DecisionTreeClassifier is not imported

Solution

  1. Step 1: Check parameter types

    n_estimators expects an integer number of models, but '10' is a string.
  2. Step 2: Identify error cause

    Passing a string instead of int causes a type error when fitting the model.
  3. Final Answer:

    n_estimators should be an integer, not a string -> Option C
  4. Quick Check:

    n_estimators must be int, not str [OK]
Hint: n_estimators must be int, not quoted string [OK]
Common Mistakes:
  • Passing n_estimators as string instead of int
  • Forgetting to import DecisionTreeClassifier
  • Thinking base_estimator must be string
5. You want to improve a model's stability by using bagging with decision trees. Which approach is best to reduce overfitting while keeping good accuracy?
hard
A. Use many deep trees trained on the same full dataset without sampling
B. Use one very deep decision tree trained on all data
C. Use a single shallow tree with no bagging
D. Use many shallow decision trees trained on random samples and combine their votes

Solution

  1. Step 1: Understand bagging effect on overfitting

    Bagging reduces overfitting by training many models on random samples and averaging results.
  2. Step 2: Choose model depth and sampling

    Shallow trees reduce overfitting individually, and random sampling adds diversity, improving stability and accuracy.
  3. Final Answer:

    Use many shallow decision trees trained on random samples and combine their votes -> Option D
  4. Quick Check:

    Bagging + shallow trees + random samples = less overfitting [OK]
Hint: Bagging + shallow trees + random samples = stable, accurate model [OK]
Common Mistakes:
  • Using one deep tree causes overfitting
  • Training many deep trees on full data lacks diversity
  • Ignoring bagging and using single tree