Open In Colab View Notebook on GitHub

IEEE Fraud detection adversarial validation [LGBM]#

Giskard is an open-source framework for testing all ML models, from LLMs to tabular models. Don’t hesitate to give the project a star on GitHub ⭐️ if you find it useful!

In this notebook, you’ll learn how to create comprehensive test suites for your model in a few lines of code, thanks to Giskard’s open-source Python library.

Use-case:

Outline:

  • Detect vulnerabilities automatically with Giskard’s scan

  • Automatically generate & curate a comprehensive test suite to test your model beyond accuracy-related metrics

  • Upload your model to the Giskard Hub to:

    • Debug failing tests & diagnose issues

    • Compare models & decide which one to promote

    • Share your results & collect feedback from non-technical team members

Install dependencies#

Make sure to install the giskard

[ ]:
%pip install giskard --upgrade

Troubleshooting#

If you encounter a segmentation fault on macOS at any point during this tutorial, check: https://docs.giskard.ai/en/latest/contribute/dev-environment.html

Import libraries#

[1]:
import os
from pathlib import Path
from urllib.request import urlretrieve

import numpy as np
import pandas as pd
from lightgbm import LGBMClassifier
from sklearn.metrics import roc_auc_score
from pandas.api.types import union_categoricals
from sklearn.model_selection import train_test_split

from giskard import GiskardClient, scan, testing, Dataset, Model, Suite

Define constants#

[2]:
# Constants.
TARGET_COLUMN = 'isTest'
IDX_LABEL = 'TransactionID'

# Paths.
DATA_URL = "ftp://sys.giskard.ai/pub/unit_test_resources/fraud_detection_classification_dataset/{}"
DATA_PATH = Path.home() / ".giskard" / "fraud_detection_classification_dataset"

Dataset preparation#

Load and preprocess data#

[3]:
def fetch_from_ftp(url: str, file: Path) -> None:
    """Helper to fetch data from the FTP server."""
    if not file.parent.exists():
        file.parent.mkdir(parents=True, exist_ok=True)

    if not file.exists():
        print(f"Downloading data from {url}")
        urlretrieve(url, file)

    print(f"Data was loaded!")


def fetch_dataset():
    files_to_fetch = ["train_transaction.csv", "train_identity.csv", "test_transaction.csv", "test_identity.csv"]
    for file_name in files_to_fetch:
        fetch_from_ftp(DATA_URL.format(file_name), DATA_PATH / file_name)


# Define data-types of transactions features.
DATA_TYPES_TRANSACTION = {
    'TransactionID': 'int32',
    'isFraud': 'int8',
    'TransactionDT': 'int32',
    'TransactionAmt': 'float32',
    'ProductCD': 'category',
    'card1': 'int16',
    'card2': 'float32',
    'card3': 'float32',
    'card4': 'category',
    'card5': 'float32',
    'card6': 'category',
    'addr1': 'float32',
    'addr2': 'float32',
    'dist1': 'float32',
    'dist2': 'float32',
    'P_emaildomain': 'category',
    'R_emaildomain': 'category',
}

C_COLS = [f'C{i}' for i in range(1, 15)]
D_COLS = [f'D{i}' for i in range(1, 16)]
M_COLS = [f'M{i}' for i in range(1, 10)]
V_COLS = [f'V{i}' for i in range(1, 340)]

DATA_TYPES_TRANSACTION.update((c, 'float32') for c in C_COLS)
DATA_TYPES_TRANSACTION.update((c, 'float32') for c in D_COLS)
DATA_TYPES_TRANSACTION.update((c, 'float32') for c in V_COLS)
DATA_TYPES_TRANSACTION.update((c, 'category') for c in M_COLS)

# Define datatypes of identity features.
DATA_TYPES_ID = {
    'TransactionID': 'int32',
    'DeviceType': 'category',
    'DeviceInfo': 'category',
}

ID_COLS = [f'id_{i:02d}' for i in range(1, 39)]
ID_CATS = [
    'id_12', 'id_15', 'id_16', 'id_23', 'id_27', 'id_28', 'id_29', 'id_30',
    'id_31', 'id_33', 'id_34', 'id_35', 'id_36', 'id_37', 'id_38'
]

DATA_TYPES_ID.update(((c, 'float32') for c in ID_COLS))
DATA_TYPES_ID.update(((c, 'category') for c in ID_CATS))

# Define list of all categorical features.
CATEGORICALS = [f_name for (f_name, f_type) in dict(DATA_TYPES_TRANSACTION, **DATA_TYPES_ID).items() if
                f_type == "category"]


