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 over 6x 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

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

Search for 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.

[4]:
X_train, X_holdout, y_train, y_holdout = evalml.preprocessing.split_data(X, y, test_size=0.2, random_state=0)

print(X.dtypes)
job        object
state      object
zip       float64
action     object
amount    float64
dtype: object

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

[5]:
automl = AutoMLSearch(problem_type='binary',
                      objective=lead_scoring_objective,
                      additional_objectives=['auc'],
                      max_iterations=5,
                      optimize_thresholds=True)

automl.search(X_train, y_train)
`X` passed was not a DataTable. EvalML will try to convert the input as a Woodwork DataTable and types will be inferred. To control this behavior, please pass in a Woodwork DataTable instead.
`y` passed was not a DataColumn. EvalML will try to convert the input as a Woodwork DataTable and types will be inferred. To control this behavior, please pass in a Woodwork DataTable instead.
The following labels fall below 10% of the target: [True]
Generating pipelines to search over...
*****************************
* Beginning pipeline search *
*****************************

Optimizing for Lead Scoring.
Greater score is better.

Searching up to 5 pipelines.
Allowed model families: decision_tree, linear_model, xgboost, catboost, extra_trees, lightgbm, random_forest

Batch 1: (1/5) Mode Baseline Binary Classification P... Elapsed:00:00
        Starting cross validation
        Finished cross validation - mean Lead Scoring: 0.000
2/5) Decision Tree Classifier w/ Imputer +... Elapsed:00:01
        Starting cross validation
        Finished cross validation - mean Lead Scoring: 41.454
3/5) LightGBM Classifier w/ Imputer + Text... Elapsed:00:16
        Starting cross validation
[LightGBM] [Warning] bagging_fraction is set=0.9, subsample=1.0 will be ignored. Current value: bagging_fraction=0.9
[LightGBM] [Warning] bagging_freq is set=0, subsample_freq=0 will be ignored. Current value: bagging_freq=0
[LightGBM] [Warning] bagging_fraction is set=0.9, subsample=1.0 will be ignored. Current value: bagging_fraction=0.9
[LightGBM] [Warning] bagging_freq is set=0, subsample_freq=0 will be ignored. Current value: bagging_freq=0
[LightGBM] [Warning] bagging_fraction is set=0.9, subsample=1.0 will be ignored. Current value: bagging_fraction=0.9
[LightGBM] [Warning] bagging_freq is set=0, subsample_freq=0 will be ignored. Current value: bagging_freq=0
        Finished cross validation - mean Lead Scoring: 44.549
4/5) Extra Trees Classifier w/ Imputer + T... Elapsed:00:30
        Starting cross validation
        Finished cross validation - mean Lead Scoring: 37.848
5/5) Elastic Net Classifier w/ Imputer + T... Elapsed:00:45
        Starting cross validation
        Finished cross validation - mean Lead Scoring: 42.140

Search finished after 00:59
Best pipeline: LightGBM Classifier w/ Imputer + Text Featurization Component + One Hot Encoder
Best pipeline Lead Scoring: 44.549120

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

