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

Install dependenciesยถ

Make sure to install the giskard

[ ]:
%pip install giskard --upgrade

Import librariesยถ

[1]:
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, scan, testing

Notebook-level settingsยถ

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

Define constantsยถ

[3]:
# 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ยถ

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

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

[ ]:
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ยถ

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

[13]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
2024-05-29 11:31:46,497 pid:47376 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'reviewText': 'object'} to {'reviewText': 'object'}
2024-05-29 11:31:46,501 pid:47376 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (9587, 2) executed in 0:00:00.015202
2024-05-29 11:31:47,278 pid:47376 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'reviewText': 'object'} to {'reviewText': 'object'}
2024-05-29 11:31:47,490 pid:47376 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (9587, 2) executed in 0:00:00.246625
2024-05-29 11:31:47,499 pid:47376 MainThread giskard.utils.logging_utils INFO     Perturb and predict data executed in 0:00:01.872730
2024-05-29 11:31:47,500 pid:47376 MainThread giskard.utils.logging_utils INFO     Compare and predict the data executed in 0:00:00.000723
Executed 'Invariance to โ€œAdd typosโ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextTypoTransformation object at 0x163469e70>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
               Test failed
               Metric: 0.9
                - [INFO] 9515 rows were perturbed

2024-05-29 11:31:47,559 pid:47376 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'reviewText': 'object'} to {'reviewText': 'object'}
2024-05-29 11:31:47,560 pid:47376 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (1554, 2) executed in 0:00:00.013542
Executed 'Overconfidence on data slice โ€œ`reviewText` contains "don"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x339cea860>, 'threshold': 0.20769479469770452, 'p_threshold': 0.5}:
               Test failed
               Metric: 0.27


2024-05-29 11:31:47,582 pid:47376 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'reviewText': 'object'} to {'reviewText': 'object'}
2024-05-29 11:31:47,584 pid:47376 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (4436, 2) executed in 0:00:00.016746
Executed 'Overconfidence on data slice โ€œ`text_length(reviewText)` < 174.500โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x3a11fe1d0>, 'threshold': 0.20769479469770452, 'p_threshold': 0.5}:
               Test failed
               Metric: 0.21


2024-05-29 11:31:47,641 pid:47376 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'reviewText': 'object'} to {'reviewText': 'object'}
2024-05-29 11:31:47,642 pid:47376 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (734, 2) executed in 0:00:00.008658
Executed 'Underconfidence on data slice โ€œ`reviewText` contains "way"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x33bcabd60>, 'threshold': 0.03912589965578388, 'p_threshold': 0.95}:
               Test failed
               Metric: 0.05


2024-05-29 11:31:47,698 pid:47376 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'reviewText': 'object'} to {'reviewText': 'object'}
2024-05-29 11:31:47,699 pid:47376 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (707, 2) executed in 0:00:00.008718
Executed 'Underconfidence on data slice โ€œ`reviewText` contains "better"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x33b84efe0>, 'threshold': 0.03912589965578388, 'p_threshold': 0.95}:
               Test failed
               Metric: 0.04


2024-05-29 11:31:47,756 pid:47376 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'reviewText': 'object'} to {'reviewText': 'object'}
2024-05-29 11:31:47,757 pid:47376 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (849, 2) executed in 0:00:00.009271
Executed 'Underconfidence on data slice โ€œ`reviewText` contains "want"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3380c1ea0>, 'threshold': 0.03912589965578388, 'p_threshold': 0.95}:
               Test failed
               Metric: 0.04


2024-05-29 11:31:47,813 pid:47376 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'reviewText': 'object'} to {'reviewText': 'object'}
2024-05-29 11:31:47,814 pid:47376 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (733, 2) executed in 0:00:00.007101
Executed 'Underconfidence on data slice โ€œ`reviewText` contains "got"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3aaa19ed0>, 'threshold': 0.03912589965578388, 'p_threshold': 0.95}:
               Test failed
               Metric: 0.04


2024-05-29 11:31:47,868 pid:47376 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'reviewText': 'object'} to {'reviewText': 'object'}
2024-05-29 11:31:47,869 pid:47376 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (538, 2) executed in 0:00:00.006875
Executed 'Recall on data slice โ€œ`reviewText` contains "download"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x339c7beb0>, 'threshold': 0.6419472738166567}:
               Test failed
               Metric: 0.59


