Open In Colab View Notebook on GitHub

Amazon reviews 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:

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

[40]:
%pip install giskard --upgrade

Import libraries

[2]:
import string
from pathlib import Path
from urllib.request import urlretrieve

import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, balanced_accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer

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

Notebook-level settings

[3]:
# Disable chained assignment warning.
pd.options.mode.chained_assignment = None

Define constants

[4]:
# Constants.
RANDOM_SEED = 0
TEST_RATIO = 0.2

TARGET_THRESHOLD = 0.5
TARGET_NAME = "isHelpful"

# Paths.
DATA_URL = "ftp://sys.giskard.ai/pub/unit_test_resources/amazon_review_dataset/reviews.json"
DATA_PATH = Path.home() / ".giskard" / "amazon_review_dataset" / "reviews.json"

Dataset preparation

Load and preprocess data

[5]:
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_json(DATA_PATH, lines=True, **kwargs)
    return _df


def preprocess_data(df: pd.DataFrame) -> pd.DataFrame:
    """Perform data-preprocessing steps."""
    print(f"Start data preprocessing...")

    # Select columns.
    df = df[["reviewText", "helpful"]]

    # Remove Null-characters (x00) from the dataset.
    df.reviewText = df.reviewText.apply(lambda x: x.replace("\x00", ""))

    # Extract numbers of helpful and total votes.
    df['helpful_ratings'] = df.helpful.apply(lambda x: x[0])
    df['total_ratings'] = df.helpful.apply(lambda x: x[1])

    # Filter unreasonable comments.
    df = df[df.total_ratings > 10]

    # Create target column.
    df[TARGET_NAME] = np.where((df.helpful_ratings / df.total_ratings) > TARGET_THRESHOLD, 1, 0).astype(int)

    # Delete columns we don't need anymore.
    df.drop(columns=["helpful", 'helpful_ratings', 'total_ratings'], inplace=True)

    print("Data preprocessing finished!")

    return df
[ ]:
reviews_df = download_data()
reviews_df = preprocess_data(reviews_df)

Train-test split

[7]:
X_train, X_test, y_train, y_test = train_test_split(reviews_df[["reviewText"]], reviews_df[TARGET_NAME],
                                                    test_size=TEST_RATIO, random_state=RANDOM_SEED,
                                                    stratify=reviews_df[TARGET_NAME])

Wrap dataset with Giskard

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

[10]:
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_NAME,  # Ground truth variable.
    name="reviews",  # Optional.
)

Model building

Define preprocessing pipeline

[11]:
def remove_punctuation(x):
    """Remove punctuation from input string."""
    x = x.reviewText.apply(lambda row: row.translate(str.maketrans('', '', string.punctuation)))
    return x


preprocessor = Pipeline(steps=[
    ("punctuation", FunctionTransformer(remove_punctuation)),
    ("vectorizer", TfidfVectorizer(stop_words='english', min_df=0.01))
])

Build estimator

[ ]:
pipeline = Pipeline(steps=[
    ("preprocessor", preprocessor),
    ("estimator", LogisticRegression(random_state=RANDOM_SEED, class_weight="balanced"))
])

pipeline.fit(X_train, y_train)

# ROC-AUC score.
train_metric = roc_auc_score(y_train, pipeline.predict_proba(X_train)[:, 1])
test_metric = roc_auc_score(y_test, pipeline.predict_proba(X_test)[:, 1])
print(f"Train ROC-AUC score: {train_metric:.2f}")
print(f"Test ROC-AUC score: {test_metric:.2f}")

# Balanced accuracy to account for imbalanced targets.
b_acc_train = balanced_accuracy_score(y_train, pipeline.predict(X_train))
b_acc_test = balanced_accuracy_score(y_test, pipeline.predict(X_test))
print(f"Train balanced accuracy: {b_acc_train:.2f}")
print(f"Test balanced accuracy: {b_acc_test:.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.

[ ]:
# Wrap prediction function so that the whole pipeline is uploaded to the Hub
def prediction_function(df):
    return pipeline.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="review_helpfulness_predictor",  # Optional.
    classification_labels=[0, 1],  # Their order MUST be identical to the prediction_function's output order.
    feature_names=["reviewText"],  # Default: all columns of your dataset.
)

# Validate wrapped model.
wrapped_predict = giskard_model.predict(giskard_dataset).raw[:, 1]
wrapped_test_metric = roc_auc_score(y_test, wrapped_predict)

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)
[15]:
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.

[16]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
Executed 'Invariance to “Add typos”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x1872d0cd0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12d09a800>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextTypoTransformation object at 0x10f76dea0>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
               Test failed
               Metric: 0.91
                - [TestMessageLevel.INFO] 9506 rows were perturbed

