0% found this document useful (0 votes)
14 views7 pages

Credit Risk Prediction Model Development

The project aims to develop a machine-learning model to predict loan defaults using the German Credit dataset, focusing on preprocessing, feature engineering, and model evaluation metrics. Key objectives include cleaning data, training classifiers, handling class imbalance, and deploying the model. The final output includes performance metrics such as accuracy and ROC-AUC, along with visualizations like confusion matrices and feature importance plots.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views7 pages

Credit Risk Prediction Model Development

The project aims to develop a machine-learning model to predict loan defaults using the German Credit dataset, focusing on preprocessing, feature engineering, and model evaluation metrics. Key objectives include cleaning data, training classifiers, handling class imbalance, and deploying the model. The final output includes performance metrics such as accuracy and ROC-AUC, along with visualizations like confusion matrices and feature importance plots.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PREDICTIVE ANALYTICS LAB PROJECT

AIM :
To build a machine-learning model that predicts whether a loan
applicant will default (binary classification), and to evaluate the model using
standard metrics (accuracy, precision, recall, F1, AUC-ROC). Also
demonstrate preprocessing, feature engineering, imbalance handling, model
explanation, and a simple deployment demo.

OBJECTIVES:
1. Acquire and explore a real credit dataset.
2. Clean and preprocess the data: missing values, encoding categorical
variables, scaling numeric features.
3. Engineer and select predictive features (e.g., income ratios, credit
history flags).
4. Train several classifiers (Logistic Regression, Random Forest, XGBoost)
and compare performance.
5. Handle class imbalance (SMOTE, class weighting) and evaluate effects.
6. Use model explainability tools (SHAP or feature importances) to
interpret decisions.
7. Package the model for deployment (Flask API or simple pickle + demo
notebook).

Description / Dataset :
German Credit (UCI Statlog) — small, classic dataset (1,000 instances, 20
attributes) for “good/bad” credit risk classification. Good for quick
experiments and interpretability work.

Typical features (varies by dataset):

 Age, Sex, Job type, Housing status

 Credit amount, Duration (months), Purpose of loan

 History of credit, Existing credits at bank, Number of dependents

 Target: credit_risk (Good/Bad or 0/1)


(Full variable descriptions are on the dataset pages.)
PROGRAM:
# credit_risk_with_visuals.py

# Requirements: pandas, numpy, scikit-learn, imbalanced-learn, xgboost,


shap, matplotlib, seaborn, joblib

import pandas as pd

import numpy as np

import [Link] as plt

import seaborn as sns

from sklearn.model_selection import train_test_split

from [Link] import StandardScaler, OneHotEncoder

from [Link] import ColumnTransformer

from [Link] import Pipeline

from [Link] import SimpleImputer

from [Link] import classification_report, roc_auc_score,


confusion_matrix, roc_curve

from imblearn.over_sampling import SMOTE

from [Link] import Pipeline as ImbPipeline

from xgboost import XGBClassifier

import joblib

# 1) Load dataset

df = pd.read_csv("german_credit_data.csv") # replace with your dataset


# 2) Target distribution visualization

[Link](figsize=(6,4))

[Link](x='target', data=df, palette="Set2")

[Link]("Target Distribution (Good vs Bad Credit)")

[Link]("Credit Risk")

[Link]("Count")

[Link]("target_distribution.png")

[Link]()

# 3) Define features/target

y = df['target'] # 0 = good, 1 = bad (check dataset encoding)

X = [Link](columns=['target', 'ID'], errors='ignore')

# 4) Split data

