The bank launches credit card activation campaigns using various communication channels. Personal calls to clients are quite an expensive way of communication, and not all clients respond positively to this communication format: for some, SMS or push notifications will be enough.
Your task is to help the bank optimize communication costs by learning to predict the difference in the effectiveness of voice calls based on client data. As a solution, you need to provide the uplift predicted by the model for each client from the test sample.
Files:
train.csv - Use this file to train a model
test.csv - Produce an answer from data in this file. This file doesn't have the successful_utilization metric.
Data:
Using the history of interactions, mobile app sessions, product requests, and other features, you will have to create a model that can increase the effectiveness of campaigns through a personalized selection of the most appropriate method of communication with each client. Features contained in the samples, including datatypes (multiple columns mean e.g. [cc_1, cc_2, ]):
successful_utilization – a variable that shows whether the client used the credit product, binary.
retro_date – the date the task was created for the client, YYYY-MM-DD
treatment – a column that shows whether there was voice communication with the client. 1 – the client was communicated with via voice, 0 – the client could have been communicated with via voice at that moment, but did not
mb – a group of features that characterizes sessions in the client’s mobile application, multiple columns
application – a group of features that characterizes various client applications for our products in the past, multiple columns
bki – a group of features that characterizes client visits to the Credit History Bureau, multiple columns
partner – a group of features that characterizes various client subscriptions to partner services, multiple columns
graph – a group of features that characterizes data on our clients’ contact books, multiple columns
feature – a group of features that is hidden from the description, multiple columns
cc - a group of features that is hidden from the description, multiple columns
In all of these NaNs are possible. Some of the columns are mostly numerical, but it is possible that they might be categorical.
Metric:
The quality of the solution is determined using the Area under uplift curve (AUUQ) metric.
The number of points for the task is determined by the formula:
Points=300∗percentileofscore(upliftaucscores,upliftaucscore), where
percentileofscore is a function that calculates the percentile rank
uplift auc scores are the values of the uplift auc score metrics of all participants,
uplift auc score is the value of the uplift auc score metric of this participant.
When calculating points, the metric values of participants whose solutions showed a better result than the attached example answer to the task are used. Solutions with a metric lower than or equal to the value obtained using the example are estimated at 0 points.
Assistant
To optimize the bank's communication costs by predicting the differential effectiveness of voice calls versus other communication channels, you'll need to build an uplift modeling solution. Uplift modeling estimates the incremental impact of a treatment (in this case, voice calls) on an individual’s behavior (successful credit card utilization).
Below is a step-by-step guide to help you build this solution, including data preprocessing, model selection, training, and prediction. I'll also provide sample Python code using popular libraries such as pandas, scikit-learn, and scikit-uplift.
Table of Contents
Understanding Uplift Modeling
Environment Setup
Data Preprocessing
Feature Engineering
Model Selection and Training
Evaluating the Model
Predicting Uplift on Test Data
Generating the Submission File
Additional Tips
1. Understanding Uplift Modeling
Uplift modeling (also known as incremental modeling or true lift modeling) focuses on predicting the causal effect of a treatment on an individual. Unlike traditional predictive modeling, which predicts an outcome, uplift modeling predicts the difference in outcomes between treated and untreated scenarios.
Key Concepts:
Treatment Group (treatment = 1): Clients who received a voice call.
Control Group (treatment = 0): Clients who did not receive a voice call.
Uplift: The difference in the probability of successful utilization between the treatment and control groups.
Objective: Estimate the uplift for each client in the test set to decide whether a voice call (treatment) would be beneficial for them.
2. Environment Setup
Ensure you have the necessary libraries installed. You can use pip to install any missing packages.
import pandas as pd
# Load the datasets
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
b. Exploring the Data
Understand the structure, data types, and presence of missing values.
python
# Display the first few rows
print(train.head())
# Check data types and missing values
print(train.info())
print(train.isnull().sum())
c. Handling Dates
Convert retro_date to datetime and extract useful features like the day of the week, month, etc.
python
train['retro_date'] = pd.to_datetime(train['retro_date'])
test['retro_date'] = pd.to_datetime(test['retro_date'])
# Example feature extraction
for df in [train, test]:
df['day_of_week'] = df['retro_date'].dt.dayofweek
df['month'] = df['retro_date'].dt.month
df['year'] = df['retro_date'].dt.year
df['day'] = df['retro_date'].dt.day
# Drop the original date if not needed
df.drop('retro_date', axis=1, inplace=True)
d. Handling Missing Values
Decide on strategies to handle missing data, such as imputation or removal.
python
from sklearn.impute import SimpleImputer
# Identify numerical and categorical columns
numerical_cols = train.select_dtypes(include=['int64', 'float64']).columns.tolist()
numerical_cols.remove('treatment') # Exclude treatment if it's binary
categorical_cols = train.select_dtypes(include=['object', 'category']).columns.tolist()
# Impute numerical columns with median
num_imputer = SimpleImputer(strategy='median')
train[numerical_cols] = num_imputer.fit_transform(train[numerical_cols])
test[numerical_cols] = num_imputer.transform(test[numerical_cols])
# Impute categorical columns with the most frequent value
cat_imputer = SimpleImputer(strategy='most_frequent')
train[categorical_cols] = cat_imputer.fit_transform(train[categorical_cols])
test[categorical_cols] = cat_imputer.transform(test[categorical_cols])
e. Encoding Categorical Variables
Convert categorical variables into numerical representations.
python
from sklearn.preprocessing import OneHotEncoder
# Initialize encoder
encoder = OneHotEncoder(handle_unknown='ignore', sparse=False)
# Fit on training data
encoded_train = encoder.fit_transform(train[categorical_cols])
encoded_test = encoder.transform(test[categorical_cols])
# Get new column names
encoded_cols = encoder.get_feature_names_out(categorical_cols)
# Create DataFrames
encoded_train = pd.DataFrame(encoded_train, columns=encoded_cols, index=train.index)
encoded_test = pd.DataFrame(encoded_test, columns=encoded_cols, index=test.index)
# Concatenate with original data
train = pd.concat([train.drop(categorical_cols, axis=1), encoded_train], axis=1)
test = pd.concat([test.drop(categorical_cols, axis=1), encoded_test], axis=1)
f. Feature Scaling
Scale numerical features to ensure uniformity, which can benefit many models.
Features like mb, application, bki, partner, graph, feature, and cc represent groups. Ensure all these features are appropriately processed, as shown above.
b. Selecting Relevant Features
Depending on the size and redundancy, consider feature selection techniques to reduce dimensionality.
python
# Example: Remove features with low variance
from sklearn.feature_selection import VarianceThreshold
selector = VarianceThreshold(threshold=0.01) # Adjust threshold as needed
train_selected = selector.fit_transform(train.drop(['successful_utilization', 'treatment'], axis=1))
test_selected = selector.transform(test)
Alternatively, leverage tree-based models that handle feature selection implicitly.
5. Model Selection and Training
a. Choosing the Right Uplift Model
There are several approaches to uplift modeling:
Two-Model Approach: Train separate models for treatment and control groups.
Interaction-Based Models: Include interaction terms between treatment and features.
Specialized Uplift Models: Such as X-learner, S-learner, T-learner, or models provided by specialized libraries.
For this guide, we'll use the Two-Model Approach with a tree-based algorithm, which is effective and straightforward.
b. Implementing the Two-Model Approach
i. Split the Training Data
Separate treatment and control groups.
python
# Separate treatment and control
train_treated = train[train['treatment'] == 1]
train_control = train[train['treatment'] == 0]
# Features and target
X_treated = train_treated.drop(['successful_utilization', 'treatment'], axis=1)
y_treated = train_treated['successful_utilization']
X_control = train_control.drop(['successful_utilization', 'treatment'], axis=1)
y_control = train_control['successful_utilization']
ii. Train Models
Use a robust classifier like RandomForestClassifier for both groups.
Evaluating uplift models requires specific metrics. The Area Under the Uplift Curve (AUUC) or Qini Coefficient are commonly used. However, given the scope, we'll briefly touch upon model validation.
a. Cross-Validation
Ensure your model generalizes well by performing cross-validation.
python
from sklearn.model_selection import cross_val_score
# Example: Cross-validation for treated
cv_scores_treated = cross_val_score(model_treated, X_treated, y_treated, cv=5, scoring='roc_auc')
print(f'Treated Model AUROC: {cv_scores_treated.mean()}')
# Similarly for control
cv_scores_control = cross_val_score(model_control, X_control, y_control, cv=5, scoring='roc_auc')
print(f'Control Model AUROC: {cv_scores_control.mean()}')
b. Qini Curve and Coefficient
For a more precise uplift evaluation, consider using the scikit-uplift library.
python
!pip install scikit-uplift
python
from sklift.metrics import QiniCurve, qini_area
from sklift.models import ClassTransformation
from sklift.models import RandomForestClassifier as UpliftRandomForest
# Prepare data
X = train.drop(['successful_utilization', 'treatment'], axis=1)
y = train['successful_utilization']
treatment = train['treatment']
# Initialize uplift model
uplift_model = UpliftRandomForest(n_estimators=100, random_state=42)
# Fit model
uplift_model.fit(X, y, treatment)
# Predict uplift
uplift_pred = uplift_model.predict(X)
# Evaluate
qini = qini_area(y, uplift_pred, treatment)
print(f'Qini Area: {qini}')
Note: The above leverages the ClassTransformation or R-Learner provided by scikit-uplift. Adjust the model selection based on the library's documentation and your specific needs.
7. Predicting Uplift on Test Data
Assuming you've trained a specialized uplift model, you can directly predict the uplift for the test set.
python
# Predict uplift
test_uplift = uplift_model.predict(test)
# If using the Two-Model approach:
# Predict probabilities for treated and control
prob_treated = model_treated.predict_proba(test_selected)[:, 1]
prob_control = model_control.predict_proba(test_selected)[:, 1]
# Calculate uplift
test_uplift = prob_treated - prob_control
Ensure that test_selected includes the same feature transformations as the training data.
8. Generating the Submission File
Prepare the output as required, typically with an identifier and the uplift score.
python
# Assuming test has an 'id' column
submission = pd.DataFrame({
'id': test['id'],
'uplift': test_uplift
})
# Save to CSV
submission.to_csv('submission.csv', index=False)
Ensure that the 'id' column exists in your test dataset. Adjust accordingly based on actual identifiers.
9. Additional Tips
a. Feature Importance
Understand which features contribute most to the uplift.
python
import matplotlib.pyplot as plt
import seaborn as sns
# For tree-based models
feature_importances = uplift_model.feature_importances_
features = X.columns
# Create a DataFrame
importance_df = pd.DataFrame({
'feature': features,
'importance': feature_importances
}).sort_values(by='importance', ascending=False)
# Plot
plt.figure(figsize=(10, 8))
sns.barplot(x='importance', y='feature', data=importance_df.head(20))
plt.title('Top 20 Feature Importances for Uplift Model')
plt.show()
b. Advanced Uplift Models
Explore other uplift modeling techniques and libraries for potentially better performance:
S-Learner, T-Learner, X-Learner: Different strategies to estimate causal effects.
Meta-Learners: Such as the Causal Forest.
Specialized Libraries: Consider using libraries like econml by Microsoft, which offers advanced causal inference models.
c. Hyperparameter Tuning
Optimize model performance through hyperparameter tuning using GridSearchCV or RandomizedSearchCV.
python
from sklearn.model_selection import GridSearchCV
param_grid = {
'n_estimators': [100, 200],
'max_depth': [None, 10, 20],
# Add other hyperparameters as needed
}
grid_search = GridSearchCV(uplift_model, param_grid, cv=3, scoring='roc_auc')
grid_search.fit(X, y, treatment)
print(f'Best Parameters: {grid_search.best_params_}')
d. Handling Imbalanced Data
If the successful_utilization classes are imbalanced, consider techniques like SMOTE, class weighting, or balanced sampling.
python
from imblearn.over_sampling import SMOTE
smote = SMOTE(random_state=42)
X_res, y_res = smote.fit_resample(X, y)
# Re-train uplift model
uplift_model.fit(X_res, y_res, treatment)
e. Feature Interactions
Incorporate interaction terms between treatment and features to capture differential effects.
python
for feature in feature_cols:
X[feature + '_treatment'] = X[feature] * treatment
By following this guide, you should be able to build an effective uplift model to predict the differential effectiveness of voice calls for each client. Remember to iterate on feature engineering and model selection to optimize performance continually.