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 leadfalse_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=100, false_positives=-5)
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.init(semantic_tags={"job": "category"}, logical_types={"job": "Categorical"})
y = ww.init_series(y)
X.ww
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/main/lib/python3.9/site-packages/woodwork/type_sys/utils.py:33: UserWarning: Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.
pd.to_datetime(
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/main/lib/python3.9/site-packages/woodwork/type_sys/utils.py:33: UserWarning: Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.
pd.to_datetime(
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/main/lib/python3.9/site-packages/woodwork/type_sys/utils.py:33: UserWarning: Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.
pd.to_datetime(
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/main/lib/python3.9/site-packages/woodwork/type_sys/utils.py:33: UserWarning: Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.
pd.to_datetime(
[4]:
Physical Type | Logical Type | Semantic Tag(s) | |
---|---|---|---|
Column | |||
job | category | Categorical | ['category'] |
state | category | Categorical | ['category'] |
zip | Int64 | IntegerNullable | ['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
)
X.ww
[5]:
Physical Type | Logical Type | Semantic Tag(s) | |
---|---|---|---|
Column | |||
job | category | Categorical | ['category'] |
state | category | Categorical | ['category'] |
zip | Int64 | IntegerNullable | ['numeric'] |
action | category | Categorical | ['category'] |
amount | float64 | Double | ['numeric'] |
Because the lead scoring labels are binary, we will use set the problem type to “binary”. When we call .search()
, the search for the best pipeline will begin.
[6]:
automl = AutoMLSearch(
X_train=X_train,
y_train=y_train,
problem_type="binary",
objective=lead_scoring_objective,
additional_objectives=["auc"],
allowed_model_families=["extra_trees", "linear_model"],
max_batches=2,
verbose=True,
)
automl.search(interactive_plot=False)
AutoMLSearch will use mean CV score to rank pipelines.
*****************************
* Beginning pipeline search *
*****************************
Optimizing for Lead Scoring.
Greater score is better.
Using SequentialEngine to train and score pipelines.
Searching up to 2 batches for a total of None pipelines.
Allowed model families:
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 *
*****************************
Random Forest Classifier w/ Label Encoder + Imputer + One Hot Encoder + Oversampler + RF Classifier Select From Model:
Starting cross validation
Finished cross validation - mean Lead Scoring: 1.515
*****************************
* Evaluating Batch Number 2 *
*****************************
Extra Trees Classifier w/ Label Encoder + Select Columns By Type Transformer + Label Encoder + Imputer + Select Columns Transformer + Select Columns Transformer + Label Encoder + Imputer + One Hot Encoder + Oversampler:
Starting cross validation
Finished cross validation - mean Lead Scoring: 1.566
Elastic Net Classifier w/ Label Encoder + Select Columns By Type Transformer + Label Encoder + Imputer + Standard Scaler + Select Columns Transformer + Select Columns Transformer + Label Encoder + Imputer + One Hot Encoder + Standard Scaler + Oversampler:
Starting cross validation
Finished cross validation - mean Lead Scoring: 1.369
Logistic Regression Classifier w/ Label Encoder + Select Columns By Type Transformer + Label Encoder + Imputer + Standard Scaler + Select Columns Transformer + Select Columns Transformer + Label Encoder + Imputer + One Hot Encoder + Standard Scaler + Oversampler:
Starting cross validation
Finished cross validation - mean Lead Scoring: 1.367
Search finished after 15.31 seconds
Best pipeline: Extra Trees Classifier w/ Label Encoder + Select Columns By Type Transformer + Label Encoder + Imputer + Select Columns Transformer + Select Columns Transformer + Label Encoder + Imputer + One Hot Encoder + Oversampler
Best pipeline Lead Scoring: 1.565920