Open In Colab View Notebook on GitHub

๐Ÿ“Š Tabular Quickstartยถ

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:

  • Binary classification. Whether Titanic passenger survived or not

  • Model: Logistic regression

  • Dataset: Titanic dataset

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ยถ

[1]:
%pip install giskard --upgrade

Import librariesยถ

[ ]:
import numpy as np
import pandas as pd

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

Define constantsยถ

[3]:
# Constants.
TARGET_COLUMN = "Survived"

CATEGORICAL_COLUMNS = ["Pclass", "Sex", "SibSp", "Parch", "Embarked"]

Dataset preparationยถ

Load dataยถ

[4]:
raw_data = demo.titanic_df()

Wrap dataset with Giskardยถ

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

[5]:
giskard_dataset = Dataset(
    df=raw_data,
    # 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="Titanic dataset",  # Optional
    cat_columns=CATEGORICAL_COLUMNS,
    # List of categorical columns. Optional, but is a MUST if available. Inferred automatically if not.
)

Model buildingยถ

Load modelยถ

[ ]:
preprocessing_function, classifier = demo.titanic_pipeline()

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.

[7]:
def prediction_function(df: pd.DataFrame) -> np.ndarray:
    preprocessed_df = preprocessing_function(df)
    return classifier.predict_proba(preprocessed_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="Titanic model",  # Optional
    classification_labels=classifier.classes_,
    # Their order MUST be identical to the prediction_function's output order
    feature_names=[
        "PassengerId",
        "Pclass",
        "Name",
        "Sex",
        "Age",
        "SibSp",
        "Parch",
        "Fare",
        "Embarked",
    ],  # Default: all columns of your dataset
)

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)

If you are running in a notebook, you can display the scan report directly in the notebook using display(...), otherwise you can export the report to an HTML file. Check the API Reference for more details on the export methods available on the ScanReport class.

[9]:
display(results)

# Save it to a file
results.to_html("scan_report.html")

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.

[ ]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()

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.

Hereโ€™s a sneak peak 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_token,
    # hf_token=hf_token  # Use this token to access a private HF space.
)

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

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

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, "my_project", 302)
test_suite_downloaded.run()