def read_set(_type):
    """Read both transactions and identity data."""
    print(f"Reading transactions data...")
    _df = pd.read_csv(os.path.join(DATA_PATH, f'{_type}_transaction.csv'),
                      index_col=IDX_LABEL, dtype=DATA_TYPES_TRANSACTION, nrows=250)

    print(f"Reading identity data...")
    _df = _df.join(pd.read_csv(os.path.join(DATA_PATH, f'{_type}_identity.csv'),
                               index_col=IDX_LABEL, dtype=DATA_TYPES_ID))
    return _df


def read_dataset():
    """Read whole data."""
    fetch_dataset()

    print(f"Reading train data...")
    train_set = read_set('train')

    print(f"Reading test data...")
    test_set = read_set('test')

    return train_set, test_set
[4]:
def preprocess_dataset(train_set, test_set):
    """Unite train and test into common dataframe."""
    # Create a new target column and remove a former one from the train data.
    print("Start data preprocessing...")
    train_set.pop('isFraud')
    train_set['isTest'] = 0
    test_set['isTest'] = 1

    # Preprocess categorical features.
    n_train = train_set.shape[0]
    for c in train_set.columns:
        s = train_set[c]
        if hasattr(s, 'cat'):
            u = union_categoricals([train_set[c], test_set[c]], sort_categories=True)
            train_set[c] = u[:n_train]
            test_set[c] = u[n_train:]

    # Unite train and test data.
    united = pd.concat([train_set, test_set])

    # Add additional features.
    united['TimeInDay'] = united.TransactionDT % 86400
    united['Cents'] = united.TransactionAmt % 1

    # Remove useless columns.
    united.drop("TransactionDT", axis=1, inplace=True)

    print(f"Dataset merged and preprocessed! Resulted shape: {united.shape}")

    return united
[ ]:
united_dataset = preprocess_dataset(*read_dataset())

Train-test split#

[6]:
X_train, X_test, y_train, y_test = train_test_split(united_dataset.drop(TARGET_COLUMN, axis=1),
                                                    united_dataset[TARGET_COLUMN], test_size=0.25)

Wrap dataset with Giskard#

To prepare for the vulnerability scan, make sure to wrap your dataset using Giskard’s Dataset class. More details here.

[7]:
raw_dataset = pd.concat([X_test, y_test], axis=1)
giskard_dataset = Dataset(
    df=raw_dataset,  # A pandas.DataFrame that contains the raw data (before all the pre-processing steps) and the actual ground truth variable (target).
    target=TARGET_COLUMN,  # Ground truth variable.
    name="fraud_detection_adversarial_dataset",   # Optional.
    cat_columns=CATEGORICALS  # List of categorical columns. Optional, but is a MUST if available. Inferred automatically if not.
)

Model building#

Build estimator#

[ ]:
# Define parameters of an estimator.
ESTIMATOR_PARAMS = {
    'num_leaves': 64,
    'objective': 'binary',
    'min_data_in_leaf': 10,
    'learning_rate': 0.1,
    'feature_fraction': 0.5,
    'bagging_fraction': 0.9,
    'bagging_freq': 1,
    'max_cat_to_onehot': 128,
    'metric': 'auc',
    'n_jobs': -1,
    'seed': 42,
    'subsample_for_bin': united_dataset.shape[0]
}

estimator = LGBMClassifier(**ESTIMATOR_PARAMS)
estimator.fit(X_train, y_train)

train_metric = roc_auc_score(y_train, estimator.predict_proba(X_train)[:, 1].T)
test_metric = roc_auc_score(y_test, estimator.predict_proba(X_test)[:, 1].T)

print(f"Train ROC-AUC score: {train_metric:.2f}")
print(f"Test ROC-AUC score: {test_metric:.2f}")

Wrap model with Giskard#

To prepare for the vulnerability scan, make sure to wrap your model using Giskard’s Model class. You can choose to either wrap the prediction function (preferred option) or the model object. More details here.

[9]:
def prediction_function(df: pd.DataFrame) -> np.ndarray:
    return estimator.predict_proba(df)
[ ]:
giskard_model = Model(
    model=prediction_function,  # A prediction function that encapsulates all the data pre-processing steps and that could be executed with the dataset used by the scan.
    model_type="classification",  # Either regression, classification or text_generation.
    name="train_test_data_classifier",  # Optional.
    classification_labels=[0, 1],  # Their order MUST be identical to the prediction_function's output order.
    feature_names=X_train.columns,  # Default: all columns of your dataset.
)

