Drug 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:
Multinomial classification of a drugβs type.
Outline:
Detect vulnerabilities automatically with Giskardβs scan
Automatically generate & curate a comprehensive test suite to test your model beyond accuracy-related metrics
Install dependenciesΒΆ
Make sure to install the giskard
[ ]:
%pip install giskard --upgrade
Import librariesΒΆ
[1]:
from pathlib import Path
from urllib.request import urlretrieve
import numpy as np
import pandas as pd
from sklearn.svm import SVC
from imblearn.over_sampling import SMOTE
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
from imblearn.pipeline import Pipeline as PipelineImb
from giskard import Dataset, Model, scan, testing
Define constantsΒΆ
[2]:
# Constants.
RANDOM_SEED = 0
TARGET_NAME = "Drug"
AGE_BINS = [0, 19, 29, 39, 49, 59, 69, 80]
AGE_CATEGORIES = ['<20s', '20s', '30s', '40s', '50s', '60s', '>60s']
NA_TO_K_BINS = [0, 9, 19, 29, 50]
NA_TO_K_CATEGORIES = ['<10', '10-20', '20-30', '>30']
# Paths.
DATA_URL = "ftp://sys.giskard.ai/pub/unit_test_resources/drug_classification_dataset/drug200.csv"
DATA_PATH = Path.home() / ".giskard" / "drug_classification_dataset" / "drug200.csv"
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 load_data() -> pd.DataFrame:
"""Load data."""
fetch_from_ftp(DATA_URL, DATA_PATH)
df = pd.read_csv(DATA_PATH)
return df
def bin_numerical(df: pd.DataFrame) -> np.ndarray:
"""Perform numerical features binning."""
def _bin_age(_df: pd.DataFrame) -> pd.DataFrame:
"""Bin age feature."""
_df.Age = pd.cut(_df.Age, bins=AGE_BINS, labels=AGE_CATEGORIES)
return _df
def _bin_na_to_k(_df: pd.DataFrame) -> pd.DataFrame:
"""Bin Na_to_K feature."""
_df.Na_to_K = pd.cut(_df.Na_to_K, bins=NA_TO_K_BINS, labels=NA_TO_K_CATEGORIES)
return _df
df = df.copy()
df = _bin_age(df)
df = _bin_na_to_k(df)
return df
[ ]:
df_drug = load_data()
df_drug = bin_numerical(df_drug)
Train-test splitΒΆ
[5]:
X_train, X_test, y_train, y_test = train_test_split(df_drug.drop(TARGET_NAME, axis=1), df_drug[TARGET_NAME],
test_size=0.5, 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.
[ ]:
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_NAME, # Ground truth variable.
name="Drug classification dataset", # Optional.
cat_columns=X_test.columns.tolist() # List of categorical columns. Optional, but is a MUST if available. Inferred automatically if not.
)
Model buildingΒΆ
Build estimatorΒΆ
[ ]:
pipeline = PipelineImb(steps=[
("one_hot_encoder", OneHotEncoder()),
("resampler", SMOTE(random_state=RANDOM_SEED)),
("classifier", SVC(kernel='linear', random_state=RANDOM_SEED, probability=True))
])
pipeline.fit(X_train, y_train)
y_train_pred = pipeline.classes_[pipeline.predict_proba(X_train).argmax(axis=1)]
y_test_pred = pipeline.classes_[pipeline.predict_proba(X_test).argmax(axis=1)]
train_metric = accuracy_score(y_train, y_train_pred)
test_metric = accuracy_score(y_test, y_test_pred)
print(f"Train accuracy score: {train_metric:.2f}\n"
f"Test accuracy 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.
[ ]:
def prediction_function(df: pd.DataFrame) -> np.ndarray:
return pipeline.predict_proba(df)
wrapped_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="Drug classifier", # Optional.
classification_labels=pipeline.classes_, # Their order MUST be identical to the prediction_function's output order.
feature_names=X_test.columns # Default: all columns of your dataset.
)
# Validate wrapped model.
wrapped_y_test_pred = wrapped_model.predict(giskard_dataset).prediction
wrapped_test_metric = accuracy_score(y_test, wrapped_y_test_pred)
print(f"Wrapped Test accuracy 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(wrapped_model, giskard_dataset)
[10]:
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.
[11]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
2024-05-29 11:46:34,990 pid:52758 MainThread giskard.datasets.base INFO Casting dataframe columns from {'Age': 'category', 'Sex': 'object', 'BP': 'object', 'Cholesterol': 'object', 'Na_to_K': 'category'} to {'Age': 'category', 'Sex': 'object', 'BP': 'object', 'Cholesterol': 'object', 'Na_to_K': 'category'}
2024-05-29 11:46:34,993 pid:52758 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (22, 6) executed in 0:00:00.009771
Executed 'Precision on data slice β`Age` == "30s"β' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x178523b80>, 'dataset': <giskard.datasets.base.Dataset object at 0x1785cd450>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1787d4c70>, 'threshold': 0.76}:
Test failed
Metric: 0.68
2024-05-29 11:46:35,010 pid:52758 MainThread giskard.datasets.base INFO Casting dataframe columns from {'Age': 'category', 'Sex': 'object', 'BP': 'object', 'Cholesterol': 'object', 'Na_to_K': 'category'} to {'Age': 'category', 'Sex': 'object', 'BP': 'object', 'Cholesterol': 'object', 'Na_to_K': 'category'}
2024-05-29 11:46:35,011 pid:52758 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (33, 6) executed in 0:00:00.007762
Executed 'Precision on data slice β`BP` == "NORMAL"β' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x178523b80>, 'dataset': <giskard.datasets.base.Dataset object at 0x1785cd450>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1787b2b90>, 'threshold': 0.76}:
Test failed
Metric: 0.73
2024-05-29 11:46:35,023 pid:52758 MainThread giskard.datasets.base INFO Casting dataframe columns from {'Age': 'category', 'Sex': 'object', 'BP': 'object', 'Cholesterol': 'object', 'Na_to_K': 'category'} to {'Age': 'category', 'Sex': 'object', 'BP': 'object', 'Cholesterol': 'object', 'Na_to_K': 'category'}
2024-05-29 11:46:35,025 pid:52758 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (59, 6) executed in 0:00:00.006482
Executed 'Precision on data slice β`Na_to_K` == "10-20"β' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x178523b80>, 'dataset': <giskard.datasets.base.Dataset object at 0x1785cd450>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1787b16c0>, 'threshold': 0.76}:
Test failed
Metric: 0.73
2024-05-29 11:46:35,034 pid:52758 MainThread giskard.datasets.base INFO Casting dataframe columns from {'Age': 'category', 'Sex': 'object', 'BP': 'object', 'Cholesterol': 'object', 'Na_to_K': 'category'} to {'Age': 'category', 'Sex': 'object', 'BP': 'object', 'Cholesterol': 'object', 'Na_to_K': 'category'}
2024-05-29 11:46:35,036 pid:52758 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (53, 6) executed in 0:00:00.006638
Executed 'Precision on data slice β`Cholesterol` == "HIGH"β' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x178523b80>, 'dataset': <giskard.datasets.base.Dataset object at 0x1785cd450>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1787b0b80>, 'threshold': 0.76}:
Test failed
Metric: 0.75
2024-05-29 11:46:35,039 pid:52758 MainThread giskard.core.suite INFO Executed test suite 'My first test suite'
2024-05-29 11:46:35,040 pid:52758 MainThread giskard.core.suite INFO result: failed
2024-05-29 11:46:35,040 pid:52758 MainThread giskard.core.suite INFO Precision on data slice β`Age` == "30s"β ({'model': <giskard.models.function.PredictionFunctionModel object at 0x178523b80>, 'dataset': <giskard.datasets.base.Dataset object at 0x1785cd450>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1787d4c70>, 'threshold': 0.76}): {failed, metric=0.6818181818181818}
2024-05-29 11:46:35,040 pid:52758 MainThread giskard.core.suite INFO Precision on data slice β`BP` == "NORMAL"β ({'model': <giskard.models.function.PredictionFunctionModel object at 0x178523b80>, 'dataset': <giskard.datasets.base.Dataset object at 0x1785cd450>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1787b2b90>, 'threshold': 0.76}): {failed, metric=0.7272727272727273}
2024-05-29 11:46:35,041 pid:52758 MainThread giskard.core.suite INFO Precision on data slice β`Na_to_K` == "10-20"β ({'model': <giskard.models.function.PredictionFunctionModel object at 0x178523b80>, 'dataset': <giskard.datasets.base.Dataset object at 0x1785cd450>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1787b16c0>, 'threshold': 0.76}): {failed, metric=0.7288135593220338}
2024-05-29 11:46:35,041 pid:52758 MainThread giskard.core.suite INFO Precision on data slice β`Cholesterol` == "HIGH"β ({'model': <giskard.models.function.PredictionFunctionModel object at 0x178523b80>, 'dataset': <giskard.datasets.base.Dataset object at 0x1785cd450>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1787b0b80>, 'threshold': 0.76}): {failed, metric=0.7547169811320755}
[11]:
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=wrapped_model, dataset=giskard_dataset, threshold=0.7)).run()