X_train, X_test, y_train, y_test = train_test_split(

X, y, test_size=0.2, random_state=42, stratify=y

# 5) Preprocessing

num_cols = X.select_dtypes(include=['int64','float64']).[Link]()

cat_cols = X.select_dtypes(include=['object','category']).[Link]()

num_pipeline = Pipeline([

('imputer', SimpleImputer(strategy='median')),

('scaler', StandardScaler())
])

cat_pipeline = Pipeline([

('imputer', SimpleImputer(strategy='most_frequent')),

('onehot', OneHotEncoder(handle_unknown='ignore', sparse=False))

])

preprocessor = ColumnTransformer([

('num', num_pipeline, num_cols),

('cat', cat_pipeline, cat_cols)

])

# 6) Model pipeline with SMOTE

clf = XGBClassifier(use_label_encoder=False, eval_metric='logloss',


random_state=42)

pipe = ImbPipeline([

('preproc', preprocessor),

('smote', SMOTE(random_state=42)),

('clf', clf)

])

# 7) Train

[Link](X_train, y_train)

# 8) Predictions

y_pred = [Link](X_test)

y_proba = pipe.predict_proba(X_test)[:,1]
print(classification_report(y_test, y_pred))

print("ROC-AUC:", roc_auc_score(y_test, y_proba))

# 9) Confusion matrix heatmap

cm = confusion_matrix(y_test, y_pred)

[Link](figsize=(5,4))

[Link](cm, annot=True, fmt="d", cmap="Blues",


xticklabels=["Good","Bad"], yticklabels=["Good","Bad"])

[Link]("Confusion Matrix")

[Link]("Predicted")

[Link]("Actual")

[Link]("confusion_matrix.png")

[Link]()

# 10) ROC Curve

fpr, tpr, thresholds = roc_curve(y_test, y_proba)

[Link](figsize=(6,5))

[Link](fpr, tpr, label=f"AUC = {roc_auc_score(y_test, y_proba):.2f}")

[Link]([0,1],[0,1],'k--')

[Link]("False Positive Rate")

[Link]("True Positive Rate")

[Link]("ROC Curve")

[Link](loc="lower right")

[Link]("roc_curve.png")

[Link]()
# 11) Feature importance (from XGBoost)

model = pipe.named_steps['clf']

importance = model.feature_importances_

# Feature names after preprocessing

preproc = pipe.named_steps['preproc']

ohe_cols = []

if cat_cols:

ohe = preproc.named_transformers_['cat'].named_steps['onehot']

ohe_cols = ohe.get_feature_names_out(cat_cols)

feature_names = list(num_cols) + list(ohe_cols)

# Plot top 10 important features

sorted_idx = [Link](importance)[-10:]

[Link](figsize=(8,6))

[Link]([Link](feature_names)[sorted_idx], importance[sorted_idx],
color="green")

[Link]("Top 10 Feature Importances (XGBoost)")

[Link]("Importance Score")

[Link]("feature_importance.png")

[Link]()

# 12) Save trained model

[Link](pipe, "credit_risk_model.pkl")
OUTPUT:

(1000, 21) # shape of dataset (example)

Target distribution:

0 700

1 300

Classification report:

precision recall f1-score support

0 0.78 0.85 0.81 140

1 0.66 0.52 0.58 60

Accuracy: 0.75

ROC-AUC: 0.81

Common questions

Powered by AI

Visualizing the ROC curve provides several advantages, as it enables the observation of a model's ability to distinguish between classes at different threshold settings. The curve plots the true positive rate against the false positive rate, and the area under the curve (AUC) quantifies the overall performance, with higher AUC values indicating better model discrimination. Visual inspection can reveal issues such as a lack of balance between sensitivity and specificity and help select an optimal threshold that balances trade-offs in real-world applications of credit risk prediction .

Model explainability is crucial in credit risk prediction because it helps stakeholders, such as lenders and regulatory bodies, understand the decision-making process behind loan approvals or denials. It increases trust in the model by providing insights into which factors are driving predictions. Techniques like SHAP (SHapley Additive exPlanations) values and feature importances are commonly used to interpret model decisions. SHAP values provide a unified measure of feature contribution for individual predictions, while feature importance scores from models such as XGBoost indicate which features most influence the model's output overall. Explainability allows for transparency and potential bias identification, which is critical in financial decision-making .

The XGBoost model is advantageous for credit risk classification due to its robustness and high efficiency in handling structured data. It can capture complex patterns through gradient boosting and manages overfitting with strong regularization capabilities. Furthermore, its feature importance scores aid in model interpretability, enabling stakeholders to understand the decision process. XGBoost's ability to handle imbalanced datasets effectively, especially when combined with techniques like SMOTE, makes it well-suited for credit risk tasks where data distribution can be highly skewed .

Saving a trained model using joblib plays a crucial role in the model deployment phase by enabling the persistence of model architecture and weights for future use. It allows the saved model to be easily reloaded in deployment environments, reducing the need for retraining and ensuring consistency across testing and operational phases. In the context of a credit risk prediction project, deploying the model through a Flask API or similar interface facilitates real-time predictions, integrating seamlessly into existing systems for practical application in loan approval processes .

A pipeline is used to streamline the process by concatenating data preprocessing, model training, and evaluation steps into a single, reusable sequence. For credit risk prediction, a pipeline combines processes like data imputation, encoding, scaling, and the application of SMOTE in a preprocessor step. It then integrates the model training phase using classifiers such as XGBoost. This unified structure ensures consistent data handling and avoids potential leakage between preprocessing and model training phases, enhancing reproducibility and robustness of results .

Feature engineering can significantly improve the predictive performance by transforming raw data into informative inputs that better represent the underlying patterns needed for machine learning algorithms. In the context of credit risk assessment, this may include creating new features such as income ratios, credit history flags, or usage patterns. These engineered features can provide more significant insights into a borrower's financial health and behavior, which are critical for assessing credit risk. Additionally, selecting only the most indicative features reduces noise and computational complexity, enhancing model accuracy and interpretability .

The main steps involved in preprocessing a dataset for predicting loan defaults include handling missing values, encoding categorical variables, and scaling numeric features. Specifically, missing values are imputed using strategies such as median for numerical data and most frequent for categorical data. Categorical variables are encoded using one-hot encoding to convert them into a numerical format, which is essential for machine learning algorithms. Numeric features are scaled using methods like standard scaling to ensure uniformity in data input, improving model performance. These preprocessing steps create a well-structured input dataset suitable for training and evaluating machine-learning models .

Metrics used to evaluate the performance of a credit risk prediction model include accuracy, precision, recall, F1-score, and ROC-AUC. Accuracy indicates the proportion of total correct predictions. Precision measures the proportion of true positive instances among the predicted positives and indicates the relevancy of positive classifications. Recall, or sensitivity, assesses the ability of the model to capture all actual positive instances. The F1-score is the harmonic mean of precision and recall, balancing the two metrics. ROC-AUC represents the model's ability to distinguish between classes and is a robust measure for evaluating binary classifiers .

Using a training-validation split is significant because it allows the model to be trained on a subset of the data and validated on unseen data, ensuring that it generalizes well to new, unseen examples. In developing a credit risk model, the dataset is split into training and test sets, with a typical ratio being 80% for training and 20% for testing. Stratification during splitting ensures that the distribution of the target variable remains consistent across both subsets. This split provides an unbiased evaluation of the model's performance and helps to fine-tune model parameters to avoid overfitting .

SMOTE (Synthetic Minority Over-sampling Technique) is used to address class imbalance by generating synthetic samples for the minority class, which in this case is the 'Bad' credit risk category. By enlarging the set of minority class samples, SMOTE aims to balance the class distribution, which helps improve the model's ability to predict the minority class correctly. This results in improved precision and recall for the minority class and better overall model performance metrics such as the F1 score and ROC-AUC. The use of SMOTE is integrated within the pipeline, which applies it during training to ensure that the model is trained on a balanced dataset .

You might also like