Executed 'Overconfidence on data slice “`reviewText` contains "don"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x1872d0cd0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12d09a800>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x16059c5e0>, 'threshold': 0.20729267505646984, 'p_threshold': 0.5}:
               Test failed
               Metric: 0.27


Executed 'Overconfidence on data slice “`text_length(reviewText)` < 174.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x1872d0cd0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12d09a800>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x12d0e7400>, 'threshold': 0.20729267505646984, 'p_threshold': 0.5}:
               Test failed
               Metric: 0.21


Executed 'Underconfidence on data slice “`reviewText` contains "better"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x1872d0cd0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12d09a800>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x15b49de10>, 'threshold': 0.03855220611244394, 'p_threshold': 0.95}:
               Test failed
               Metric: 0.05


Executed 'Underconfidence on data slice “`reviewText` contains "got"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x1872d0cd0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12d09a800>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x15b483bb0>, 'threshold': 0.03855220611244394, 'p_threshold': 0.95}:
               Test failed
               Metric: 0.05


Executed 'Underconfidence on data slice “`reviewText` contains "doesn"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x1872d0cd0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12d09a800>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x162696d10>, 'threshold': 0.03855220611244394, 'p_threshold': 0.95}:
               Test failed
               Metric: 0.04


Executed 'Underconfidence on data slice “`reviewText` contains "way"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x1872d0cd0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12d09a800>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1872d0f70>, 'threshold': 0.03855220611244394, 'p_threshold': 0.95}:
               Test failed
               Metric: 0.04


Executed 'Underconfidence on data slice “`reviewText` contains "good"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x1872d0cd0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12d09a800>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12d0be1a0>, 'threshold': 0.03855220611244394, 'p_threshold': 0.95}:
               Test failed
               Metric: 0.04


Executed 'Recall on data slice “`reviewText` contains "download"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x1872d0cd0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12d09a800>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x16061b8e0>, 'threshold': 0.6416057519472739}:
               Test failed
               Metric: 0.59


[16]:
close Test suite failed. To debug your failing test and diagnose the issue, please run the Giskard hub (see documentation)
Test Invariance to “Add typos”
Measured Metric = 0.90627 close Failed
model 2bbb4689-1208-4860-971f-add01cc7f3eb
dataset reviews
transformation_function Add typos
threshold 0.95
output_sensitivity 0.05
Test Overconfidence on data slice “`reviewText` contains "don"”
Measured Metric = 0.26578 close Failed
model 2bbb4689-1208-4860-971f-add01cc7f3eb
dataset reviews
slicing_function `reviewText` contains "don"
threshold 0.20729267505646984
p_threshold 0.5
Test Overconfidence on data slice “`text_length(reviewText)` < 174.500”
Measured Metric = 0.2119 close Failed
model 2bbb4689-1208-4860-971f-add01cc7f3eb
dataset reviews
slicing_function `text_length(reviewText)` < 174.500
threshold 0.20729267505646984
p_threshold 0.5
Test Underconfidence on data slice “`reviewText` contains "better"”
Measured Metric = 0.04526 close Failed
model 2bbb4689-1208-4860-971f-add01cc7f3eb
dataset reviews
slicing_function `reviewText` contains "better"
threshold 0.03855220611244394
p_threshold 0.95
Test Underconfidence on data slice “`reviewText` contains "got"”
Measured Metric = 0.04502 close Failed
model 2bbb4689-1208-4860-971f-add01cc7f3eb
dataset reviews
slicing_function `reviewText` contains "got"
threshold 0.03855220611244394
p_threshold 0.95
Test Underconfidence on data slice “`reviewText` contains "doesn"”
Measured Metric = 0.0415 close Failed
model 2bbb4689-1208-4860-971f-add01cc7f3eb
dataset reviews
slicing_function `reviewText` contains "doesn"
threshold 0.03855220611244394
p_threshold 0.95
Test Underconfidence on data slice “`reviewText` contains "way"”
Measured Metric = 0.04087 close Failed
model 2bbb4689-1208-4860-971f-add01cc7f3eb
dataset reviews
slicing_function `reviewText` contains "way"
threshold 0.03855220611244394
p_threshold 0.95
Test Underconfidence on data slice “`reviewText` contains "good"”
Measured Metric = 0.03938 close Failed
model 2bbb4689-1208-4860-971f-add01cc7f3eb
dataset reviews
slicing_function `reviewText` contains "good"
threshold 0.03855220611244394
p_threshold 0.95
Test Recall on data slice “`reviewText` contains "download"”
Measured Metric = 0.59292 close Failed
model 2bbb4689-1208-4860-971f-add01cc7f3eb
dataset reviews
slicing_function `reviewText` contains "download"
threshold 0.6416057519472739

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.

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()