# Validate wrapped model.
wrapped_test_metric = roc_auc_score(y_test, giskard_model.predict(giskard_dataset).raw[:, 1].T)
print(f"Wrapped Test ROC-AUC score: {wrapped_test_metric:.2f}")

Detect vulnerabilities in your model#

Scan your model for vulnerabilities with Giskard#

Giskard’s scan allows you to detect vulnerabilities in your model automatically. These include performance biases, unrobustness, data leakage, stochasticity, underconfidence, ethical issues, and more. For detailed information about the scan feature, please refer to our scan documentation.

[ ]:
results = scan(giskard_model, giskard_dataset)
[12]:
display(results)

Generate comprehensive test suites automatically for your model#

Generate test suites from the scan#

The objects produced by the scan can be used as fixtures to generate a test suite that integrate all detected vulnerabilities. Test suites allow you to evaluate and validate your model’s performance, ensuring that it behaves as expected on a set of predefined test cases, and to identify any regressions or issues that might arise during development or updates.

[13]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
Executed 'Precision on data slice “`D15` >= 4.000 AND `D15` < 344.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12be228f0>, 'threshold': 0.8444444444444444}:
               Test failed
               Metric: 0.7


Executed 'Precision on data slice “`D4` >= 81.000”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12b6744f0>, 'threshold': 0.8444444444444444}:
               Test failed
               Metric: 0.75


Executed 'Accuracy on data slice “`D2` >= 108.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12be232b0>, 'threshold': 0.8664000000000001}:
               Test failed
               Metric: 0.79


Executed 'Accuracy on data slice “`C6` >= 1.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12be8ba30>, 'threshold': 0.8664000000000001}:
               Test failed
               Metric: 0.8


Executed 'Accuracy on data slice “`D11` >= 65.000”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12b6747c0>, 'threshold': 0.8664000000000001}:
               Test failed
               Metric: 0.81


Executed 'Precision on data slice “`V310` >= 48.475”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12b95b2b0>, 'threshold': 0.8444444444444444}:
               Test failed
               Metric: 0.79


Executed 'Precision on data slice “`C11` >= 1.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12be22200>, 'threshold': 0.8444444444444444}:
               Test failed
               Metric: 0.79


Executed 'Accuracy on data slice “`D5` >= 13.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12b676650>, 'threshold': 0.8664000000000001}:
               Test failed
               Metric: 0.81


Executed 'Precision on data slice “`C1` >= 2.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12be21ea0>, 'threshold': 0.8444444444444444}:
               Test failed
               Metric: 0.8


Executed 'Precision on data slice “`V283` < 0.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12be211e0>, 'threshold': 0.8444444444444444}:
               Test failed
               Metric: 0.8


Executed 'Precision on data slice “`V282` < 0.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12be8a470>, 'threshold': 0.8444444444444444}:
               Test failed
               Metric: 0.8


Executed 'Accuracy on data slice “`D3` >= 13.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12be8bc10>, 'threshold': 0.8664000000000001}:
               Test failed
               Metric: 0.82


Executed 'Precision on data slice “`V285` >= 0.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12b6779a0>, 'threshold': 0.8444444444444444}:
               Test failed
               Metric: 0.81


Executed 'Recall on data slice “`addr1` >= 312.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12b677760>, 'threshold': 0.8603773584905661}:
               Test failed
               Metric: 0.83


Executed 'Accuracy on data slice “`D10` >= 222.000”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12ba078b0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12b8fac20>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12be88e50>, 'threshold': 0.8664000000000001}:
               Test failed
               Metric: 0.84


