Wage classification [scikit-learn]ยถ
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 to predict whether a person makes over 50K a year or not given their demographic variation.
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
Import librariesยถ
[2]:
from pathlib import Path
from urllib.request import urlretrieve
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from giskard import Model, Dataset, scan, testing, GiskardClient, Suite
Define constantsยถ
[3]:
# Constants
RANDOM_SEED = 0
TEST_RATIO = 0.2
DROP_FEATURES = [
'education',
'native-country',
'occupation',
'marital-status',
'educational-num'
]
CATEGORICAL_FEATURES = [
"workclass",
"relationship",
"race",
"gender"
]
NUMERICAL_FEATURES = [
"age",
"fnlwgt",
"capital-gain",
"capital-loss",
"hours-per-week",
]
TARGET_COLUMN = "income"
# Paths.
DATA_URL = "ftp://sys.giskard.ai/pub/unit_test_resources/wage_classification_dataset/adult.csv"
DATA_PATH = Path.home() / ".giskard" / "wage_classification_dataset" / "adult.csv"
Dataset preparationยถ
Load and preprocess dataยถ
[4]:
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 download_data(**kwargs) -> pd.DataFrame:
"""Download the dataset using URL."""
fetch_from_ftp(DATA_URL, DATA_PATH)
_df = pd.read_csv(DATA_PATH, **kwargs)
return _df
def preprocess_data(df: pd.DataFrame) -> pd.DataFrame:
# Drop NaNs and columns.
df = df.dropna()
df = df.drop(columns=DROP_FEATURES)
return df
[ ]:
income_df = download_data()
income_df = preprocess_data(income_df)
Train-test splitยถ
[6]:
X_train, X_test, y_train, y_test = train_test_split(income_df.drop(columns=TARGET_COLUMN), income_df[TARGET_COLUMN],
test_size=TEST_RATIO, 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.
[7]:
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_COLUMN, # Ground truth variable.
name="salary_data", # Optional.
cat_columns=CATEGORICAL_FEATURES
# List of categorical columns. Optional, but is a MUST if available. Inferred automatically if not.
)
Model buildingยถ
Define preprocessing pipelineยถ
[8]:
preprocessor = ColumnTransformer(transformers=[
("num", StandardScaler(), NUMERICAL_FEATURES),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), CATEGORICAL_FEATURES),
])
Build estimatorยถ
[ ]:
pipeline = Pipeline(steps=[
("preprocessor", preprocessor),
("classifier", RandomForestClassifier())
])
pipeline.fit(X_train, y_train)
# Accuracy score.
train_metric = pipeline.score(X_train, y_train)
test_metric = pipeline.score(X_test, y_test)
print(f'Train accuracy: {train_metric:.2f}')
print(f'Test accuracy: {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.
[ ]:
giskard_model = Model(
model=pipeline,
# 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="salary_cls", # Optional.
classification_labels=pipeline.classes_, # 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_predict = giskard_model.predict(giskard_dataset)
wrapped_test_metric = accuracy_score(y_test, wrapped_predict.prediction)
print(f'Wrapped Test accuracy: {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)
[13]:
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.
[14]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
Executed 'Overconfidence on data slice โ`hours-per-week` < 41.500โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12bccf100>, 'dataset': <giskard.datasets.base.Dataset object at 0x12bbb9de0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141f47550>, 'threshold': 0.5045638359329867, 'p_threshold': 0.5}:
Test failed
Metric: 0.51
Executed 'Underconfidence on data slice โ`relationship` == "Husband"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12bccf100>, 'dataset': <giskard.datasets.base.Dataset object at 0x12bbb9de0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141e86b60>, 'threshold': 0.01384993346299519, 'p_threshold': 0.95}:
Test failed
Metric: 0.02
Executed 'Underconfidence on data slice โ`age` >= 40.500 AND `age` < 56.500โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12bccf100>, 'dataset': <giskard.datasets.base.Dataset object at 0x12bbb9de0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141e65060>, 'threshold': 0.01384993346299519, 'p_threshold': 0.95}:
Test failed
Metric: 0.02
Executed 'Underconfidence on data slice โ`fnlwgt` < 128385.000 AND `fnlwgt` >= 99990.000โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12bccf100>, 'dataset': <giskard.datasets.base.Dataset object at 0x12bbb9de0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141e86230>, 'threshold': 0.01384993346299519, 'p_threshold': 0.95}:
Test failed
Metric: 0.02
Executed 'Underconfidence on data slice โ`gender` == "Male"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12bccf100>, 'dataset': <giskard.datasets.base.Dataset object at 0x12bbb9de0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141e870d0>, 'threshold': 0.01384993346299519, 'p_threshold': 0.95}:
Test failed
Metric: 0.01
Executed 'Recall on data slice โ`relationship` == "Own-child"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12bccf100>, 'dataset': <giskard.datasets.base.Dataset object at 0x12bbb9de0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141e5a230>, 'threshold': 0.5277777777777778}:
Test failed
Metric: 0.26
Executed 'Recall on data slice โ`workclass` == "?"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12bccf100>, 'dataset': <giskard.datasets.base.Dataset object at 0x12bbb9de0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141e70820>, 'threshold': 0.5277777777777778}:
Test failed
Metric: 0.33
Executed 'Recall on data slice โ`relationship` == "Not-in-family"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12bccf100>, 'dataset': <giskard.datasets.base.Dataset object at 0x12bbb9de0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141e589a0>, 'threshold': 0.5277777777777778}:
Test failed
Metric: 0.36
Executed 'Recall on data slice โ`workclass` == "Self-emp-not-inc"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12bccf100>, 'dataset': <giskard.datasets.base.Dataset object at 0x12bbb9de0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141e71120>, 'threshold': 0.5277777777777778}:
Test failed
Metric: 0.39
Executed 'Recall on data slice โ`race` == "Black"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12bccf100>, 'dataset': <giskard.datasets.base.Dataset object at 0x12bbb9de0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141e5a470>, 'threshold': 0.5277777777777778}:
Test failed
Metric: 0.39
Executed 'Recall on data slice โ`relationship` == "Unmarried"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12bccf100>, 'dataset': <giskard.datasets.base.Dataset object at 0x12bbb9de0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141e5a260>, 'threshold': 0.5277777777777778}:
Test failed
Metric: 0.41
Executed 'Recall on data slice โ`gender` == "Female"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12bccf100>, 'dataset': <giskard.datasets.base.Dataset object at 0x12bbb9de0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141e5a7d0>, 'threshold': 0.5277777777777778}:
Test failed
Metric: 0.5
[14]:
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.
[ ]:
# 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()