Breast cancer detection [XGBoost]¶
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 the patient has the breast cancer.
Model:
XGBClassifier
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
[13]:
%pip install giskard --upgrade
Import libraries¶
[1]:
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
from giskard import Dataset, Model, scan, testing, Suite, GiskardClient
Define constants¶
[2]:
# Constants.
TARGET_COLUMN_NAME = "target"
RANDOM_SEED = 42
Dataset preparation¶
Load data¶
[3]:
data = load_breast_cancer(as_frame=True)
features = data['data']
target = data[TARGET_COLUMN_NAME]
Train-test split¶
[4]:
# Train/test split.
X_train, X_test, y_train, y_test = train_test_split(features.loc[:, features.columns != TARGET_COLUMN_NAME], target,
random_state=RANDOM_SEED)
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]:
raw_data = pd.concat([X_test, y_test], axis=1)
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", # Ground truth variable.
name="breast_cancer", # Optional.
)
Model building¶
Build estimator¶
[ ]:
xgb = XGBClassifier()
xgb.fit(X_train, y_train)
# Evaluation.
y_test_pred = xgb.predict(X_test)
print(classification_report(y_test, y_test_pred))
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.
[ ]:
giskard_model = Model(
model=xgb,
# 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="breast_cancer_xgboost", # Optional.
classification_labels=[0, 1], # Their order MUST be identical to the prediction_function's output order.
feature_names=X_test.columns, # Default: all columns of your dataset.
)
# Validate the model wrapping.
y_test_pred_wrapped = giskard_model.predict(giskard_dataset).raw_prediction
print(classification_report(y_test, y_test_pred_wrapped))
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)
[9]:
display(results) # in your notebook
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.
[10]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
Executed 'Nominal association (Theil's U) on data slice “`worst concave points` >= 0.144”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14309f5b0>, 'threshold': 0.5}:
Test failed
Metric: 0.77
- [TestMessageLevel.INFO] metric = 0.7745014140794255, threshold = 0.5
Executed 'Nominal association (Theil's U) on data slice “`worst radius` >= 17.420”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x142dcc160>, 'threshold': 0.5}:
Test failed
Metric: 0.76
- [TestMessageLevel.INFO] metric = 0.7639160128151123, threshold = 0.5
Executed 'Nominal association (Theil's U) on data slice “`worst perimeter` >= 110.950”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430ec4c0>, 'threshold': 0.5}:
Test failed
Metric: 0.74
- [TestMessageLevel.INFO] metric = 0.7427987555404146, threshold = 0.5
Executed 'Nominal association (Theil's U) on data slice “`worst area` >= 885.950”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430ed390>, 'threshold': 0.5}:
Test failed
Metric: 0.71
- [TestMessageLevel.INFO] metric = 0.7131111241996619, threshold = 0.5
Executed 'Nominal association (Theil's U) on data slice “`mean concave points` >= 0.053”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430c8f10>, 'threshold': 0.5}:
Test failed
Metric: 0.64
- [TestMessageLevel.INFO] metric = 0.6377395426892722, threshold = 0.5
Executed 'Nominal association (Theil's U) on data slice “`mean perimeter` >= 96.380”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430ef880>, 'threshold': 0.5}:
Test failed
Metric: 0.62
- [TestMessageLevel.INFO] metric = 0.6227293846650519, threshold = 0.5
Executed 'Nominal association (Theil's U) on data slice “`mean radius` >= 15.060”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14309ecb0>, 'threshold': 0.5}:
Test failed
Metric: 0.61
- [TestMessageLevel.INFO] metric = 0.6087180717056299, threshold = 0.5
Executed 'Nominal association (Theil's U) on data slice “`mean area` >= 697.300”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14309ef80>, 'threshold': 0.5}:
Test failed
Metric: 0.61
- [TestMessageLevel.INFO] metric = 0.6087180717056299, threshold = 0.5
Executed 'Nominal association (Theil's U) on data slice “`area error` >= 39.690”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x142e7dc00>, 'threshold': 0.5}:
Test failed
Metric: 0.52
- [TestMessageLevel.INFO] metric = 0.5166070702259753, threshold = 0.5
Executed 'Accuracy on data slice “`worst radius` >= 14.765 AND `worst radius` < 17.625”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14309b670>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.8
Executed 'Accuracy on data slice “`mean radius` >= 13.310 AND `mean radius` < 15.005”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14309ed10>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.8
Executed 'Accuracy on data slice “`mean perimeter` >= 86.140 AND `mean perimeter` < 98.085”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430ca290>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.8
Executed 'Accuracy on data slice “`worst perimeter` >= 96.625 AND `worst perimeter` < 122.350”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430c95d0>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.8
Executed 'Accuracy on data slice “`mean area` >= 518.300 AND `mean area` < 664.350”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430ca9e0>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.8
Executed 'Accuracy on data slice “`mean concavity` >= 0.078 AND `mean concavity` < 0.140”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430ed4b0>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.8
Executed 'Accuracy on data slice “`mean concave points` >= 0.048 AND `mean concave points` < 0.079”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430ec340>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.8
Executed 'Accuracy on data slice “`worst area` >= 610.200 AND `worst area` < 828.500”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430cb3a0>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.82
Executed 'Accuracy on data slice “`fractal dimension error` < 0.003 AND `fractal dimension error` >= 0.002”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14309d6f0>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.83
Executed 'Accuracy on data slice “`worst concavity` >= 0.277 AND `worst concavity` < 0.415”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14309fc70>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.83
Executed 'Accuracy on data slice “`compactness error` >= 0.020 AND `compactness error` < 0.030”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14309db70>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.84
Executed 'Accuracy on data slice “`mean compactness` >= 0.099 AND `mean compactness` < 0.128”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430c8340>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.84
Executed 'Recall on data slice “`concave points error` >= 0.009 AND `concave points error` < 0.015”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430edd20>, 'threshold': 0.9179775280898876}:
Test failed
Metric: 0.88
Executed 'Accuracy on data slice “`perimeter error` < 2.151 AND `perimeter error` >= 1.505”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430cbd90>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.89
Executed 'Accuracy on data slice “`area error` < 40.745 AND `area error` >= 19.215”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12ce6f670>, 'dataset': <giskard.datasets.base.Dataset object at 0x12cce5ae0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1430c8850>, 'threshold': 0.9101398601398601}:
Test failed
Metric: 0.89
[10]:
Customize your suite by loading objects from the Giskard catalog¶
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 peek of automated model insights on a credit scoring classification model.
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()