2024-05-29 11:31:47,872 pid:47376 MainThread giskard.core.suite INFO     Executed test suite 'My first test suite'
2024-05-29 11:31:47,873 pid:47376 MainThread giskard.core.suite INFO     result: failed
2024-05-29 11:31:47,873 pid:47376 MainThread giskard.core.suite INFO     Invariance to โ€œAdd typosโ€ ({'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextTypoTransformation object at 0x163469e70>, 'threshold': 0.95, 'output_sensitivity': 0.05}): {failed, metric=0.9038360483447189}
2024-05-29 11:31:47,873 pid:47376 MainThread giskard.core.suite INFO     Overconfidence on data slice โ€œ`reviewText` contains "don"โ€ ({'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x339cea860>, 'threshold': 0.20769479469770452, 'p_threshold': 0.5}): {failed, metric=0.26622296173044924}
2024-05-29 11:31:47,873 pid:47376 MainThread giskard.core.suite INFO     Overconfidence on data slice โ€œ`text_length(reviewText)` < 174.500โ€ ({'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x3a11fe1d0>, 'threshold': 0.20769479469770452, 'p_threshold': 0.5}): {failed, metric=0.21353196772191185}
2024-05-29 11:31:47,874 pid:47376 MainThread giskard.core.suite INFO     Underconfidence on data slice โ€œ`reviewText` contains "way"โ€ ({'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x33bcabd60>, 'threshold': 0.03912589965578388, 'p_threshold': 0.95}): {failed, metric=0.04904632152588556}
2024-05-29 11:31:47,874 pid:47376 MainThread giskard.core.suite INFO     Underconfidence on data slice โ€œ`reviewText` contains "better"โ€ ({'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x33b84efe0>, 'threshold': 0.03912589965578388, 'p_threshold': 0.95}): {failed, metric=0.042432814710042434}
2024-05-29 11:31:47,874 pid:47376 MainThread giskard.core.suite INFO     Underconfidence on data slice โ€œ`reviewText` contains "want"โ€ ({'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3380c1ea0>, 'threshold': 0.03912589965578388, 'p_threshold': 0.95}): {failed, metric=0.04240282685512368}
2024-05-29 11:31:47,874 pid:47376 MainThread giskard.core.suite INFO     Underconfidence on data slice โ€œ`reviewText` contains "got"โ€ ({'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3aaa19ed0>, 'threshold': 0.03912589965578388, 'p_threshold': 0.95}): {failed, metric=0.03956343792633015}
2024-05-29 11:31:47,875 pid:47376 MainThread giskard.core.suite INFO     Recall on data slice โ€œ`reviewText` contains "download"โ€ ({'model': <giskard.models.function.PredictionFunctionModel object at 0x107c5e110>, 'dataset': <giskard.datasets.base.Dataset object at 0x1634696c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x339c7beb0>, 'threshold': 0.6419472738166567}): {failed, metric=0.5929203539823009}
[13]:
close Test suite failed.
Test Invariance to โ€œAdd typosโ€
Measured Metric = 0.90384 close Failed
model review_helpfulness_predictor
dataset reviews
transformation_function Add typos
threshold 0.95
output_sensitivity 0.05
Test Overconfidence on data slice โ€œ`reviewText` contains "don"โ€
Measured Metric = 0.26622 close Failed
model review_helpfulness_predictor
dataset reviews
slicing_function `reviewText` contains "don"
threshold 0.20769479469770452
p_threshold 0.5
Test Overconfidence on data slice โ€œ`text_length(reviewText)` < 174.500โ€
Measured Metric = 0.21353 close Failed
model review_helpfulness_predictor
dataset reviews
slicing_function `text_length(reviewText)` < 174.500
threshold 0.20769479469770452
p_threshold 0.5
Test Underconfidence on data slice โ€œ`reviewText` contains "way"โ€
Measured Metric = 0.04905 close Failed
model review_helpfulness_predictor
dataset reviews
slicing_function `reviewText` contains "way"
threshold 0.03912589965578388
p_threshold 0.95
Test Underconfidence on data slice โ€œ`reviewText` contains "better"โ€
Measured Metric = 0.04243 close Failed
model review_helpfulness_predictor
dataset reviews
slicing_function `reviewText` contains "better"
threshold 0.03912589965578388
p_threshold 0.95
Test Underconfidence on data slice โ€œ`reviewText` contains "want"โ€
Measured Metric = 0.0424 close Failed
model review_helpfulness_predictor
dataset reviews
slicing_function `reviewText` contains "want"
threshold 0.03912589965578388
p_threshold 0.95
Test Underconfidence on data slice โ€œ`reviewText` contains "got"โ€
Measured Metric = 0.03956 close Failed
model review_helpfulness_predictor
dataset reviews
slicing_function `reviewText` contains "got"
threshold 0.03912589965578388
p_threshold 0.95
Test Recall on data slice โ€œ`reviewText` contains "download"โ€
Measured Metric = 0.59292 close Failed
model review_helpfulness_predictor
dataset reviews
slicing_function `reviewText` contains "download"
threshold 0.6419472738166567

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