Building a Lead Scoring Model with EvalML

In this demo, we will build an optimized lead scoring model using EvalML. To optimize the pipeline, we will set up an objective function to maximize the revenue generated with true positives while taking into account the cost of false positives. At the end of this demo, we also show you how introducing the right objective during the training is significantly better than using a generic machine learning metric like AUC.

[1]:
import evalml
from evalml import AutoMLSearch
from evalml.objectives import LeadScoring

Configure LeadScoring

To optimize the pipelines toward the specific business needs of this model, you can set your own assumptions for how much value is gained through true positives and the cost associated with false positives. These parameters are

  • true_positive - dollar amount to be gained with a successful lead

  • false_positive - dollar amount to be lost with an unsuccessful lead

Using these parameters, EvalML builds a pileline that will maximize the amount of revenue per lead generated.

[2]:
lead_scoring_objective = LeadScoring(
    true_positives=1000,
    false_positives=-10
)

Dataset

We will be utilizing a dataset detailing a customer’s job, country, state, zip, online action, the dollar amount of that action and whether they were a successful lead.

[3]:
from urllib.request import urlopen
import pandas as pd
import woodwork as ww
customers_data = urlopen('https://featurelabs-static.s3.amazonaws.com/lead_scoring_ml_apps/customers.csv')
interactions_data = urlopen('https://featurelabs-static.s3.amazonaws.com/lead_scoring_ml_apps/interactions.csv')
leads_data = urlopen('https://featurelabs-static.s3.amazonaws.com/lead_scoring_ml_apps/previous_leads.csv')
customers = pd.read_csv(customers_data)
interactions = pd.read_csv(interactions_data)
leads = pd.read_csv(leads_data)

X = customers.merge(interactions, on='customer_id').merge(leads, on='customer_id')
y = X['label']
X = X.drop(['customer_id', 'date_registered', 'birthday','phone', 'email',
            'owner', 'company', 'id', 'time_x',
            'session', 'referrer', 'time_y', 'label', 'country'], axis=1)
display(X.head())
job state zip action amount
0 Engineer, mining NY 60091.0 page_view NaN
1 Psychologist, forensic CA NaN purchase 135.23
2 Psychologist, forensic CA NaN page_view NaN
3 Air cabin crew NaN 60091.0 download NaN
4 Air cabin crew NaN 60091.0 page_view NaN

We will convert our data into Woodwork data structures. Doing so enables us to have more control over the types passed to and inferred by AutoML.

[4]:
X = ww.DataTable(X, semantic_tags={'job': 'category'}, logical_types={'job': 'Categorical'})
y = ww.DataColumn(y)
X.types
[4]:
Physical Type Logical Type Semantic Tag(s)
Data Column
job category Categorical ['category']
state category Categorical ['category']
zip float64 Double ['numeric']
action category Categorical ['category']
amount float64 Double ['numeric']

Search for the best pipeline

In order to validate the results of the pipeline creation and optimization process, we will save some of our data as a holdout set.

EvalML natively supports one-hot encoding and imputation so the above NaN and categorical values will be taken care of.

[5]:
X_train, X_holdout, y_train, y_holdout = evalml.preprocessing.split_data(X, y, problem_type='binary', test_size=0.2, random_seed=0)

print(X.types)
            Physical Type Logical Type Semantic Tag(s)
Data Column
job              category  Categorical    ['category']
state            category  Categorical    ['category']
zip               float64       Double     ['numeric']
action           category  Categorical    ['category']
amount            float64       Double     ['numeric']

Because the lead scoring labels are binary, we will use AutoMLSearch(X_train=X_train, y_train=y_train, problem_type='binary'). When we call .search(), the search for the best pipeline will begin.

[6]:
from evalml.preprocessing import BalancedClassificationDataCVSplit
# we choose to slightly sample classes by setting the sampling ratio low
# we use the same splitter for both cases
data_splitter = BalancedClassificationDataCVSplit(sampling_ratio=0.1, random_seed=0)

automl = AutoMLSearch(X_train=X_train, y_train=y_train,
                      problem_type='binary',
                      data_splitter=data_splitter,
                      objective=lead_scoring_objective,
                      additional_objectives=['auc'],
                      max_batches=1,
                      optimize_thresholds=True)

automl.search()
Generating pipelines to search over...