[13]:
close Test suite failed. To debug your failing test and diagnose the issue, please run the Giskard hub (see documentation)
Test Precision on data slice “`D15` >= 4.000 AND `D15` < 344.500”
Measured Metric = 0.7 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `D15` >= 4.000 AND `D15` < 344.500
threshold 0.8444444444444444
Test Precision on data slice “`D4` >= 81.000”
Measured Metric = 0.75 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `D4` >= 81.000
threshold 0.8444444444444444
Test Accuracy on data slice “`D2` >= 108.500”
Measured Metric = 0.79412 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `D2` >= 108.500
threshold 0.8664000000000001
Test Accuracy on data slice “`C6` >= 1.500”
Measured Metric = 0.8 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `C6` >= 1.500
threshold 0.8664000000000001
Test Accuracy on data slice “`D11` >= 65.000”
Measured Metric = 0.80556 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `D11` >= 65.000
threshold 0.8664000000000001
Test Precision on data slice “`V310` >= 48.475”
Measured Metric = 0.78571 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `V310` >= 48.475
threshold 0.8444444444444444
Test Precision on data slice “`C11` >= 1.500”
Measured Metric = 0.79167 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `C11` >= 1.500
threshold 0.8444444444444444
Test Accuracy on data slice “`D5` >= 13.500”
Measured Metric = 0.8125 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `D5` >= 13.500
threshold 0.8664000000000001
Test Precision on data slice “`C1` >= 2.500”
Measured Metric = 0.8 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `C1` >= 2.500
threshold 0.8444444444444444
Test Precision on data slice “`V283` < 0.500”
Measured Metric = 0.8 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `V283` < 0.500
threshold 0.8444444444444444
Test Precision on data slice “`V282` < 0.500”
Measured Metric = 0.8 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `V282` < 0.500
threshold 0.8444444444444444
Test Accuracy on data slice “`D3` >= 13.500”
Measured Metric = 0.82353 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `D3` >= 13.500
threshold 0.8664000000000001
Test Precision on data slice “`V285` >= 0.500”
Measured Metric = 0.80645 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `V285` >= 0.500
threshold 0.8444444444444444
Test Recall on data slice “`addr1` >= 312.500”
Measured Metric = 0.83333 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `addr1` >= 312.500
threshold 0.8603773584905661
Test Accuracy on data slice “`D10` >= 222.000”
Measured Metric = 0.84375 close Failed
model af2b2aaa-c0d6-4428-9a9c-9aa288c718f4
dataset fraud_detection_adversarial_dataset
slicing_function `D10` >= 222.000
threshold 0.8664000000000001

Customize your suite by loading objects from the Giskard catalog#

The Giskard open source catalog will enable to load:

  • Tests such as metamorphic, performance, prediction & data drift, statistical tests, etc

  • Slicing functions such as detectors of toxicity, hate, emotion, etc

  • Transformation functions such as generators of typos, paraphrase, style tune, etc

To create custom tests, refer to this page.

For demo purposes, we will load a simple unit test (test_f1) that checks if the test F1 score is above the given threshold. For more examples of tests and functions, refer to the Giskard catalog.

[ ]:
test_suite.add_test(testing.test_f1(model=giskard_model, dataset=giskard_dataset, threshold=0.7)).run()

Debug and interact with your tests in the Giskard Hub#

At this point, you’ve created a test suite that is highly specific to your domain & use-case. Failing tests can be a pain to debug, which is why we encourage you to head over to the Giskard Hub.

Play around with a demo of the Giskard Hub on HuggingFace Spaces using this link.

More than just debugging tests, the Giskard Hub allows you to:

  • Compare models to decide which model to promote

  • Automatically create additional domain-specific tests through our automated model insights feature

  • Share your test results with team members and decision makers

The Giskard Hub can be deployed easily on HuggingFace Spaces. Other installation options are available in the documentation.

Here’s a sneak peek of automated model insights on a credit scoring classification model.

CleanShot 2023-09-26 at 18.38.09.png

CleanShot 2023-09-26 at 18.38.50.png

Upload your test suite to the Giskard Hub#

The entry point to the Giskard Hub is the upload of your test suite. Uploading the test suite will automatically save the model, dataset, tests, slicing & transformation functions to the Giskard Hub.

[ ]:
# Create a Giskard client after having install the Giskard server (see documentation)
api_key = "<Giskard API key>" #This can be found in the Settings tab of the Giskard hub
#hf_token = "<Your Giskard Space token>" #If the Giskard Hub is installed on HF Space, this can be found on the Settings tab of the Giskard Hub

client = GiskardClient(
    url="http://localhost:19000",  # Option 1: Use URL of your local Giskard instance.
    # url="<URL of your Giskard hub Space>",  # Option 2: Use URL of your remote HuggingFace space.
    key=api_key,
    # hf_token=hf_token  # Use this token to access a private HF space.
)

project_key = "my_project"
my_project = client.create_project(project_key, "PROJECT_NAME", "DESCRIPTION")

# Upload to the project you just created
test_suite.upload(client, project_key)

Download a test suite from the Giskard Hub#

After curating your test suites with additional tests on the Giskard Hub, you can easily download them back into your environment. This allows you to:

  • Check for regressions after training a new model

  • Automate the test suite execution in a CI/CD pipeline

  • Compare several models during the prototyping phase

[ ]:
test_suite_downloaded = Suite.download(client, project_key, suite_id=...)
test_suite_downloaded.run()