Certainly! Let's work through the steps outlined to develop a predictive model for determining the probability that a client will register a business after communication with the bank. We'll focus on cleaning the dataset, feature engineering, model training, and optimizing for the recall@k metric as specified.
1. Data Cleaning
1.1 Load the Data
Firstly, we'll load the training and test datasets using pandas.
import pandas as pd
# Load datasets
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
1.2 Identify and Drop Columns with Excessive Missing Data
Columns with more than 50% missing values will be dropped.
# Calculate the percentage of missing values for each column
missing_pct = train.isnull().mean() * 100
# Identify columns to drop
cols_to_drop = missing_pct[missing_pct > 50].index.tolist()
print(f"Columns to drop due to high missingness: {cols_to_drop}")
# Drop columns from both train and test datasets
train.drop(columns=cols_to_drop, inplace=True)
test.drop(columns=cols_to_drop, inplace=True)
1.3 Impute Remaining Missing Values
1.3.1 Numeric Features
For numeric features, we'll impute missing values with the median.
from sklearn.impute import SimpleImputer
# Identify numeric features
numeric_features = train.select_dtypes(include=['int64', 'float64']).columns.tolist()
numeric_features.remove('target') # Exclude the target variable
# Impute missing values with median
numeric_imputer = SimpleImputer(strategy='median')
train[numeric_features] = numeric_imputer.fit_transform(train[numeric_features])
test[numeric_features] = numeric_imputer.transform(test[numeric_features])
1.3.2 Categorical Features
For categorical features, we'll fill missing values with the most frequent value.
# Identify categorical features
categorical_features = train.select_dtypes(include=['object', 'category']).columns.tolist()
# Impute missing values with the most frequent value (mode)
categorical_imputer = SimpleImputer(strategy='most_frequent')
train[categorical_features] = categorical_imputer.fit_transform(train[categorical_features])
test[categorical_features] = categorical_imputer.transform(test[categorical_features])
2. Feature Engineering
2.1 Normalize Features with Large Value Ranges
We're going to standardize features to ensure that large value ranges do not adversely affect model training.
from sklearn.preprocessing import StandardScaler
# Initialize scaler
scaler = StandardScaler()
# Fit and transform on training data
train[numeric_features] = scaler.fit_transform(train[numeric_features])
# Transform test data
test[numeric_features] = scaler.transform(test[numeric_features])
2.2 Encode Categorical Variables
We'll convert categorical variables into numeric form using one-hot encoding.
# Concatenate train and test data for consistent encoding
combined = pd.concat([train, test], sort=False)
# One-hot encode categorical features
combined = pd.get_dummies(combined, columns=categorical_features)
# Split back into train and test datasets
train = combined[combined['target'].notnull()]
test = combined[combined['target'].isnull()].drop(columns=['target'])
3. Model Training
3.1 Prepare Features and Target Variable
# Features and target
X = train.drop(columns=['id', 'target'])
y = train['target']
# Test features
X_test = test.drop(columns=['id'])
3.2 Split Data into Training and Validation Sets
We'll use a stratified split to maintain class distribution in both sets.
from sklearn.model_selection import train_test_split
# Split data
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
3.3 Train Models
We'll try Logistic Regression, Random Forest, and Gradient Boosting.
3.3.1 Logistic Regression
from sklearn.linear_model import LogisticRegression
# Initialize model
lr_model = LogisticRegression(max_iter=1000, random_state=42)
# Train model
lr_model.fit(X_train, y_train)
3.3.2 Random Forest
from sklearn.ensemble import RandomForestClassifier
# Initialize model
rf_model = RandomForestClassifier(n_estimators=100, random_state=42)
# Train model
rf_model.fit(X_train, y_train)
3.3.3 Gradient Boosting (XGBoost)
import xgboost as xgb
# Initialize model
xgb_model = xgb.XGBClassifier(
n_estimators=100,
learning_rate=0.1,
max_depth=6,
use_label_encoder=False,
eval_metric='logloss',
random_state=42
)
# Train model
xgb_model.fit(X_train, y_train)
4. Model Evaluation
4.1 Define recall@k Metric
We will define a function to calculate recall@k.
import numpy as np
from sklearn.metrics import recall_score
def recall_at_k(y_true, y_scores, k):
# Determine the number of top k instances
cutoff = int(len(y_scores) * k)
# Get the indices that would sort the array in descending order
idx = np.argsort(-y_scores)
# Create binary predictions with 1s for top k scores
y_preds = np.zeros_like(y_scores)
y_preds[idx[:cutoff]] = 1
# Calculate recall
return recall_score(y_true, y_preds)
4.2 Evaluate Each Model
We'll calculate recall@k for each model on the validation set, focusing on the top 15% of predictions.
k = 0.15 # Top 15%
# Logistic Regression
lr_probs = lr_model.predict_proba(X_val)[:, 1]
lr_recall_k = recall_at_k(y_val.values, lr_probs, k)
print(f'Logistic Regression recall@{k*100:.0f}%: {lr_recall_k:.4f}')
# Random Forest
rf_probs = rf_model.predict_proba(X_val)[:, 1]
rf_recall_k = recall_at_k(y_val.values, rf_probs, k)
print(f'Random Forest recall@{k*100:.0f}%: {rf_recall_k:.4f}')
# XGBoost
xgb_probs = xgb_model.predict_proba(X_val)[:, 1]
xgb_recall_k = recall_at_k(y_val.values, xgb_probs, k)
print(f'XGBoost recall@{k*100:.0f}%: {xgb_recall_k:.4f}')
4.3 Select the Best Model
Based on the recall@k scores, choose the model with the highest performance.
5. Model Optimization
5.1 Hyperparameter Tuning
We can perform hyperparameter tuning on the best model using Grid Search or Random Search, focusing on maximizing recall@k.
Example with Randomized Search for XGBoost
from sklearn.model_selection import RandomizedSearchCV
# Define parameter grid
param_dist = {
'n_estimators': [100, 200, 300],
'max_depth': [4, 6, 8],
'learning_rate': [0.01, 0.1, 0.2],
'subsample': [0.7, 0.8, 1.0],
'colsample_bytree': [0.7, 0.8, 1.0]
}
# Initialize model
xgb_model_tuned = xgb.XGBClassifier(
use_label_encoder=False,
eval_metric='logloss',
random_state=42
)
# Initialize Randomized Search
random_search = RandomizedSearchCV(
estimator=xgb_model_tuned,
param_distributions=param_dist,
n_iter=50,
scoring='recall',
cv=3,
verbose=1,
random_state=42,
n_jobs=-1
)
# Perform Randomized Search
random_search.fit(X_train, y_train)
print(f'Best parameters found: {random_search.best_params_}')
5.2 Retrain Model with Best Parameters
# Retrieve the best model
best_xgb_model = random_search.best_estimator_
# Evaluate on validation set
best_xgb_probs = best_xgb_model.predict_proba(X_val)[:, 1]
best_xgb_recall_k = recall_at_k(y_val.values, best_xgb_probs, k)
print(f'Optimized XGBoost recall@{k*100:.0f}%: {best_xgb_recall_k:.4f}')
6. Final Predictions and Submission
6.1 Make Predictions on Test Data
# Predict probabilities on test data
test_probs = best_xgb_model.predict_proba(X_test)[:, 1]
# Add predictions to the test dataframe
test['probability'] = test_probs
6.2 Prepare Submission File
We'll create a CSV file with the required format.
# Prepare submission dataframe
submission = test[['id', 'probability']]
# Save to CSV
submission.to_csv('submission.csv', index=False)
print("Submission file 'submission.csv' is ready.")
7. Conclusion and Next Steps
By following the steps above, you've:
- Cleaned the Data: Handled missing values appropriately by dropping columns with excessive missingness and imputing remaining missing values.
- Engineered Features: Normalized numeric features and encoded categorical variables.
- Trained Multiple Models: Evaluated Logistic Regression, Random Forest, and XGBoost.
- Optimized the Best Model: Performed hyperparameter tuning on XGBoost to improve performance based on
recall@k.
- Prepared the Submission: Generated probabilities for test data and created the submission file.
Additional Recommendations
-
Feature Importance Analysis: Use model feature importances to understand which features contribute most to the predictions. This can also guide further feature engineering.
# Feature importance from XGBoost
import matplotlib.pyplot as plt
xgb.plot_importance(best_xgb_model)
plt.show()
-
Address Class Imbalance: If the dataset is imbalanced, consider techniques like resampling, using class weights, or specialized algorithms.
# Example: Using class weights in Logistic Regression
lr_model_balanced = LogisticRegression(
class_weight='balanced', max_iter=1000, random_state=42)
-
Ensemble Methods: Combine predictions from multiple models to potentially improve performance.
# Averaging probabilities
avg_probs = (lr_probs + rf_probs + xgb_probs) / 3
avg_recall_k = recall_at_k(y_val.values, avg_probs, k)
print(f'Ensemble recall@{k*100:.0f}%: {avg_recall_k:.4f}')
-
Threshold Tuning: Experiment with different thresholds for classification to maximize recall@k.
-
Cross-Validation: Utilize cross-validation to assess how the model generalizes to unseen data.
from sklearn.model_selection import cross_val_score
# Cross-validation scores
xgb_cv_scores = cross_val_score(
best_xgb_model, X, y, cv=5, scoring='recall')
print(f'Cross-validated recall scores: {xgb_cv_scores}')
Let me know if you have any questions or need further assistance with any of the steps!