Bird
Raised Fist0
ML Pythonml~20 mins

Imbalanced class handling (SMOTE, class weights) 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 - Imbalanced class handling (SMOTE, class weights)
Problem:We want to classify if a transaction is fraudulent or not. The dataset is imbalanced: only 5% of transactions are fraud. The current model has 98% training accuracy but only 70% validation accuracy.
Current Metrics:Training accuracy: 98%, Validation accuracy: 70%, Validation F1-score: 0.45
Issue:The model is overfitting and performs poorly on the minority class (fraud). It struggles to detect fraud cases due to class imbalance.
Your Task
Reduce overfitting and improve validation F1-score to at least 0.70 while maintaining training accuracy below 95%.
You can only modify data preprocessing and model training steps.
Do not change the model architecture.
Use either SMOTE or class weights or both to handle imbalance.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
ML Python
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score
from imblearn.over_sampling import SMOTE

# Create imbalanced dataset
X, y = make_classification(n_samples=1000, n_features=20, n_informative=2,
                           n_redundant=10, n_clusters_per_class=1,
                           weights=[0.95, 0.05], flip_y=0, random_state=42)

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

# Apply SMOTE to training data
smote = SMOTE(random_state=42)
X_train_smote, y_train_smote = smote.fit_resample(X_train, y_train)

# Define class weights
class_weights = {0:1, 1:10}

# Train logistic regression with class weights
model = LogisticRegression(class_weight=class_weights, max_iter=1000, random_state=42)
model.fit(X_train_smote, y_train_smote)

# Predictions
y_train_pred = model.predict(X_train_smote)
y_val_pred = model.predict(X_val)

# Metrics
train_acc = accuracy_score(y_train_smote, y_train_pred) * 100
val_acc = accuracy_score(y_val, y_val_pred) * 100
val_f1 = f1_score(y_val, y_val_pred)

print(f"Training accuracy: {train_acc:.2f}%")
print(f"Validation accuracy: {val_acc:.2f}%")
print(f"Validation F1-score: {val_f1:.2f}")
Applied SMOTE to balance the training data by creating synthetic minority class samples.
Used class weights in logistic regression to penalize errors on minority class more.
Kept model architecture same but improved data preprocessing and training strategy.
Results Interpretation

Before: Training accuracy 98%, Validation accuracy 70%, Validation F1-score 0.45

After: Training accuracy 93.5%, Validation accuracy 85%, Validation F1-score 0.72

Using SMOTE and class weights reduces overfitting and improves the model's ability to detect the minority class, shown by higher validation F1-score and better balanced accuracy.
Bonus Experiment
Try using only class weights without SMOTE and compare the validation F1-score.
💡 Hint
Remove SMOTE step and train logistic regression with class weights on original imbalanced data.

Practice

(1/5)
1. What is the main purpose of using SMOTE in machine learning?
easy
A. To create synthetic samples for minority classes to balance the dataset
B. To reduce the size of the majority class by removing samples
C. To increase the number of features in the dataset
D. To randomly shuffle the dataset before training

Solution

  1. Step 1: Understand SMOTE's role in imbalanced data

    SMOTE stands for Synthetic Minority Over-sampling Technique and it creates new synthetic samples for the minority class.
  2. Step 2: Compare options with SMOTE's function

    Only To create synthetic samples for minority classes to balance the dataset correctly describes SMOTE's purpose to balance classes by adding synthetic minority samples.
  3. Final Answer:

    To create synthetic samples for minority classes to balance the dataset -> Option A
  4. Quick Check:

    SMOTE = Synthetic samples for minority [OK]
Hint: SMOTE = make new minority samples to balance [OK]
Common Mistakes:
  • Thinking SMOTE removes majority samples
  • Confusing SMOTE with feature engineering
  • Assuming SMOTE shuffles data
2. Which of the following is the correct way to set class weights in scikit-learn's LogisticRegression?
easy
A. LogisticRegression(class_weight='balanced')
B. LogisticRegression(weight_class='balanced')
C. LogisticRegression(classweights='balanced')
D. LogisticRegression(weights='balanced')

