The Bank launches credit card activation campaigns using various communication channels. Personal calls to customers are a rather costly way of communication, and not all customers respond positively to this format of communication: an SMS or push notification will be enough for some.
Your task is to help the bank optimize communication costs by learning to predict the difference in the effectiveness of voice calls based on customer data. As a solution, you need to provide the uplift predicted by the model for each customer in the test sample.
Data:
Using interaction history, mobile app sessions, product requests, and other attributes, you will have to create a model that can improve the effectiveness of campaigns by personalizing the most appropriate way to communicate with each customer.
The attributes that are contained in the samples:
successful_utilization - a variable that indicates whether the customer has used the loan product
retro_date - date when the task was created for the client
treatment - a column that shows whether there was a voice communication with the client.
1 - the client was communicated with via voice channel, 0 - the client could have been communicated with via voice channel at this moment, but was not
mb - group of attributes that characterizes sessions in the client's mobile application
application - a group of attributes that characterizes different applications of customers for our products in the past
bki - a group of attributes that characterizes customer visits to the Credit History Bureau.
partner - a group of attributes that characterizes various subscriptions of clients to partner services
graph - a group of features that characterizes data on contact books of our clients feature - a group of features that is hidden from description
feature - a group of features that is hidden from the description
Metric:
The quality of the solution is determined using the Area under uplift curve (AUUQ) metric.
The number of points for an assignment is determined by the formula:
Points = 300 * percentileofscore(upliftaucscores, upliftaucscore), where
percentileofscore - function that calculates percentile rank
uplift auc scores - values of uplift auc score metrics of all participants,
uplift auc score - value of uplift auc score metric of this participant.
When calculating scores, the metric values of the participants whose solutions showed a better result than the attached example answer to the task are used. Solutions with metric values less than or equal to the value obtained with the example are scored 0 points.
Files:
train.csv
test.csv
sample_submission.csv
Use the best ML solutions. Keep in mind that the code will run in google colab
Assistant
To optimize the Bank's communication costs by predicting the uplift from using voice calls for each customer, we'll develop an uplift modeling solution. Uplift modeling estimates the incremental impact of a treatment (voice call) compared to a control (no voice call) for each individual customer.
Below is a comprehensive guide to building an uplift model using Python in Google Colab. We'll use the CausalML library, which provides robust tools for uplift modeling. Here's the step-by-step process:
Set Up the Environment
Load and Explore the Data
Preprocess the Data
Feature Engineering
Model Training
Predicting Uplift on Test Data
Prepare Submission File
Let's go through each step in detail.
1. Set Up the Environment
First, ensure that you have the necessary libraries installed. We'll use pandas for data manipulation, CausalML for uplift modeling, and other essential libraries for preprocessing and evaluation.
# Import libraries
import pandas as pd
import numpy as np
from causalml.inference.tree import BaseCausalModel
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.metrics import roc_auc_score
import warnings
warnings.filterwarnings('ignore')
2. Load and Explore the Data
Load the training and test datasets. We'll also take a quick look at the data to understand its structure.
python
# Load datasets
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
sample_submission = pd.read_csv('sample_submission.csv')
# Display first few rows of training data
train.head()
Note: Ensure that the train.csv, test.csv, and sample_submission.csv files are uploaded to your Google Colab environment or accessible via a mounted Google Drive.
Apply the preprocessing pipelines to both training and test datasets.
python
# Separate features and target
X = train.drop(['successful_utilization', 'retro_date'], axis=1)
y = train['successful_utilization']
# Separate treatment indicator
treatment = train['treatment']
# Preprocess features
X_preprocessed = preprocessor.fit_transform(X)
test_preprocessed = preprocessor.transform(test)
print(f"Training features shape after preprocessing: {X_preprocessed.shape}")
print(f"Test features shape after preprocessing: {test_preprocessed.shape}")
4. Feature Engineering
Create time-based features from retro_date and any other necessary feature transformations.
python
# Convert 'retro_date' to datetime
X['retro_date'] = pd.to_datetime(X['retro_date'])
test['retro_date'] = pd.to_datetime(test['retro_date'])
# Extract year, month, day
for df in [X, test]:
df['retro_year'] = df['retro_date'].dt.year
df['retro_month'] = df['retro_date'].dt.month
df['retro_day'] = df['retro_date'].dt.day
df.drop('retro_date', axis=1, inplace=True)
# Re-define feature columns after feature engineering
feature_cols = X.columns.tolist()
feature_cols.remove('treatment')
feature_cols.remove('successful_utilization')
# Update numerical and categorical columns
numerical_cols = []
categorical_cols = []
for col in feature_cols:
if X[col].dtype in ['int64', 'float64']:
numerical_cols.append(col)
else:
categorical_cols.append(col)
# Update preprocessor with new features
preprocessor = ColumnTransformer(transformers=[
('num', numerical_pipeline, numerical_cols),
('cat', categorical_pipeline, categorical_cols)
])
# Re-preprocess with new features
X = X.drop(['retro_date'], axis=1)
test = test.drop(['retro_date'], axis=1)
X_preprocessed = preprocessor.fit_transform(X)
test_preprocessed = preprocessor.transform(test)
print(f"Training features shape after feature engineering and preprocessing: {X_preprocessed.shape}")
print(f"Test features shape after feature engineering and preprocessing: {test_preprocessed.shape}")
5. Model Training
We'll use the CausalML library's BaseCausalModel to estimate the uplift. Specifically, we'll use the X-learner approach, which is effective when there is an imbalance between treatment and control groups.
5.1 Initialize the Uplift Model
python
from causalml.inference.tree import BaseCausalModel
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
# Initialize model. Here, we'll use RandomForest as the base estimator
model = BaseCausalModel(
learner=RandomForestRegressor(),
control_learner=RandomForestRegressor(),
treated_learner=RandomForestRegressor()
)
5.2 Fit the Model
python
# Fit the uplift model
model.fit(X=X_preprocessed, treatment=treatment.values, y=y.values)
6. Predicting Uplift on Test Data
Use the trained model to predict the uplift scores for each customer in the test set.
python
# Predict uplift scores on test data
uplift_scores = model.predict(X=test_preprocessed)
# Add uplift scores to the test dataframe
test['uplift'] = uplift_scores
# Display top 5 uplift scores
test[['uplift']].head()
7. Prepare Submission File
Create the submission file with the uplift scores. Ensure that the submission follows the format specified by sample_submission.csv.
python
# Assuming 'test.csv' has an 'id' column to match with 'sample_submission.csv'
# If not, adjust accordingly
# If 'id' is not present, ensure you align the order correctly
submission = test[['uplift']]
# If 'sample_submission.csv' has specific columns, align with it
# For example, if sample_submission has an 'id' and 'uplift' column:
# submission = pd.DataFrame({
# 'id': test['id'],
# 'uplift': uplift_scores
# })
# Save to CSV
submission.to_csv('submission.csv', index=False)
print("Submission file 'submission.csv' created successfully.")
Note: Verify the structure of sample_submission.csv to ensure that the submission file matches the required format. Adjust the columns accordingly if there are discrepancies.
Additional Considerations
7.1 Evaluation Metric: Area Under Uplift Curve (AUUC)
While the primary goal is to maximize the AUUC metric, it's essential to validate your model's performance using cross-validation before generating the final uplift scores.
python
# Example: Split training data for validation
X_train, X_val, treatment_train, treatment_val, y_train, y_val = train_test_split(
X_preprocessed, treatment, y, test_size=0.2, random_state=42
)
# Fit the model on training split
model.fit(X=X_train, treatment=treatment_train.values, y=y_train.values)
# Predict uplift on validation set
uplift_val = model.predict(X_val)
# Here you would compute the AUUC metric
# Since AUUC is not readily available in libraries, you may need to implement it or use available implementations
# For demonstration, we'll compute a placeholder ROC AUC based on uplift
auc = roc_auc_score(y_val, uplift_val)
print(f"Validation ROC AUC (Placeholder for AUUC): {auc}")
Implementing AUUC: To accurately compute the AUUC metric, you may need to use or implement a specialized function. Libraries like CausalML or UpliftML might offer utilities for this purpose.
7.2 Hyperparameter Tuning
Optimize the hyperparameters of your uplift model to achieve better performance.
Note: Hyperparameter tuning for causal models can be more involved than standard models. Consider using validation strategies tailored for uplift modeling.
7.3 Feature Importance
Understanding which features contribute most to the uplift can provide valuable business insights.
python
# Feature importances (example)
# Depending on the model, retrieve feature importances
# For RandomForestRegressor-based uplift models, feature importances can be accessed
importances = model.learner.feature_importances_
feature_names_num = numerical_cols
feature_names_cat = preprocessor.named_transformers_['cat']['encoder'].get_feature_names_out(categorical_cols)
feature_names = list(feature_names_num) + list(feature_names_cat)
feature_importance = pd.Series(importances, index=feature_names).sort_values(ascending=False)
# Display top 20 features
print(feature_importance.head(20))
Conclusion
By following the above steps, you can build an uplift model to predict the differential effectiveness of communication methods for each customer. This personalized approach allows the Bank to allocate resources more efficiently, reducing costs associated with less effective communication channels.
Key Takeaways:
Uplift Modeling: Focuses on the incremental impact of treatments vs. control on individuals.
CausalML Library: Provides robust tools for implementing uplift models.
Preprocessing & Feature Engineering: Critical for model performance.
Validation: Essential to ensure the model generalizes well and optimizes the desired metric (AUUC).
Submission: Ensure that the output aligns with the required format for evaluation.
Feel free to iterate on the model by experimenting with different algorithms, feature engineering techniques, and hyperparameter tuning to optimize performance further.