Building a Fraud Prediction Model with EvalML

In this demo, we will build an optimized fraud prediction model using EvalML. To optimize the pipeline, we will set up an objective function to minimize the percentage of total transaction value lost to fraud. At the end of this demo, we also show you how introducing the right objective during the training is over 4x better than using a generic machine learning metric like AUC.

[1]:
import evalml
from evalml import AutoMLSearch
from evalml.objectives import FraudCost
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/v0.11.2/lib/python3.7/site-packages/evalml/pipelines/components/transformers/preprocessing/text_featurization.py:35: RuntimeWarning: No text columns were given to TextFeaturizer, component will have no effect
  warnings.warn("No text columns were given to TextFeaturizer, component will have no effect", RuntimeWarning)

Configure “Cost of Fraud”

To optimize the pipelines toward the specific business needs of this model, you can set your own assumptions for the cost of fraud. These parameters are

  • retry_percentage - what percentage of customers will retry a transaction if it is declined?

  • interchange_fee - how much of each successful transaction do you collect?

  • fraud_payout_percentage - the percentage of fraud will you be unable to collect

  • amount_col - the column in the data the represents the transaction amount

Using these parameters, EvalML determines attempt to build a pipeline that will minimize the financial loss due to fraud.

[2]:
fraud_objective = FraudCost(retry_percentage=.5,
                            interchange_fee=.02,
                            fraud_payout_percentage=.75,
                            amount_col='amount')

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

[3]:
X, y = evalml.demos.load_fraud(n_rows=2500)
             Number of Features
Boolean                       1
Categorical                   6
Numeric                       5

Number of training examples: 2500
Labels
False    85.92%
True     14.08%
Name: fraud, dtype: object

EvalML natively supports one-hot encoding. Here we keep 1 out of the 6 categorical columns to decrease computation time.

[4]:
X = X.drop(['datetime', 'expiration_date', 'country', 'region', 'provider'], axis=1)

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

print(X.dtypes)
card_id               int64
store_id              int64
amount                int64
currency             object
customer_present       bool
lat                 float64
lng                 float64
dtype: object

Because the fraud 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=fraud_objective,
                      additional_objectives=['auc', 'f1', 'precision'],
                      max_pipelines=5,
                      optimize_thresholds=True)

automl.search(X_train, y_train)
Generating pipelines to search over...
*****************************
* Beginning pipeline search *
*****************************

Optimizing for Fraud Cost.
Lower score is better.

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

(1/5) Mode Baseline Binary Classification P... Elapsed:00:00
        Starting cross validation
        Finished cross validation - mean Fraud Cost: 0.002
(2/5) CatBoost Classifier w/ Simple Imputer    Elapsed:00:00
        Starting cross validation
        Finished cross validation - mean Fraud Cost: 0.011
(3/5) XGBoost Classifier w/ Simple Imputer ... Elapsed:00:08
        Starting cross validation
[08:27:31] 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.11.2/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].

/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/v0.11.2/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].

[08:27: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.
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/v0.11.2/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].