*****************************
* Beginning pipeline search *
*****************************

Optimizing for Lead Scoring.
Greater score is better.

Using SequentialEngine to train and score pipelines.
Searching up to 1 batches for a total of 9 pipelines.
Allowed model families: decision_tree, extra_trees, linear_model, xgboost, catboost, random_forest, lightgbm

Evaluating Baseline Pipeline: Mode Baseline Binary Classification Pipeline
Mode Baseline Binary Classification Pipeline:
        Starting cross validation
        Finished cross validation - mean Lead Scoring: 0.000

*****************************
* Evaluating Batch Number 1 *
*****************************

Decision Tree Classifier w/ Imputer + One Hot Encoder:
        Starting cross validation
        Finished cross validation - mean Lead Scoring: 6.047
        High coefficient of variation (cv >= 0.2) within cross validation scores.
        Decision Tree Classifier w/ Imputer + One Hot Encoder may not perform as estimated on unseen data.
Extra Trees Classifier w/ Imputer + One Hot Encoder:
        Starting cross validation
        Finished cross validation - mean Lead Scoring: 6.247
        High coefficient of variation (cv >= 0.2) within cross validation scores.
        Extra Trees Classifier w/ Imputer + One Hot Encoder may not perform as estimated on unseen data.
CatBoost Classifier w/ Imputer:
        Starting cross validation
        Finished cross validation - mean Lead Scoring: 6.138
        High coefficient of variation (cv >= 0.2) within cross validation scores.
        CatBoost Classifier w/ Imputer may not perform as estimated on unseen data.
Random Forest Classifier w/ Imputer + One Hot Encoder:
        Starting cross validation
        Finished cross validation - mean Lead Scoring: 7.666
        High coefficient of variation (cv >= 0.2) within cross validation scores.
        Random Forest Classifier w/ Imputer + One Hot Encoder may not perform as estimated on unseen data.
LightGBM Classifier w/ Imputer + One Hot Encoder:
        Starting cross validation
        Finished cross validation - mean Lead Scoring: 10.820
        High coefficient of variation (cv >= 0.2) within cross validation scores.
        LightGBM Classifier w/ Imputer + One Hot Encoder may not perform as estimated on unseen data.
XGBoost Classifier w/ Imputer + One Hot Encoder:
        Starting cross validation
        Finished cross validation - mean Lead Scoring: 3.927
        High coefficient of variation (cv >= 0.2) within cross validation scores.
        XGBoost Classifier w/ Imputer + One Hot Encoder may not perform as estimated on unseen data.
Elastic Net Classifier w/ Imputer + One Hot Encoder + Standard Scaler:
        Starting cross validation
        Finished cross validation - mean Lead Scoring: 10.797
        High coefficient of variation (cv >= 0.2) within cross validation scores.
        Elastic Net Classifier w/ Imputer + One Hot Encoder + Standard Scaler may not perform as estimated on unseen data.
Logistic Regression Classifier w/ Imputer + One Hot Encoder + Standard Scaler:
        Starting cross validation
        Finished cross validation - mean Lead Scoring: 5.003
        High coefficient of variation (cv >= 0.2) within cross validation scores.
        Logistic Regression Classifier w/ Imputer + One Hot Encoder + Standard Scaler may not perform as estimated on unseen data.

Search finished after 00:13
Best pipeline: LightGBM Classifier w/ Imputer + One Hot Encoder
Best pipeline Lead Scoring: 10.819907

View rankings and select pipeline

Once the fitting process is done, we can see all of the pipelines that were searched, ranked by their score on the lead scoring objective we defined.