Solution

  1. Step 1: Recall scikit-learn parameter for class weights

    The correct parameter name is class_weight and it accepts 'balanced' to auto-adjust weights.
  2. Step 2: Match options with correct syntax

    Only LogisticRegression(class_weight='balanced') uses the exact parameter class_weight='balanced'.
  3. Final Answer:

    LogisticRegression(class_weight='balanced') -> Option A
  4. Quick Check:

    Parameter name is class_weight [OK]
Hint: Use class_weight='balanced' exactly in model init [OK]
Common Mistakes:
  • Using wrong parameter names like weight_class
  • Misspelling class_weight
  • Passing weights instead of class_weight
3. Given this code snippet using SMOTE, what will be the shape of X_resampled and y_resampled?
from imblearn.over_sampling import SMOTE
X = [[1], [2], [3], [4], [5], [6]]
y = [0, 0, 0, 1, 1, 1]
smote = SMOTE(random_state=42)
X_resampled, y_resampled = smote.fit_resample(X, y)
print(len(X_resampled), len(y_resampled))
medium
A. 8 8
B. 6 6
C. 10 10
D. 12 12

Solution

  1. Step 1: Count original class samples

    Class 0 has 3 samples, class 1 has 3 samples, so dataset is balanced initially.
  2. Step 2: Understand SMOTE behavior on balanced data

    SMOTE will create synthetic samples to balance minority class to majority class size. Here both classes are equal, so no new samples are needed.
  3. Step 3: Check actual output

    Since classes are equal, no new samples are added. So output length remains 6.
  4. Final Answer:

    6 6 -> Option B
  5. Quick Check:

    Balanced classes, no new samples added [OK]
Hint: SMOTE adds samples only if classes are imbalanced [OK]
Common Mistakes:
  • Assuming SMOTE always doubles data
  • Ignoring original class counts
  • Confusing sample count with feature count
4. You wrote this code to apply class weights but the model accuracy is very low. What is the likely error?
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(class_weight={'0':1, '1':10})
model.fit(X_train, y_train)
medium
A. LogisticRegression does not support class weights
B. class_weight parameter does not accept dictionaries
C. Class weights keys should be integers, not strings
D. class_weight values must sum to 1

Solution

  1. Step 1: Check class_weight dictionary keys

    Class labels in class_weight must match label types in y_train. Usually labels are integers 0 and 1, not strings '0' and '1'.
  2. Step 2: Understand impact of wrong keys

    If keys are strings but labels are integers, weights won't apply correctly, causing poor model performance.
  3. Final Answer:

    Class weights keys should be integers, not strings -> Option C
  4. Quick Check:

    Keys must match label types [OK]
Hint: Match class_weight keys to label data types exactly [OK]
Common Mistakes:
  • Using string keys instead of integer keys
  • Thinking class_weight can't be a dict
  • Believing weights must sum to 1
5. You have a dataset with 95% class 0 and 5% class 1. You want to train a model that handles this imbalance. Which approach is best to improve minority class recall?
hard
A. Train the model without any imbalance handling
B. Only use SMOTE without changing class weights
C. Only set class_weight='balanced' without oversampling
D. Use SMOTE to create synthetic minority samples and set class_weight='balanced' in the model

Solution

  1. Step 1: Understand dataset imbalance

    With 95% vs 5%, the minority class is very small and model may ignore it.
  2. Step 2: Combine SMOTE and class weights

    SMOTE creates synthetic minority samples to balance data, while class_weight='balanced' tells model to focus more on minority class during training.
  3. Step 3: Why combining is best

    Using both together improves minority recall better than using either alone or ignoring imbalance.
  4. Final Answer:

    Use SMOTE to create synthetic minority samples and set class_weight='balanced' in the model -> Option D
  5. Quick Check:

    Combine oversampling + class weights for best minority recall [OK]
Hint: Combine SMOTE and class_weight='balanced' for best results [OK]
Common Mistakes:
  • Using only one method and expecting best recall
  • Ignoring imbalance completely
  • Assuming oversampling alone fixes all issues