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.objectives import FraudCost

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()
             Number of Features
Boolean                       1
Categorical                   6
Numeric                       5

Number of training examples: 99992

Labels
False    84.82%
True     15.18%
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 AutoClassifier. When we call .fit(), the search for the best pipeline will begin.

[5]:
clf = evalml.AutoClassifier(objective=fraud_objective,
                            additional_objectives=['auc', 'recall', 'precision'],
                            max_pipelines=5)

clf.fit(X_train, y_train)
*****************************
* Beginning pipeline search *
*****************************

Optimizing for Fraud Cost. Lower score is better.

Searching up to 5 pipelines.
Possible model types: linear_model, random_forest, xgboost

✔ XGBoost Classifier w/ One Hot Encod...     0%|          | Elapsed:00:24
✔ XGBoost Classifier w/ One Hot Encod...    20%|██        | Elapsed:00:51
✔ Random Forest Classifier w/ One Hot...    40%|████      | Elapsed:02:49
✔ XGBoost Classifier w/ One Hot Encod...    60%|██████    | Elapsed:03:15
✔ Logistic Regression Classifier w/ O...    80%|████████  | Elapsed:03:47
✔ Logistic Regression Classifier w/ O...   100%|██████████| Elapsed:03:47

✔ Optimization finished

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]:
clf.rankings
[6]:
id pipeline_name score high_variance_cv parameters
0 1 XGBoostPipeline 0.007623 False {'eta': 0.38438170729269994, 'min_child_weight...
1 0 XGBoostPipeline 0.007623 False {'eta': 0.5928446182250184, 'min_child_weight'...
2 4 LogisticRegressionPipeline 0.007623 False {'penalty': 'l2', 'C': 8.444214828324364, 'imp...
3 2 RFClassificationPipeline 0.007623 False {'n_estimators': 569, 'max_depth': 22, 'impute...
4 3 XGBoostPipeline 0.007623 False {'eta': 0.5288949197529046, 'min_child_weight'...

to select the best pipeline we can run

[7]:
best_pipeline = clf.best_pipeline

Describe pipeline

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

[8]:
clf.describe_pipeline(clf.rankings.iloc[0]["id"])
********************************************************************************************
* XGBoost Classifier w/ One Hot Encoder + Simple Imputer + RF Classifier Select From Model *
********************************************************************************************

Problem Types: Binary Classification, Multiclass Classification
Model Type: XGBoost Classifier
Objective to Optimize: Fraud Cost (lower is better)
Number of features: 5

Pipeline Steps
==============
1. One Hot Encoder
2. Simple Imputer
         * impute_strategy : median
3. RF Classifier Select From Model
         * percent_features : 0.793807787701838
         * threshold : -inf
4. XGBoost Classifier
         * eta : 0.38438170729269994
         * max_depth : 13
         * min_child_weight : 3.677811458900251

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

Cross Validation
----------------
             Fraud Cost   AUC  Recall  Precision # Training # Testing
0                 0.008 0.864   0.264      0.152  53328.000 26665.000
1                 0.008 0.862   0.264      0.152  53328.000 26665.000
2                 0.008 0.867   0.264      0.152  53330.000 26663.000
mean              0.008 0.864   0.264      0.152          -         -
std               0.000 0.003   0.000      0.000          -         -
coef of var       0.003 0.003   0.000      0.000          -         -

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.xgboost.XGBoostPipeline at 0x139088290>

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, other_objectives=["auc", fraud_objective])
[10]:
(0.007626457502689945,
 OrderedDict([('AUC', 0.8691817003558158),
              ('Fraud Cost', 0.007626457502689945)]))

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]:
clf_auc = evalml.AutoClassifier(objective='auc',
                                additional_objectives=['recall', 'precision'],
                                max_pipelines=5)

clf_auc.fit(X_train, y_train)
*****************************
* Beginning pipeline search *
*****************************

Optimizing for AUC. Greater score is better.

Searching up to 5 pipelines.
Possible model types: linear_model, random_forest, xgboost

✔ XGBoost Classifier w/ One Hot Encod...     0%|          | Elapsed:00:28
✔ XGBoost Classifier w/ One Hot Encod...    20%|██        | Elapsed:00:58
✔ Random Forest Classifier w/ One Hot...    40%|████      | Elapsed:03:30
✔ XGBoost Classifier w/ One Hot Encod...    60%|██████    | Elapsed:04:00
✔ Logistic Regression Classifier w/ O...    80%|████████  | Elapsed:04:34
✔ Logistic Regression Classifier w/ O...   100%|██████████| Elapsed:04:34

✔ Optimization finished

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

[12]:
clf_auc.rankings
[12]:
id pipeline_name score high_variance_cv parameters
0 2 RFClassificationPipeline 0.873053 False {'n_estimators': 569, 'max_depth': 22, 'impute...
1 1 XGBoostPipeline 0.867186 False {'eta': 0.38438170729269994, 'min_child_weight...
2 0 XGBoostPipeline 0.852527 False {'eta': 0.5928446182250184, 'min_child_weight'...
3 3 XGBoostPipeline 0.847393 False {'eta': 0.5288949197529046, 'min_child_weight'...
4 4 LogisticRegressionPipeline 0.831181 False {'penalty': 'l2', 'C': 8.444214828324364, 'imp...
[13]:
best_pipeline_auc = clf_auc.best_pipeline

# train on the full training data
best_pipeline_auc.fit(X_train, y_train)
[13]:
<evalml.pipelines.classification.random_forest.RFClassificationPipeline at 0x10f4fce90>
[14]:
# get the fraud score on holdout data
best_pipeline_auc.score(X_holdout, y_holdout,  other_objectives=["auc", fraud_objective])
[14]:
(0.8745605699827037,
 OrderedDict([('AUC', 0.8745605699827037),
              ('Fraud Cost', 0.03273490785793763)]))

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 example highlights how performance in the real world can diverge greatly from machine learning metrics.