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

Configure “Cost of Fraud”

To optimize the pipelines toward the specific business needs of this model, we can set our 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 the holdout set.

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

Number of training examples: 1000
Targets
False    85.90%
True     14.10%
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]:
cols_to_drop = ['datetime', 'expiration_date', 'country', 'region', 'provider']
for col in cols_to_drop:
    X.pop(col)

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

print(X.types)
                 Physical Type Logical Type Semantic Tag(s)
Data Column
card_id                  Int64      Integer     ['numeric']
store_id                 Int64      Integer     ['numeric']
amount                   Int64      Integer     ['numeric']
currency              category  Categorical    ['category']
customer_present       boolean      Boolean              []
lat                    float64       Double     ['numeric']
lng                    float64       Double     ['numeric']

Because the fraud 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.

[5]:
automl = AutoMLSearch(X_train=X_train, y_train=y_train,
                      problem_type='binary',
                      objective=fraud_objective,
                      additional_objectives=['auc', 'f1', 'precision'],
                      max_batches=1,
                      optimize_thresholds=True)

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

Optimizing for Fraud Cost.
Lower score is better.

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

Batch 1: (1/9) Mode Baseline Binary Classification P... Elapsed:00:00
        Starting cross validation
        Finished cross validation - mean Fraud Cost: 0.033
High coefficient of variation (cv >= 0.2) within cross validation scores. Mode Baseline Binary Classification Pipeline may not perform as estimated on unseen data.
Batch 1: (2/9) Logistic Regression Classifier w/ Imp... Elapsed:00:00
        Starting cross validation
        Finished cross validation - mean Fraud Cost: 0.010
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.
Batch 1: (3/9) Random Forest Classifier w/ Imputer +... Elapsed:00:03
        Starting cross validation
        Finished cross validation - mean Fraud Cost: 0.002
Batch 1: (4/9) XGBoost Classifier w/ Imputer + One H... Elapsed:00:05
        Starting cross validation
        Finished cross validation - mean Fraud Cost: 0.010
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.
Batch 1: (5/9) CatBoost Classifier w/ Imputer           Elapsed:00:06
        Starting cross validation
        Finished cross validation - mean Fraud Cost: 0.002
Batch 1: (6/9) Elastic Net Classifier w/ Imputer + O... Elapsed:00:07
        Starting cross validation
        Finished cross validation - mean Fraud Cost: 0.002
Batch 1: (7/9) Extra Trees Classifier w/ Imputer + O... Elapsed:00:09
        Starting cross validation
        Finished cross validation - mean Fraud Cost: 0.002
Batch 1: (8/9) LightGBM Classifier w/ Imputer + One ... Elapsed:00:10
        Starting cross validation
        Finished cross validation - mean Fraud Cost: 0.033
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.
Batch 1: (9/9) Decision Tree Classifier w/ Imputer +... Elapsed:00:12
        Starting cross validation
        Finished cross validation - mean Fraud Cost: 0.012
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.

Search finished after 00:13
Best pipeline: Random Forest Classifier w/ Imputer + One Hot Encoder
Best pipeline Fraud Cost: 0.002083