[6]:
automl.rankings
[6]:
id pipeline_name score validation_score percent_better_than_baseline high_variance_cv parameters
0 2 LightGBM Classifier w/ Imputer + Text Featuriz... 44.549120 44.909677 NaN False {'Imputer': {'categorical_impute_strategy': 'm...
1 4 Elastic Net Classifier w/ Imputer + Text Featu... 42.140250 42.129032 NaN False {'Imputer': {'categorical_impute_strategy': 'm...
2 1 Decision Tree Classifier w/ Imputer + Text Fea... 41.454140 42.129032 NaN False {'Imputer': {'categorical_impute_strategy': 'm...
3 3 Extra Trees Classifier w/ Imputer + Text Featu... 37.847874 39.754839 NaN False {'Imputer': {'categorical_impute_strategy': 'm...
4 0 Mode Baseline Binary Classification Pipeline 0.000000 0.000000 NaN False {'Baseline Classifier': {'strategy': 'mode'}}

to select the best pipeline we can run

[7]:
best_pipeline = automl.best_pipeline

Describe pipeline

You can get more details about any pipeline. Including how it performed on other objective functions.

[8]:
automl.describe_pipeline(automl.rankings.iloc[0]["id"])
***********************************************************************************
* LightGBM Classifier w/ Imputer + Text Featurization Component + 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. Text Featurization Component
         * text_columns : ['job']
3. One Hot Encoder
         * top_n : 10
         * features_to_encode : None
         * categories : None
         * drop : None
         * handle_unknown : ignore
         * handle_missing : error
4. 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 0x7f49f2adb790>
Total training time (including CV): 13.9 seconds

Cross Validation
----------------
             Lead Scoring   AUC # Training # Testing
0                  44.910 0.889   2479.000  1550.000
1                  45.329 0.896   2479.000  1550.000
2                  43.409 0.876   2480.000  1549.000
mean               44.549 0.887          -         -
std                 1.010 0.011          -         -
coef of var         0.023 0.012          -         -

Evaluate on hold out

Finally, we retrain the best pipeline on all of the training data and evaluate on the holdout

[9]:
best_pipeline.fit(X_train, y_train)
[LightGBM] [Warning] bagging_fraction is set=0.9, subsample=1.0 will be ignored. Current value: bagging_fraction=0.9
[LightGBM] [Warning] bagging_freq is set=0, subsample_freq=0 will be ignored. Current value: bagging_freq=0
[9]:
GeneratedPipeline(parameters={'Imputer':{'categorical_impute_strategy': 'most_frequent', 'numeric_impute_strategy': 'mean', 'categorical_fill_value': None, 'numeric_fill_value': None}, 'Text Featurization Component':{'text_columns': ['job']}, 'One Hot Encoder':{'top_n': 10, 'features_to_encode': None, 'categories': None, 'drop': None, 'handle_unknown': 'ignore', 'handle_missing': 'error'}, '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},})

Now, we can score the pipeline on the hold out data using both the lead scoring score and the AUC.

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

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(problem_type='binary',
                                 objective='auc',
                                 additional_objectives=[],
                                 max_iterations=5,
                                 optimize_thresholds=True)

automl_auc.search(X_train, y_train)
`X` passed was not a DataTable. EvalML will try to convert the input as a Woodwork DataTable and types will be inferred. To control this behavior, please pass in a Woodwork DataTable instead.
`y` passed was not a DataColumn. EvalML will try to convert the input as a Woodwork DataTable and types will be inferred. To control this behavior, please pass in a Woodwork DataTable instead.
The following labels fall below 10% of the target: [True]
Generating pipelines to search over...
*****************************
* Beginning pipeline search *
*****************************

Optimizing for AUC.
Greater score is better.

Searching up to 5 pipelines.
Allowed model families: decision_tree, linear_model, xgboost, catboost, extra_trees, lightgbm, random_forest

Batch 1: (1/5) Mode Baseline Binary Classification P... Elapsed:00:00
        Starting cross validation
        Finished cross validation - mean AUC: 0.500
2/5) Decision Tree Classifier w/ Imputer +... Elapsed:00:00
        Starting cross validation
        Finished cross validation - mean AUC: 0.714
3/5) LightGBM Classifier w/ Imputer + Text... Elapsed:00:07
        Starting cross validation
[LightGBM] [Warning] bagging_fraction is set=0.9, subsample=1.0 will be ignored. Current value: bagging_fraction=0.9
[LightGBM] [Warning] bagging_freq is set=0, subsample_freq=0 will be ignored. Current value: bagging_freq=0
[LightGBM] [Warning] bagging_fraction is set=0.9, subsample=1.0 will be ignored. Current value: bagging_fraction=0.9
[LightGBM] [Warning] bagging_freq is set=0, subsample_freq=0 will be ignored. Current value: bagging_freq=0
[LightGBM] [Warning] bagging_fraction is set=0.9, subsample=1.0 will be ignored. Current value: bagging_fraction=0.9
[LightGBM] [Warning] bagging_freq is set=0, subsample_freq=0 will be ignored. Current value: bagging_freq=0
        Finished cross validation - mean AUC: 0.903
4/5) Extra Trees Classifier w/ Imputer + T... Elapsed:00:15
        Starting cross validation
        Finished cross validation - mean AUC: 0.726
5/5) Elastic Net Classifier w/ Imputer + T... Elapsed:00:24
        Starting cross validation
        Finished cross validation - mean AUC: 0.500

Search finished after 00:32
Best pipeline: LightGBM Classifier w/ Imputer + Text Featurization Component + One Hot Encoder
Best pipeline AUC: 0.902642

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

[12]:
automl_auc.rankings
[12]:
id pipeline_name score validation_score percent_better_than_baseline high_variance_cv parameters
0 2 LightGBM Classifier w/ Imputer + Text Featuriz... 0.902642 0.880999 80.528416 False {'Imputer': {'categorical_impute_strategy': 'm...
1 3 Extra Trees Classifier w/ Imputer + Text Featu... 0.726074 0.737538 45.214732 False {'Imputer': {'categorical_impute_strategy': 'm...
2 1 Decision Tree Classifier w/ Imputer + Text Fea... 0.714280 0.660102 42.855997 False {'Imputer': {'categorical_impute_strategy': 'm...
3 0 Mode Baseline Binary Classification Pipeline 0.500000 0.500000 0.000000 False {'Baseline Classifier': {'strategy': 'mode'}}
4 4 Elastic Net Classifier w/ Imputer + Text Featu... 0.500000 0.500000 0.000000 False {'Imputer': {'categorical_impute_strategy': 'm...
[13]:
best_pipeline_auc = automl_auc.best_pipeline

# train on the full training data
best_pipeline_auc.fit(X_train, y_train)
[LightGBM] [Warning] bagging_fraction is set=0.9, subsample=1.0 will be ignored. Current value: bagging_fraction=0.9
[LightGBM] [Warning] bagging_freq is set=0, subsample_freq=0 will be ignored. Current value: bagging_freq=0
[13]:
GeneratedPipeline(parameters={'Imputer':{'categorical_impute_strategy': 'most_frequent', 'numeric_impute_strategy': 'mean', 'categorical_fill_value': None, 'numeric_fill_value': None}, 'Text Featurization Component':{'text_columns': ['job']}, 'One Hot Encoder':{'top_n': 10, 'features_to_encode': None, 'categories': None, 'drop': None, 'handle_unknown': 'ignore', 'handle_missing': 'error'}, '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},})
[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.8958824418253248), ('Lead Scoring', 9.346517626827172)])

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 gained was only $7 per lead when optimized for AUC and was $45 when optimized for lead scoring. As a result, we would gain up to 6x 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.