Goal:
Develop a model to determine the probability that a client will register a business after communication with the bank.
Data Provided:
train.csv: Data on clients who either registered a business between May and August 2023 or did not register after communication with the bank.
test.csv: Data on clients for which you need to make predictions.
Features include:
mb: Mobile app session data.
application: Applications for bank products.
bki: Credit bureau data.
partner: Subscription to partner services.
graph: Contact book data.
feature: Other anonymized features.
target: 1 for registration, 0 for no registration.
Metric:
recall@k is the primary metric, where "k" refers to the top candidates ranked by registration likelihood.
Output:
A CSV file with predicted registration probabilities for the test clients.
Assistant
To develop a model that predicts the probability of a client registering a business after communication with the bank, we'll follow a systematic approach. This guide outlines the steps from data preparation to model evaluation and prediction generation. We'll use Python along with libraries such as pandas, scikit-learn, and LightGBM for this task.
Ensure you have the necessary libraries installed. You can install any missing libraries using pip.
bash
pip install pandas numpy scikit-learn lightgbm
Import the required libraries:
python
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.metrics import recall_score
import lightgbm as lgb
import matplotlib.pyplot as plt
import seaborn as sns
2. Data Loading and Exploration
Load the training and test datasets to understand their structure and contents.
python
# Load datasets
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
# Display first few rows
print(train.head())
print(test.head())
# Check for missing values
print(train.isnull().sum())
print(test.isnull().sum())
# Summary statistics
print(train.describe())
# Target distribution
sns.countplot(x='target', data=train)
plt.title('Target Distribution')
plt.show()
# Check class imbalance
target_counts = train['target'].value_counts()
print(target_counts)
3. Data Preprocessing
Handling Missing Values
Handle missing values appropriately, depending on the feature nature.
python
# Example: Fill numerical features with median
num_cols = train.select_dtypes(include=['int64', 'float64']).columns
for col in num_cols:
median = train[col].median()
train[col].fillna(median, inplace=True)
test[col].fillna(median, inplace=True)
# Example: Fill categorical features with mode
cat_cols = train.select_dtypes(include=['object']).columns
for col in cat_cols:
mode = train[col].mode()[0]
train[col].fillna(mode, inplace=True)
test[col].fillna(mode, inplace=True)
Encoding Categorical Variables
Convert categorical variables into numerical representations.
python
# Initialize LabelEncoder
le = LabelEncoder()
for col in cat_cols:
combined = pd.concat([train[col], test[col]], axis=0).astype(str)
le.fit(combined)
train[col] = le.transform(train[col].astype(str))
test[col] = le.transform(test[col].astype(str))
Feature Scaling (if necessary)
Some models benefit from feature scaling. However, tree-based models like LightGBM handle scaling internally.
Enhance the model's performance by creating new features or transforming existing ones.
python
# Example: Interaction features
# train['mb_application_interaction'] = train['mb'] * train['application']
# test['mb_application_interaction'] = test['mb'] * test['application']
# Example: Log transformation for skewed features
# from scipy.stats import skew
# skewed_feats = train[num_cols].apply(lambda x: skew(x.dropna())).sort_values(ascending=False)
# skewed_cols = skewed_feats[skewed_feats > 0.75].index
# for col in skewed_cols:
# train[col] = np.log1p(train[col])
# test[col] = np.log1p(test[col])
Customize feature engineering based on domain knowledge and data exploration insights.
5. Handling Class Imbalance
If the target classes are imbalanced, techniques like SMOTE or class weighting can be applied. LightGBM supports class weighting directly.
python
# Calculate class weights
from sklearn.utils import class_weight
class_weights = class_weight.compute_class_weight('balanced',
classes=np.unique(train['target']),
y=train['target'])
class_weight_dict = {0: class_weights[0], 1: class_weights[1]}
print(class_weight_dict)
6. Model Selection and Training
We'll use LightGBM, a powerful gradient boosting framework, suitable for large datasets and quick training.
Preparing Data for LightGBM
python
X = train.drop(['target'], axis=1)
y = train['target']
X_test = test.copy()
# Split 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
)
train_data = lgb.Dataset(X_train, label=y_train)
valid_data = lgb.Dataset(X_val, label=y_val, reference=train_data)
# Train the model
model = lgb.train(
params,
train_data,
num_boost_round=1000,
valid_sets=[train_data, valid_data],
early_stopping_rounds=50,
verbose_eval=100
)
7. Model Evaluation (Recall@k)
Understanding Recall@k
Recall@k measures the proportion of actual positives captured in the top k predictions. To compute this, determine a suitable k based on business requirements or a predefined value.
Selecting k
If k is not predefined, you might choose it based on the dataset size or desired percentage. For example, selecting the top 10% of clients as candidates.
python
# Example: Top 10% of the validation set
k = int(0.10 * len(y_val))
Calculating Recall@k
python
# Predict probabilities on validation set
y_val_pred_proba = model.predict(X_val, num_iteration=model.best_iteration)
# Create a dataframe with actual and predicted probabilities
val_results = pd.DataFrame({
'actual': y_val,
'pred_proba': y_val_pred_proba
})
# Sort by predicted probabilities descending
val_results_sorted = val_results.sort_values(by='pred_proba', ascending=False)
# Select top k
top_k = val_results_sorted.head(k)
# Calculate recall
recall_at_k = top_k['actual'].sum() / y_val['actual'].sum()
print(f"Recall@k: {recall_at_k:.4f}")
Adjust k based on specific requirements or iterate to find an optimal value.
8. Making Predictions on Test Data
Once satisfied with model performance, make predictions on the test dataset.
python
# Predict probabilities on test set
test_pred_proba = model.predict(X_test, num_iteration=model.best_iteration)
# Add predictions to test dataframe
test['registration_probability'] = test_pred_proba
9. Generating the Output CSV
Create a CSV file with client identifiers and their corresponding registration probabilities.
python
# Assuming there's an 'id' column in the test set
output = test[['id', 'registration_probability']]
# Save to CSV
output.to_csv('predicted_registration_probabilities.csv', index=False)
print("Predictions saved to 'predicted_registration_probabilities.csv'")
Ensure that the test dataset has a unique identifier (e.g., 'id'). Adjust the column names accordingly.
10. Complete Code Example
Below is the complete code incorporating all the steps mentioned above. Adjust paths, column names, and parameters as needed based on your specific dataset and requirements.
python
Notes:
Feature Engineering: Depending on the insights from data exploration, create new features or transform existing ones to enhance model performance.
Hyperparameter Tuning: For better performance, consider performing hyperparameter tuning using techniques like Grid Search or Bayesian Optimization.
Cross-Validation: Implement cross-validation (e.g., StratifiedKFold) to ensure the model's robustness and generalizability.
Recall@k Calculation: Adjust k based on business requirements. For example, if the bank wants to target the top 5% of clients, set k = int(0.05 * len(y_val)).
Final Model Training: After validation, you might want to retrain the model on the entire training dataset before making final predictions on the test set.
Additional Recommendations
Feature Importance Analysis:
Understanding which features contribute most to the model can provide valuable business insights.
Instead of selecting a fixed k, you can determine an optimal probability threshold that maximizes Recall@k.
Ensemble Methods:
Combine predictions from multiple models to potentially improve performance.
Handling Potential Data Leaks:
Ensure that no future information is inadvertently used during training, which could lead to overly optimistic performance estimates.
Deployment Considerations:
If the model is to be deployed, consider serialization (e.g., using joblib) and integrating it into the production environment.
python
import joblib
# Save the model
joblib.dump(model, 'lgbm_registration_model.pkl')
# Load the model
# model = joblib.load('lgbm_registration_model.pkl')
Documentation and Reproducibility:
Maintain clear documentation of the data processing steps, model parameters, and evaluation metrics to ensure reproducibility and ease of maintenance.
By following this guide, you should be able to develop a robust model to predict the probability of clients registering a business post-bank communication, optimize it based on the Recall@k metric, and generate the required prediction outputs.