[08:27: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.
        Finished cross validation - mean Fraud Cost: 0.007
(4/5) Random Forest Classifier w/ Simple Im... Elapsed:00:10
        Starting cross validation
        Finished cross validation - mean Fraud Cost: 0.002
(5/5) Logistic Regression Classifier w/ Sim... Elapsed:00:12
        Starting cross validation
        Finished cross validation - mean Fraud Cost: 0.016

Search finished after 00:13
Best pipeline: Mode Baseline Binary Classification Pipeline
Best pipeline Fraud Cost: 0.002316

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 fraud detection objective we defined

[6]:
automl.rankings
[6]:
id pipeline_name score high_variance_cv parameters
0 0 Mode Baseline Binary Classification Pipeline 0.002316 False {'Baseline Classifier': {'strategy': 'random_w...
1 3 Random Forest Classifier w/ Simple Imputer + O... 0.002316 False {'Simple Imputer': {'impute_strategy': 'most_f...
2 2 XGBoost Classifier w/ Simple Imputer + One Hot... 0.007152 True {'Simple Imputer': {'impute_strategy': 'most_f...
3 1 CatBoost Classifier w/ Simple Imputer 0.011063 True {'Simple Imputer': {'impute_strategy': 'most_f...
4 4 Logistic Regression Classifier w/ Simple Imput... 0.015898 True {'Simple Imputer': {'impute_strategy': 'most_f...

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[1]["id"])
****************************************************************
* Random Forest Classifier w/ Simple Imputer + One Hot Encoder *
****************************************************************

Problem Type: Binary Classification
Model Family: Random Forest

Pipeline Steps
==============
1. Simple Imputer
         * impute_strategy : most_frequent
         * fill_value : None
2. One Hot Encoder
         * top_n : 10
         * categories : None
         * drop : None
         * handle_unknown : ignore
         * handle_missing : error
3. Random Forest Classifier
         * n_estimators : 100
         * max_depth : 6
         * n_jobs : -1

Training
========
Training for Binary Classification problems.
Objective to optimize binary classification pipeline thresholds for: <evalml.objectives.fraud_cost.FraudCost object at 0x7f511e37cdd0>
Total training time (including CV): 2.3 seconds

Cross Validation
----------------
             Fraud Cost   AUC    F1  Precision # Training # Testing
0                 0.002 0.853 0.247      0.141   1066.000   667.000
1                 0.002 0.847 0.247      0.141   1066.000   667.000
2                 0.002 0.856 0.247      0.141   1067.000   666.000
mean              0.002 0.852 0.247      0.141          -         -
std               0.000 0.004 0.000      0.000          -         -
coef of var       0.055 0.005 0.001      0.001          -         -

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)
[9]:
<evalml.pipelines.classification.baseline_binary.ModeBaselineBinaryPipeline at 0x7f511a164450>

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

[10]:
best_pipeline.score(X_holdout, y_holdout, objectives=["auc", fraud_objective])
[10]:
OrderedDict([('AUC', 0.5), ('Fraud Cost', 0.016036197878507734)])

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 fraud cost objective to see how the best pipelines compare.

[11]:
automl_auc = AutoMLSearch(problem_type='binary',
                          objective='auc',
                          additional_objectives=['f1', 'precision'],
                          max_pipelines=5,
                          optimize_thresholds=True)

automl_auc.search(X_train, y_train)
Generating pipelines to search over...
*****************************
* Beginning pipeline search *
*****************************

Optimizing for AUC.
Greater score is better.

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

(1/5) Mode Baseline Binary Classification P... Elapsed:00:00
        Starting cross validation
        Finished cross validation - mean AUC: 0.500
(2/5) CatBoost Classifier w/ Simple Imputer    Elapsed:00:00
        Starting cross validation
        Finished cross validation - mean AUC: 0.839
(3/5) XGBoost Classifier w/ Simple Imputer ... Elapsed:00:09
        Starting cross validation
[08:27:46] 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.11.2/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].

/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/v0.11.2/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].

[08:27:46] 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.
[08:27:46] 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.
        Finished cross validation - mean AUC: 0.851
/home/docs/checkouts/readthedocs.org/user_builds/feature-labs-inc-evalml/envs/v0.11.2/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].

(4/5) Random Forest Classifier w/ Simple Im... Elapsed:00:09
        Starting cross validation
        Finished cross validation - mean AUC: 0.855
(5/5) Logistic Regression Classifier w/ Sim... Elapsed:00:11
        Starting cross validation
        Finished cross validation - mean AUC: 0.806

Search finished after 00:11
Best pipeline: Random Forest Classifier w/ Simple Imputer + One Hot Encoder
Best pipeline AUC: 0.854910

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 3 Random Forest Classifier w/ Simple Imputer + O... 0.854910 False {'Simple Imputer': {'impute_strategy': 'most_f...
1 2 XGBoost Classifier w/ Simple Imputer + One Hot... 0.851262 False {'Simple Imputer': {'impute_strategy': 'most_f...
2 1 CatBoost Classifier w/ Simple Imputer 0.839414 False {'Simple Imputer': {'impute_strategy': 'most_f...
3 4 Logistic Regression Classifier w/ Simple Imput... 0.806067 False {'Simple Imputer': {'impute_strategy': 'most_f...
4 0 Mode Baseline Binary Classification Pipeline 0.500000 False {'Baseline Classifier': {'strategy': 'random_w...
[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.utils.make_pipeline.<locals>.GeneratedPipeline at 0x7f511a107dd0>
[14]:
# get the fraud score on holdout data
best_pipeline_auc.score(X_holdout, y_holdout,  objectives=["auc", fraud_objective])
[14]:
OrderedDict([('AUC', 0.8299003322259136),
             ('Fraud Cost', 0.004329350526560073)])
[15]:
# fraud score on fraud optimized again
best_pipeline.score(X_holdout, y_holdout, objectives=["auc", fraud_objective])
[15]:
OrderedDict([('AUC', 0.5), ('Fraud Cost', 0.01126539759779717)])

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 fraud cost. However, the losses due to fraud are over 3% of the total transaction amount when optimized for AUC and under 1% when optimized for fraud cost. As a result, we lose more than 2% of the total transaction amount by not optimizing for fraud cost specifically.

This happens because optimizing for AUC does not take into account the user-specified retry_percentage, interchange_fee, fraud_payout_percentage values. Thus, the best pipelines may produce the highest AUC but may not actually reduce the amount loss due to your specific type fraud.

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