View rankings and select pipelines

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 validation_score percent_better_than_baseline high_variance_cv parameters
0 2 Random Forest Classifier w/ Imputer + One Hot ... 0.002083 0.002101 93.667672 False {'Imputer': {'categorical_impute_strategy': 'm...
1 4 CatBoost Classifier w/ Imputer 0.002083 0.002101 93.667672 False {'Imputer': {'categorical_impute_strategy': 'm...
2 5 Elastic Net Classifier w/ Imputer + One Hot En... 0.002083 0.002101 93.667672 False {'Imputer': {'categorical_impute_strategy': 'm...
3 6 Extra Trees Classifier w/ Imputer + One Hot En... 0.002083 0.002101 93.667672 False {'Imputer': {'categorical_impute_strategy': 'm...
4 1 Logistic Regression Classifier w/ Imputer + On... 0.009782 0.002101 70.263315 True {'Imputer': {'categorical_impute_strategy': 'm...
5 3 XGBoost Classifier w/ Imputer + One Hot Encoder 0.009782 0.002101 70.263315 True {'Imputer': {'categorical_impute_strategy': 'm...
6 8 Decision Tree Classifier w/ Imputer + One Hot ... 0.011775 0.008407 64.203384 True {'Imputer': {'categorical_impute_strategy': 'm...
7 0 Mode Baseline Binary Classification Pipeline 0.032895 0.022769 0.000000 True {'Baseline Classifier': {'strategy': 'mode'}}
8 7 LightGBM Classifier w/ Imputer + One Hot Encoder 0.032895 0.022769 0.000000 True {'Imputer': {'categorical_impute_strategy': 'm...

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

[7]:
best_pipeline = automl.best_pipeline

Describe pipelines

We can get more details about any pipeline created during the search process, including how it performed on other objective functions, by calling the describe_pipeline method and passing the id of the pipeline of interest.

[8]:
automl.describe_pipeline(automl.rankings.iloc[1]["id"])
**********************************
* CatBoost Classifier w/ Imputer *
**********************************

Problem Type: binary
Model Family: CatBoost

Pipeline Steps
==============
1. Imputer
         * categorical_impute_strategy : most_frequent
         * numeric_impute_strategy : mean
         * categorical_fill_value : None
         * numeric_fill_value : None
2. CatBoost Classifier
         * n_estimators : 10
         * eta : 0.03
         * max_depth : 6
         * bootstrap_type : None
         * silent : True
         * allow_writing_files : False

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

Cross Validation
----------------
             Fraud Cost   AUC    F1  Precision # Training # Validation
0                 0.002 0.877 0.249      0.142    426.000      267.000
1                 0.002 0.817 0.249      0.142    426.000      267.000
2                 0.002 0.809 0.244      0.139    427.000      266.000
mean              0.002 0.834 0.248      0.141          -            -
std               0.000 0.037 0.003      0.002          -            -
coef of var       0.090 0.045 0.012      0.013          -            -

Evaluate on holdout data

Finally, since the best pipeline is already trained, we evaluate it on the holdout data.

Now, we can score the pipeline on the holdout data using both our fraud cost objective and the AUC (Area under the ROC Curve) objective.

[9]:
best_pipeline.score(X_holdout, y_holdout, objectives=["auc", fraud_objective])
[9]:
OrderedDict([('AUC', 0.8556893687707641),
             ('Fraud Cost', 0.0019819080665371956)])

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.

[10]:
automl_auc = AutoMLSearch(X_train=X_train, y_train=y_train,
                          problem_type='binary',
                          objective='auc',
                          additional_objectives=['f1', 'precision'],
                          max_batches=1,
                          optimize_thresholds=True)

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

Optimizing for AUC.
Greater score is better.

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

Batch 1: (1/9) Mode Baseline Binary Classification P... Elapsed:00:00
        Starting cross validation
        Finished cross validation - mean AUC: 0.500
Batch 1: (2/9) Logistic Regression Classifier w/ Imp... Elapsed:00:00
        Starting cross validation
        Finished cross validation - mean AUC: 0.754
Batch 1: (3/9) Random Forest Classifier w/ Imputer +... Elapsed:00:00
        Starting cross validation
        Finished cross validation - mean AUC: 0.839
Batch 1: (4/9) XGBoost Classifier w/ Imputer + One H... Elapsed:00:01
        Starting cross validation
        Finished cross validation - mean AUC: 0.837
Batch 1: (5/9) CatBoost Classifier w/ Imputer           Elapsed:00:02
        Starting cross validation
        Finished cross validation - mean AUC: 0.828
Batch 1: (6/9) Elastic Net Classifier w/ Imputer + O... Elapsed:00:03
        Starting cross validation
        Finished cross validation - mean AUC: 0.500
Batch 1: (7/9) Extra Trees Classifier w/ Imputer + O... Elapsed:00:03
        Starting cross validation
        Finished cross validation - mean AUC: 0.799
Batch 1: (8/9) LightGBM Classifier w/ Imputer + One ... Elapsed:00:04
        Starting cross validation
        Finished cross validation - mean AUC: 0.845
Batch 1: (9/9) Decision Tree Classifier w/ Imputer +... Elapsed:00:05
        Starting cross validation
        Finished cross validation - mean AUC: 0.799

Search finished after 00:06
Best pipeline: LightGBM Classifier w/ Imputer + One Hot Encoder
Best pipeline AUC: 0.844609

Like before, we can look at the rankings of all of the pipelines searched and pick the best pipeline.

[11]:
automl_auc.rankings
[11]:
id pipeline_name score validation_score percent_better_than_baseline high_variance_cv parameters
0 7 LightGBM Classifier w/ Imputer + One Hot Encoder 0.844609 0.840496 68.921714 False {'Imputer': {'categorical_impute_strategy': 'm...
1 2 Random Forest Classifier w/ Imputer + One Hot ... 0.838816 0.862216 67.763236 False {'Imputer': {'categorical_impute_strategy': 'm...
2 3 XGBoost Classifier w/ Imputer + One Hot Encoder 0.836970 0.840956 67.394055 False {'Imputer': {'categorical_impute_strategy': 'm...
3 4 CatBoost Classifier w/ Imputer 0.828173 0.867846 65.634596 False {'Imputer': {'categorical_impute_strategy': 'm...
4 8 Decision Tree Classifier w/ Imputer + One Hot ... 0.799137 0.802172 59.827398 False {'Imputer': {'categorical_impute_strategy': 'm...
5 6 Extra Trees Classifier w/ Imputer + One Hot En... 0.799061 0.836589 59.812283 False {'Imputer': {'categorical_impute_strategy': 'm...
6 1 Logistic Regression Classifier w/ Imputer + On... 0.753983 0.803264 50.796648 False {'Imputer': {'categorical_impute_strategy': 'm...
7 0 Mode Baseline Binary Classification Pipeline 0.500000 0.500000 0.000000 False {'Baseline Classifier': {'strategy': 'mode'}}
8 5 Elastic Net Classifier w/ Imputer + One Hot En... 0.500000 0.500000 0.000000 False {'Imputer': {'categorical_impute_strategy': 'm...
[12]:
best_pipeline_auc = automl_auc.best_pipeline
[13]:
# get the fraud score on holdout data
best_pipeline_auc.score(X_holdout, y_holdout,  objectives=["auc", fraud_objective])
[13]:
OrderedDict([('AUC', 0.9067691029900331),
             ('Fraud Cost', 0.024416589442515867)])
[14]:
# fraud score on fraud optimized again
best_pipeline.score(X_holdout, y_holdout, objectives=["auc", fraud_objective])
[14]:
OrderedDict([('AUC', 0.8556893687707641),
             ('Fraud Cost', 0.0019819080665371956)])

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.