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 AutoClassificationSearch
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]:
import pandas as pd

customers = pd.read_csv('s3://featurelabs-static/lead_scoring_ml_apps/customers.csv')
interactions = pd.read_csv('s3://featurelabs-static/lead_scoring_ml_apps/interactions.csv')
leads = pd.read_csv('s3://featurelabs-static/lead_scoring_ml_apps/previous_leads.csv')

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'], axis=1)

display(X.head())
job country state zip action amount
0 Engineer, mining NaN NY 60091.0 page_view NaN
1 Psychologist, forensic US CA NaN purchase 135.23
2 Psychologist, forensic US CA NaN page_view NaN
3 Air cabin crew US NaN 60091.0 download NaN
4 Air cabin crew US 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
country     object
state       object
zip        float64
action      object
amount     float64
dtype: object

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

[5]:
automl = AutoClassificationSearch(objective=lead_scoring_objective,
                                  additional_objectives=['auc'],
                                  max_pipelines=5)

automl.search(X_train, y_train)
*****************************
* Beginning pipeline search *
*****************************

Optimizing for Lead Scoring. Greater score is better.

Searching up to 5 pipelines.
✔ Cat Boost Classification Pipeline:        20%|██        | Elapsed:00:04
✔ Logistic Regression Pipeline:             40%|████      | Elapsed:00:07
✔ Logistic Regression Pipeline:             60%|██████    | Elapsed:00:08
▹ XGBoost Classification Pipeline:          80%|████████  | Elapsed:00:08
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/v0.8.0/lib/python3.7/site-packages/xgboost/sklearn.py:888: UserWarning:

The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1].

[19:58:05] WARNING: ../src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/v0.8.0/lib/python3.7/site-packages/xgboost/sklearn.py:888: UserWarning:

The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1].

[19:58:08] WARNING: ../src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/v0.8.0/lib/python3.7/site-packages/xgboost/sklearn.py:888: UserWarning:

The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1].

[19:58:11] WARNING: ../src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
✔ XGBoost Classification Pipeline:          80%|████████  | Elapsed:00:19
✔ Cat Boost Classification Pipeline:       100%|██████████| Elapsed:00:20
✔ Optimization finished                    100%|██████████| Elapsed:00:20

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 high_variance_cv parameters
0 3 XGBoost Classification Pipeline 14.706382 False {'impute_strategy': 'most_frequent', 'percent_...
1 0 Cat Boost Classification Pipeline 13.224749 True {'impute_strategy': 'most_frequent', 'n_estima...
2 1 Logistic Regression Pipeline 12.973101 True {'impute_strategy': 'median', 'penalty': 'l2',...
3 2 Logistic Regression Pipeline 12.973101 True {'impute_strategy': 'median', 'penalty': 'l2',...
4 4 Cat Boost Classification Pipeline 11.848536 True {'impute_strategy': 'most_frequent', 'n_estima...

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"])
***********************************
* XGBoost Classification Pipeline *
***********************************

Supported Problem Types: Binary Classification, Multiclass Classification
Model Family: XGBoost Classifier
Objective to Optimize: Lead Scoring (greater is better)
Number of features: 1

Pipeline Steps
==============
1. One Hot Encoder
         * top_n : 10
2. Simple Imputer
         * impute_strategy : most_frequent
         * fill_value : None
3. RF Classifier Select From Model
         * percent_features : 0.08032569761590808
         * threshold : mean
4. XGBoost Classifier
         * eta : 0.020218397440325723
         * max_depth : 20
         * min_child_weight : 9.614396430577418
         * n_estimators : 848

Training
========
Training for Binary Classification problems.
Total training time (including CV): 10.3 seconds

Cross Validation
----------------
             Lead Scoring   AUC # Training # Testing
0                  15.619 0.531   3099.000  1550.000
1                  13.826 0.492   3099.000  1550.000
2                  14.674 0.502   3100.000  1549.000
mean               14.706 0.508          -         -
std                 0.897 0.020          -         -
coef of var         0.061 0.040          -         -

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)
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/v0.8.0/lib/python3.7/site-packages/xgboost/sklearn.py:888: UserWarning:

The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1].

[19:58:16] WARNING: ../src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
[9]:
<evalml.pipelines.classification.xgboost.XGBoostPipeline at 0x7f496d321350>

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, other_objectives=["auc", lead_scoring_objective])
[10]:
(11.453138435081685,
 OrderedDict([('AUC', 0.515593834995467),
              ('Lead Scoring', 11.453138435081685)]))

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.AutoClassificationSearch(objective='auc',
                                additional_objectives=[],
                                max_pipelines=5)

automl_auc.search(X_train, y_train)
*****************************
* Beginning pipeline search *
*****************************

Optimizing for AUC. Greater score is better.

Searching up to 5 pipelines.
✔ Cat Boost Classification Pipeline:        20%|██        | Elapsed:00:04
✔ Logistic Regression Pipeline:             40%|████      | Elapsed:00:04
✔ Logistic Regression Pipeline:             60%|██████    | Elapsed:00:05
▹ XGBoost Classification Pipeline:          80%|████████  | Elapsed:00:05
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/v0.8.0/lib/python3.7/site-packages/xgboost/sklearn.py:888: UserWarning:

The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1].

[19:58:26] WARNING: ../src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/v0.8.0/lib/python3.7/site-packages/xgboost/sklearn.py:888: UserWarning:

The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1].

[19:58:29] WARNING: ../src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/v0.8.0/lib/python3.7/site-packages/xgboost/sklearn.py:888: UserWarning:

The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1].

[19:58:32] WARNING: ../src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
✔ XGBoost Classification Pipeline:          80%|████████  | Elapsed:00:14
✔ Cat Boost Classification Pipeline:       100%|██████████| Elapsed:00:15
✔ Optimization finished                    100%|██████████| Elapsed:00:15

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

[12]:
automl_auc.rankings
[12]:
id pipeline_name score high_variance_cv parameters
0 4 Cat Boost Classification Pipeline 0.928045 False {'impute_strategy': 'most_frequent', 'n_estima...
1 0 Cat Boost Classification Pipeline 0.891013 False {'impute_strategy': 'most_frequent', 'n_estima...
2 2 Logistic Regression Pipeline 0.695681 False {'impute_strategy': 'median', 'penalty': 'l2',...
3 1 Logistic Regression Pipeline 0.695662 False {'impute_strategy': 'median', 'penalty': 'l2',...
4 3 XGBoost Classification Pipeline 0.509056 False {'impute_strategy': 'most_frequent', 'percent_...
[13]:
best_pipeline_auc = automl_auc.best_pipeline

# train on the full training data
best_pipeline_auc.fit(X_train, y_train)
[13]:
<evalml.pipelines.classification.catboost.CatBoostClassificationPipeline at 0x7f49342b6050>
[14]:
# get the auc and lead scoring score on holdout data
best_pipeline_auc.score(X_holdout, y_holdout,  other_objectives=["auc", lead_scoring_objective])
[14]:
(0.9197793895436688,
 OrderedDict([('AUC', 0.9197793895436688),
              ('Lead Scoring', -0.017196904557179708)]))

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.