medium.com 4 min read Original Source

Building a Credit Score Model: Model Selection, Training, and Evaluation

Creating a high-performing credit scoring model isn’t just about picking an algorithm — it’s about designing a comprehensive strategy that ensures accuracy, fairness, and real-world effectiveness. A successful model must not only make precise predictions but also withstand the complexities of real-world credit risk assessment. From carefully selecting the right machine learning models to fine-tuning their performance through data preprocessing, hyperparameter optimization, and validation, every decision impacts the model’s ability to drive responsible lending.

Model Selection: Choosing the Right Algorithm

Since credit scoring is a classification problem with an imbalanced dataset (more good borrowers than bad ones), model choice is critical. Some models naturally handle imbalance, while others require additional techniques like resampling or class weighting.

Model-Specific Imbalance Handling

For a credit score model, tree-based models like XGBoost and LightGBM are the best choices due to their ability to handle non-linearity, missing data, and feature importance analysis.

Best Overall: XGBoost → Handles imbalance with scale_pos_weight, no need for SMOTE.

Train-Test Split

Since credit scoring datasets are often imbalanced, it’s essential to use stratified sampling when splitting the data. This ensures that both the majority and minority classes are proportionally represented in the training and test sets, preventing skewed model performance.

# stratified splitting

from sklearn.model_selection import train_test_split

# Split the dataset (80% train, 20% test) with stratification
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size=0.2,
                                                    stratify=y,
                                                    random_state=42)
# stratified splitting

from sklearn.model_selection import train_test_split

# Split the dataset (80% train, 20% test) with stratification
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size=0.2,
                                                    stratify=y,
                                                    random_state=42)

Why Stratify?
Stratification ensures that both majority and minority classes (0 and 1) are proportionally represented in the train/test sets. This prevents the model from learning a biased distribution and improves generalization.

Why an 80–20 Split?
An 80–20 split maintains a practical balance — enough data for the model to learn effectively while preserving a significant portion for evaluation. This helps assess real-world performance without overfitting to training data.

Handle Class Imbalance (Before Training)

Class imbalance is a major challenge in credit scoring models, as the number of default cases (TARGET=1) is significantly lower compared to non-default cases (TARGET=0). In the dataset, default cases make up only 8.07% of the data. Training a model without addressing this imbalance can lead to biased predictions, where the model favors the majority class and fails to detect high-risk borrowers effectively.

Instead of oversampling the minority class or undersampling the majority class, which can introduce bias or information loss, XGBoost provides a built-in solution: scale_pos_weight. This parameter helps balance the impact of each class during training.

Calculating scale_pos_weight
It can determine the appropriate value by scale_pos_weight using the ratio of majority to minority class instances:

# XGBoost scale_pos_weight

# Compute class weight
scale_pos_weight = len(y_train[y_train == 0]) / len(y_train[y_train == 1])
print(scale_pos_weight)
# XGBoost scale_pos_weight

# Compute class weight
scale_pos_weight = len(y_train[y_train == 0]) / len(y_train[y_train == 1])
print(scale_pos_weight)

In this case, the calculated scale_pos_weight is 11.4, meaning XGBoost will assign 11.4 times more weight to the minority class (TARGET=1) than the majority class (TARGET=0). This adjustment helps improve the model’s sensitivity to default cases, leading to more balanced and effective predictions.

Why scale_pos_weight?

  • Prevents the model from ignoring minority cases (which would happen if the dataset remains unbalanced).
  • Avoids the pitfalls of oversampling/undersampling, which can distort real-world data distributions.
  • Improves recall for high-risk borrowers, ensuring that the model correctly identifies default probabilities.

By leveraging scale_pos_weight, it ensures that the model remains both fair and effective, detecting potential defaults without overcompensating for imbalance in ways that might distort real-world trends.

Train XGBoost Model

import xgboost as xgb
from xgboost import callback
import time

# Define the XGBoost model
model = xgb.XGBClassifier(
    n_estimators=1000,  # Start with 1000 trees
    learning_rate=0.05,  # Lower learning rate for stability
    max_depth=6,         # Control overfitting
    subsample=0.8,       # Avoid overfitting by using 80% of data per tree
    colsample_bytree=0.8, # Feature selection
    scale_pos_weight=scale_pos_weight,  # Handle imbalance
    objective='binary:logistic',
    eval_metric='auc',
    random_state=42,
    early_stopping_rounds=50
)

# Train the model using callbacks and sleep calls
model.fit(
    X_train, y_train,
    eval_set=[(X_train, y_train), (X_test, y_test)],
    verbose=100
)
import xgboost as xgb
from xgboost import callback
import time

# Define the XGBoost model
model = xgb.XGBClassifier(
    n_estimators=1000,  # Start with 1000 trees
    learning_rate=0.05,  # Lower learning rate for stability
    max_depth=6,         # Control overfitting
    subsample=0.8,       # Avoid overfitting by using 80% of data per tree
    colsample_bytree=0.8, # Feature selection
    scale_pos_weight=scale_pos_weight,  # Handle imbalance
    objective='binary:logistic',
    eval_metric='auc',
    random_state=42,
    early_stopping_rounds=50
)

# Train the model using callbacks and sleep calls
model.fit(
    X_train, y_train,
    eval_set=[(X_train, y_train), (X_test, y_test)],
    verbose=100
)

Early stopping prevents overfitting if validation AUC stops improving. eval_set shows training progress on both train and test sets.

Performance Metrics (AUC Scores)

  • Training AUC: 0.94695
  • Validation AUC: 0.86755

Interpretation:

  • The model performs well on the training set (high AUC of ~0.95).
  • The validation AUC is slightly lower (~0.8675), but not dropping drastically, indicating no severe overfitting.
  • The gap suggests some overfitting, which could be mitigated with further tuning.

Early Stopping Triggered at Iteration 644

  • Training was stopped early as the validation score stopped improving.
  • Adding more trees wouldn’t enhance performance.

Model Evaluation & Interpretation

# Evaluate Model Performance

from sklearn.metrics import classification_report, roc_auc_score

# Predict
y_pred = model.predict(X_test)
y_pred_proba = model.predict_proba(X_test)[:,1]

# Classification Report
print(classification_report(y_test, y_pred))

# AUC Score (better for imbalanced data)
print("AUC Score:", roc_auc_score(y_test, y_pred_proba))
# Evaluate Model Performance

from sklearn.metrics import classification_report, roc_auc_score

# Predict
y_pred = model.predict(X_test)
y_pred_proba = model.predict_proba(X_test)[:,1]

# Classification Report
print(classification_report(y_test, y_pred))

# AUC Score (better for imbalanced data)
print("AUC Score:", roc_auc_score(y_test, y_pred_proba))

Classification Report Analysis

  • Recall for Class 1 (Defaults) is high (0.72) → Model catches 72% of actual defaults.
  • Precision for Class 1 (Defaults) is very low (0.27) → 73% of predicted defaults are false positives.
  • F1-Score for Class 1 (0.39) is poor → Indicates imbalance between precision & recall.

✅ Good: The model successfully identifies most defaulters.
❌ Bad: Too many false positives → Many customers are wrongly flagged as defaulters.

Potential Issues & Optimization Opportunities

  1. Overfitting Risk
    The gap between training and validation AUC suggests possible overfitting.
  2. Hyperparameter Tuning
    Further tuning could push the validation AUC higher.

For hands-on experience, check out the full Notebook:
📂 GitHub Repo: GitHub Repository

Next Steps

In Part 6, I will explore Hyperparameter Tuning. Stay tuned!

🚀 Let’s Connect! 💼 LinkedIn: Muhammad Faizin