Certainly! Below is a comprehensive Python script that demonstrates a complete machine learning pipeline for predicting loan_status based on the provided dataset. This script includes data loading, preprocessing, feature engineering, model training, evaluation, and making predictions on a test set. It leverages powerful libraries such as pandas, scikit-learn, and ensures best practices are followed for a robust solution.
Prerequisites
Before running the script, ensure you have the necessary libraries installed. You can install them using pip:
pip install pandas numpy scikit-learn
Complete Python Code
# Import necessary libraries
import pandas as pd
import numpy as np
# Visualization libraries (optional but useful)
import matplotlib.pyplot as plt
import seaborn as sns
# Scikit-learn modules for preprocessing, modeling, and evaluation
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score
from sklearn.preprocessing import OneHotEncoder, StandardScaler, LabelEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, roc_auc_score, confusion_matrix, roc_curve
# Suppress warnings for cleaner output
import warnings
warnings.filterwarnings('ignore')
# 1. Load the Data
# Replace 'train.csv' and 'test.csv' with your actual file paths
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
print("Train Data Shape:", train.shape)
print("Test Data Shape:", test.shape)
# 2. Exploratory Data Analysis (EDA) (Optional but recommended)
# Display first few rows
print(train.head())
# Check for missing values
print("\nMissing Values in Train Data:\n", train.isnull().sum())
print("\nMissing Values in Test Data:\n", test.isnull().sum())
# Summary statistics
print("\nTrain Data Description:\n", train.describe())
# Visualize target distribution
sns.countplot(x='loan_status', data=train)
plt.title('Loan Status Distribution')
plt.show()
# 3. Data Preprocessing
# Define feature columns and target
target = 'loan_status'
ID_col = 'id'
# Features to exclude
exclude_cols = [ID_col, target]
# Separate features and target in training data
X = train.drop(exclude_cols, axis=1)
y = train[target]
# For test data, drop the ID column
X_test = test.drop(ID_col, axis=1)
# Identify categorical and numerical features
categorical_features = ['person_home_ownership', 'loan_intent', 'loan_grade', 'cb_person_default_on_file']
numerical_features = ['person_age', 'person_income', 'person_emp_length',
'loan_amnt', 'loan_int_rate', 'loan_percent_income',
'cb_person_cred_hist_length']
# Handle binary categorical features if any (e.g., 'cb_person_default_on_file')
binary_features = ['cb_person_default_on_file']
# Preprocessing pipelines for numerical and categorical data
numerical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='median')), # Handle missing values
('scaler', StandardScaler()) # Scale features
])
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='most_frequent')), # Handle missing values
('onehot', OneHotEncoder(handle_unknown='ignore')) # One-hot encode categorical variables
])
# Combine preprocessing steps
preprocessor = ColumnTransformer(
transformers=[
('num', numerical_transformer, numerical_features),
('cat', categorical_transformer, categorical_features)
])
# 4. Model Building
# Create a pipeline that combines preprocessing and the classifier
model_pipeline = Pipeline(steps=[
('preprocessor', preprocessor),
('classifier', RandomForestClassifier(random_state=42))
])
# Split the training data into training and validation sets
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y)
print("\nTraining Set Shape:", X_train.shape)
print("Validation Set Shape:", X_val.shape)
# 5. Model Training
# Train the model
model_pipeline.fit(X_train, y_train)
# 6. Model Evaluation
# Predict on validation set
y_pred = model_pipeline.predict(X_val)
y_proba = model_pipeline.predict_proba(X_val)[:, 1]
# Classification report
print("\nClassification Report:\n", classification_report(y_val, y_pred))
# ROC AUC Score
roc_auc = roc_auc_score(y_val, y_proba)
print("ROC AUC Score:", roc_auc)
# Confusion Matrix
conf_matrix = confusion_matrix(y_val, y_pred)
print("\nConfusion Matrix:\n", conf_matrix)
# Plot ROC Curve
fpr, tpr, thresholds = roc_curve(y_val, y_proba)
plt.figure()
plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], 'k--') # Diagonal line
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic')
plt.legend(loc="lower right")
plt.show()
# 7. Hyperparameter Tuning (Optional but Recommended)
# Define parameter grid for GridSearchCV
param_grid = {
'classifier__n_estimators': [100, 200, 300],
'classifier__max_depth': [None, 10, 20, 30],
'classifier__min_samples_split': [2, 5, 10],
'classifier__min_samples_leaf': [1, 2, 4],
'classifier__bootstrap': [True, False]
}
# Initialize GridSearchCV
grid_search = GridSearchCV(
estimator=model_pipeline,
param_grid=param_grid,
cv=5,
n_jobs=-1,
scoring='roc_auc',
verbose=2
)
# Fit GridSearchCV
grid_search.fit(X_train, y_train)
# Best parameters and score
print("\nBest Parameters:", grid_search.best_params_)
print("Best ROC AUC Score from GridSearchCV:", grid_search.best_score_)
# 8. Evaluate the Best Model on Validation Set
# Best model from grid search
best_model = grid_search.best_estimator_
# Predictions with the best model
y_pred_best = best_model.predict(X_val)
y_proba_best = best_model.predict_proba(X_val)[:, 1]
# Classification report
print("\nClassification Report (Best Model):\n", classification_report(y_val, y_pred_best))
# ROC AUC Score
roc_auc_best = roc_auc_score(y_val, y_proba_best)
print("ROC AUC Score (Best Model):", roc_auc_best)
# Confusion Matrix
conf_matrix_best = confusion_matrix(y_val, y_pred_best)
print("\nConfusion Matrix (Best Model):\n", conf_matrix_best)
# 9. Feature Importance (Optional)
# Extract feature importances if the classifier supports it
if hasattr(best_model.named_steps['classifier'], 'feature_importances_'):
# Get feature names after preprocessing
ohe = best_model.named_steps['preprocessor'].named_transformers_['cat'].named_steps['onehot']
cat_features = ohe.get_feature_names_out(categorical_features)
feature_names = numerical_features + list(cat_features)
importances = best_model.named_steps['classifier'].feature_importances_
feature_importances = pd.Series(importances, index=feature_names).sort_values(ascending=False)
# Plot feature importances
plt.figure(figsize=(10, 8))
sns.barplot(x=feature_importances[:10], y=feature_importances.index[:10])
plt.title('Top 10 Feature Importances')
plt.xlabel('Importance Score')
plt.ylabel('Features')
plt.show()
# 10. Make Predictions on Test Set
# Ensure the test set has the same preprocessing as the training set
test_predictions = best_model.predict(X_test)
test_proba = best_model.predict_proba(X_test)[:, 1]
# 11. Prepare Submission File
# Assuming you need to submit 'id' and 'loan_status'
submission = pd.DataFrame({
'id': test[ID_col],
'loan_status': test_predictions
})
# Save to CSV
submission.to_csv('submission.csv', index=False)
print("\nSubmission file 'submission.csv' created successfully.")
Explanation of the Steps
-
Data Loading:
- The script begins by importing the necessary libraries.
- It reads the training and test datasets using
pd.read_csv(). Ensure that the file paths are correct.
-
Exploratory Data Analysis (EDA):
- Displays the first few rows of the training data.
- Checks for missing values in both training and test datasets.
- Provides summary statistics to understand the distribution of numerical features.
- Visualizes the distribution of the target variable
loan_status to assess class balance.
-
Data Preprocessing:
- Separates the target variable
loan_status and excludes the id column from features.
- Identifies categorical and numerical features for separate preprocessing.
- Defines transformation pipelines:
- Numerical Features: Imputes missing values using the median and scales the features using
StandardScaler.
- Categorical Features: Imputes missing values using the most frequent value and applies one-hot encoding.
-
Model Building:
- Combines the preprocessing steps using
ColumnTransformer.
- Constructs a
Pipeline that first preprocesses the data and then applies a RandomForestClassifier.
-
Model Training:
- Splits the training data into training and validation sets using
train_test_split.
- Trains the model pipeline on the training set.
-
Model Evaluation:
- Predicts on the validation set and computes evaluation metrics such as the classification report, ROC AUC score, and the confusion matrix.
- Plots the ROC Curve to visualize model performance.
-
Hyperparameter Tuning:
- Utilizes
GridSearchCV to perform hyperparameter tuning on the RandomForestClassifier.
- Searches across a grid of hyperparameters to find the combination that yields the best ROC AUC score.
-
Evaluating the Best Model:
- Extracts the best model from the grid search and evaluates it on the validation set.
Notes and Best Practices
-
Handling Missing Values: The script uses SimpleImputer to handle missing values. The strategy chosen (median for numerical, most frequent for categorical) is a common starting point, but depending on the dataset, other strategies might be more appropriate.
-
Feature Scaling: Scaling numerical features is essential for algorithms sensitive to the scale of data, although RandomForestClassifier is not particularly sensitive. It's still a good practice, especially if you switch to algorithms like SVM or logistic regression.
-
Encoding Categorical Variables: One-hot encoding is used for nominal categorical variables. Ensure that the categorical variables are indeed nominal; sometimes, ordinal encoding might be more appropriate.
-
Model Selection: RandomForestClassifier is chosen for its robustness and ability to handle both numerical and categorical data. Depending on the problem complexity and data size, other models like Gradient Boosting Machines (e.g., XGBoost, LightGBM) might offer better performance.
-
Cross-Validation: GridSearchCV uses cross-validation to ensure that the hyperparameter tuning does not overfit to a particular train-validation split.
-
Evaluation Metrics: In addition to accuracy, metrics like ROC AUC are crucial, especially in classification problems with imbalanced classes.
-
Feature Importance: Understanding which features are most influential can provide valuable insights and help in feature engineering or selection.
-
Reproducibility: Setting random_state ensures that results are reproducible.
Conclusion
This script provides a solid foundation for a machine learning project involving classification. It follows best practices in data preprocessing, model training, evaluation, and deployment. Depending on specific project requirements and data characteristics, further enhancements and customizations might be necessary.
Feel free to customize the script based on your dataset's nuances and the specific requirements of your problem!