[7]:
automl.rankings
[7]:
id pipeline_name mean_cv_score standard_deviation_cv_score validation_score percent_better_than_baseline high_variance_cv parameters
0 5 LightGBM Classifier w/ Imputer + One Hot Encoder 10.819907 5.258483 14.980645 inf True {'Imputer': {'categorical_impute_strategy': 'm...
1 7 Elastic Net Classifier w/ Imputer + One Hot En... 10.796914 9.366362 16.741935 inf True {'Imputer': {'categorical_impute_strategy': 'm...
2 4 Random Forest Classifier w/ Imputer + One Hot ... 7.665850 6.685478 14.961290 inf True {'Imputer': {'categorical_impute_strategy': 'm...
3 2 Extra Trees Classifier w/ Imputer + One Hot En... 6.246608 1.841152 7.800000 inf True {'Imputer': {'categorical_impute_strategy': 'm...
4 3 CatBoost Classifier w/ Imputer 6.137733 9.191255 16.741935 inf True {'Imputer': {'categorical_impute_strategy': 'm...
5 1 Decision Tree Classifier w/ Imputer + One Hot ... 6.046804 4.303758 9.329032 inf True {'Imputer': {'categorical_impute_strategy': 'm...
6 8 Logistic Regression Classifier w/ Imputer + On... 5.002742 2.303951 7.354839 inf True {'Imputer': {'categorical_impute_strategy': 'm...
7 6 XGBoost Classifier w/ Imputer + One Hot Encoder 3.927363 4.989703 9.541935 inf True {'Imputer': {'categorical_impute_strategy': 'm...
8 0 Mode Baseline Binary Classification Pipeline 0.000000 0.000000 0.000000 0.0 False {'Baseline Classifier': {'strategy': 'mode'}}

To select the best pipeline we can call automl.best_pipeline.

[8]:
best_pipeline = automl.best_pipeline

Describe pipeline

You can get more details about any pipeline, including how it performed on other objective functions by calling .describe_pipeline() and specifying the id of the pipeline.

[9]:
automl.describe_pipeline(automl.rankings.iloc[0]["id"])

****************************************************
* LightGBM Classifier w/ Imputer + One Hot Encoder *
****************************************************

Problem Type: binary
Model Family: LightGBM

Pipeline Steps
==============
1. Imputer
         * categorical_impute_strategy : most_frequent
         * numeric_impute_strategy : mean
         * categorical_fill_value : None
         * numeric_fill_value : None
2. One Hot Encoder
         * top_n : 10
         * features_to_encode : None
         * categories : None
         * drop : if_binary
         * handle_unknown : ignore
         * handle_missing : error
3. LightGBM Classifier
         * boosting_type : gbdt
         * learning_rate : 0.1
         * n_estimators : 100
         * max_depth : 0
         * num_leaves : 31
         * min_child_samples : 20
         * n_jobs : -1
         * bagging_freq : 0
         * bagging_fraction : 0.9

Training
========
Training for binary problems.
Objective to optimize binary classification pipeline thresholds for: <evalml.objectives.lead_scoring.LeadScoring object at 0x7fd27eb68b20>
Total training time (including CV): 1.4 seconds

Cross Validation
----------------
             Lead Scoring   AUC # Training # Validation
0                  14.981 0.711      1,760        1,550
1                   4.910 0.707      1,760        1,550
2                  12.569 0.653      1,760        1,549
mean               10.820 0.690          -            -
std                 5.258 0.033          -            -
coef of var         0.486 0.047          -            -

Evaluate on hold out

Finally, since the best pipeline was trained on all of the training data, we evaluate it on the holdout dataset.

[10]:
best_pipeline.score(X_holdout, y_holdout, objectives=["auc", lead_scoring_objective])
[10]:
OrderedDict([('AUC', 0.675815956482321), ('Lead Scoring', 14.600171969045572)])

Why optimize for a problem-specific objective?

To demonstrate the importance of optimizing for the right objective, let’s search for another pipeline using AUC, a common machine learning metric. After that, we will score the holdout data using the lead scoring objective to see how the best pipelines compare.

[11]:
automl_auc = evalml.AutoMLSearch(X_train=X_train, y_train=y_train,
                                 problem_type='binary',
                                 objective='auc',
                                 data_splitter=data_splitter,
                                 additional_objectives=[],
                                 max_batches=1,
                                 optimize_thresholds=True)

automl_auc.search()
Generating pipelines to search over...

*****************************
* Beginning pipeline search *
*****************************

Optimizing for AUC.
Greater score is better.

Using SequentialEngine to train and score pipelines.
Searching up to 1 batches for a total of 9 pipelines.
Allowed model families: decision_tree, extra_trees, linear_model, xgboost, catboost, random_forest, lightgbm

Evaluating Baseline Pipeline: Mode Baseline Binary Classification Pipeline
Mode Baseline Binary Classification Pipeline:
        Starting cross validation
        Finished cross validation - mean AUC: 0.500

*****************************
* Evaluating Batch Number 1 *
*****************************

Decision Tree Classifier w/ Imputer + One Hot Encoder:
        Starting cross validation
        Finished cross validation - mean AUC: 0.624
Extra Trees Classifier w/ Imputer + One Hot Encoder:
        Starting cross validation
        Finished cross validation - mean AUC: 0.702
CatBoost Classifier w/ Imputer:
        Starting cross validation
        Finished cross validation - mean AUC: 0.578
Random Forest Classifier w/ Imputer + One Hot Encoder:
        Starting cross validation
        Finished cross validation - mean AUC: 0.702
LightGBM Classifier w/ Imputer + One Hot Encoder:
        Starting cross validation
        Finished cross validation - mean AUC: 0.692
XGBoost Classifier w/ Imputer + One Hot Encoder:
        Starting cross validation
        Finished cross validation - mean AUC: 0.717
Elastic Net Classifier w/ Imputer + One Hot Encoder + Standard Scaler:
        Starting cross validation
        Finished cross validation - mean AUC: 0.500
Logistic Regression Classifier w/ Imputer + One Hot Encoder + Standard Scaler:
        Starting cross validation
        Finished cross validation - mean AUC: 0.691

Search finished after 00:06
Best pipeline: XGBoost Classifier w/ Imputer + One Hot Encoder
Best pipeline AUC: 0.717491
[12]:
automl_auc.rankings
[12]:
id pipeline_name mean_cv_score standard_deviation_cv_score validation_score percent_better_than_baseline high_variance_cv parameters
0 6 XGBoost Classifier w/ Imputer + One Hot Encoder 0.717491 0.012589 0.730302 21.749124 False {'Imputer': {'categorical_impute_strategy': 'm...
1 2 Extra Trees Classifier w/ Imputer + One Hot En... 0.701844 0.024722 0.726947 20.184406 False {'Imputer': {'categorical_impute_strategy': 'm...
2 4 Random Forest Classifier w/ Imputer + One Hot ... 0.701549 0.023929 0.716135 20.154879 False {'Imputer': {'categorical_impute_strategy': 'm...
3 5 LightGBM Classifier w/ Imputer + One Hot Encoder 0.691695 0.029679 0.725931 19.169462 False {'Imputer': {'categorical_impute_strategy': 'm...
4 8 Logistic Regression Classifier w/ Imputer + On... 0.691426 0.017411 0.710468 19.142604 False {'Imputer': {'categorical_impute_strategy': 'm...
5 1 Decision Tree Classifier w/ Imputer + One Hot ... 0.623687 0.011813 0.611314 12.368704 False {'Imputer': {'categorical_impute_strategy': 'm...
6 3 CatBoost Classifier w/ Imputer 0.577711 0.023839 0.582849 7.771084 False {'Imputer': {'categorical_impute_strategy': 'm...
7 0 Mode Baseline Binary Classification Pipeline 0.500000 0.000000 0.500000 0.000000 False {'Baseline Classifier': {'strategy': 'mode'}}
8 7 Elastic Net Classifier w/ Imputer + One Hot En... 0.500000 0.000000 0.500000 0.000000 False {'Imputer': {'categorical_impute_strategy': 'm...

Like before, we can look at the rankings and pick the best pipeline.

[13]:
best_pipeline_auc = automl_auc.best_pipeline
[14]:
# get the auc and lead scoring score on holdout data
best_pipeline_auc.score(X_holdout, y_holdout,  objectives=["auc", lead_scoring_objective])
[14]:
OrderedDict([('AUC', 0.6813387730432154),
             ('Lead Scoring', -0.034393809114359415)])

When we optimize for AUC, we can see that the AUC score from this pipeline is better than the AUC score from the pipeline optimized for lead scoring. However, the revenue per lead is much smaller per lead when optimized for AUC and was much larger when optimized for lead scoring. As a result, we would have a huge gain on the amount of revenue if we optimized for lead scoring.

This happens because optimizing for AUC does not take into account the user-specified true_positive (dollar amount to be gained with a successful lead) and false_positive (dollar amount to be lost with an unsuccessful lead) values. Thus, the best pipelines may produce the highest AUC but may not actually generate the most revenue through lead scoring.

This example highlights how performance in the real world can diverge greatly from machine learning metrics.