Open In Colab View Notebook on GitHub

Tripadvisor reviews sentiment classification [HuggingFace]

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 review’s sentiment.

  • Model

  • Dataset

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 random
import re
import string
from dataclasses import dataclass
from pathlib import Path
from urllib.request import urlretrieve

import nltk
import numpy as np
import pandas as pd
import torch
from nltk.corpus import stopwords
from torch.utils.data import DataLoader
from torch.utils.data import TensorDataset
from transformers import DistilBertForSequenceClassification, DistilBertTokenizer
from typing import Union, List

from giskard import Dataset, Model, scan, testing

Define constants

[2]:
# Constants
TEXT_COLUMN_NAME = "Review"
TARGET_COLUMN_NAME = "label"

MAX_NUM_ROWS = 1000

PRETRAINED_WEIGHTS_NAME = "distilbert-base-uncased"
STOP_WORDS = set(stopwords.words('english'))
RANDOM_SEED = 0

DATA_URL = "ftp://sys.giskard.ai/pub/unit_test_resources/tripadvisor_reviews_dataset/{}"
DATA_PATH = Path.home() / ".giskard" / "tripadvisor_reviews_dataset"
DATA_FILE_NAME = "tripadvisor_hotel_reviews.csv"
[3]:
# Set random seeds
random.seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
torch.manual_seed(RANDOM_SEED)
torch.cuda.manual_seed_all(RANDOM_SEED)

Dataset preparation

Load data

[ ]:
nltk.download('stopwords')


# Define data download and pre-processing functions
def fetch_from_ftp(url: str, file: Path) -> None:
    if not file.parent.exists():
        file.parent.mkdir(parents=True, exist_ok=True)

    if not file.exists():
        urlretrieve(url, file)


def create_label(x: int) -> int:
    """Map rating to the label."""
    if x in [1, 2]:
        return 0
    if x == 3:
        return 1
    if x in [4, 5]:
        return 2


class TextCleaner:
    """Helper class to preprocess review's text."""

    def __init__(self, clean_pattern: str = r"[^A-ZĞÜŞİÖÇIa-zğüı'şöç0-9.\"',()]"):
        """Constructor of the class."""
        self.clean_pattern = clean_pattern

    def __call__(self, text: Union[str, list]) -> List[List[str]]:
        """Perform cleaning."""
        if isinstance(text, str):
            docs = [[text]]

        if isinstance(text, list):
            docs = text

        text = [[re.sub(self.clean_pattern, " ", sentence) for sentence in sentences] for sentences in docs]
        return text


def remove_emoji(data: str) -> str:
    """Remove emoji from the text."""
    emoji = re.compile(
        "["
        u"\U0001F600-\U0001F64F"
        u"\U0001F300-\U0001F5FF"
        u"\U0001F680-\U0001F6FF"
        u"\U0001F1E0-\U0001F1FF"
        u"\U00002500-\U00002BEF"
        u"\U00002702-\U000027B0"
        u"\U00002702-\U000027B0"
        u"\U000024C2-\U0001F251"
        u"\U0001f926-\U0001f937"
        u"\U00010000-\U0010ffff"
        u"\u2640-\u2642"
        u"\u2600-\u2B55"
        u"\u200d"
        u"\u23cf"
        u"\u23e9"
        u"\u231a"
        u"\ufe0f"
        u"\u3030"
        "]+",
        re.UNICODE,
    )
    return re.sub(emoji, '', data)


regex = re.compile('[%s]' % re.escape(string.punctuation))


def remove_punctuation(text: str) -> str:
    """Remove punctuation from the text."""
    text = regex.sub(" ", text)
    return text


text_cleaner = TextCleaner()


def text_preprocessor(df: pd.DataFrame) -> pd.DataFrame:
    """Preprocess text."""
    # Remove emoji.
    df[TEXT_COLUMN_NAME] = df[TEXT_COLUMN_NAME].apply(lambda x: remove_emoji(x))

    # Lower.
    df[TEXT_COLUMN_NAME] = df[TEXT_COLUMN_NAME].apply(lambda x: x.lower())

    # Clean.
    df[TEXT_COLUMN_NAME] = df[TEXT_COLUMN_NAME].apply(lambda x: text_cleaner(x)[0][0])

    # Remove punctuation.
    df[TEXT_COLUMN_NAME] = df[TEXT_COLUMN_NAME].apply(lambda x: remove_punctuation(x))

    return df


def load_dataset() -> pd.DataFrame:
    # Download dataset
    fetch_from_ftp(DATA_URL.format(DATA_FILE_NAME), DATA_PATH / DATA_FILE_NAME)
    df = pd.read_csv(DATA_PATH / DATA_FILE_NAME, nrows=MAX_NUM_ROWS)
    # Obtain labels for our task.
    df[TARGET_COLUMN_NAME] = df.Rating.apply(lambda x: create_label(x))
    df.drop(columns="Rating", inplace=True)
    df = text_preprocessor(df)
    return df

Wrap dataset with Giskard

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

[ ]:
giskard_dataset = Dataset(
    df=load_dataset(),
    # A pandas.DataFrame that contains the raw data (before all the pre-processing steps) and the actual ground truth variable (target).
    target=TARGET_COLUMN_NAME,  # Ground truth variable.
    name="Trip advisor reviews sentiment",  # Optional.
)

Model building

Build estimator

[ ]:
@dataclass
class Config:
    """Configuration of Distill-BERT model."""

    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    batch_size = 128
    seq_length = 150
    add_special_tokens = True
    return_attention_mask = True
    pad_to_max_length = True
    return_tensors = 'pt'


# Load tokenizer.
tokenizer = DistilBertTokenizer.from_pretrained(PRETRAINED_WEIGHTS_NAME)

# Load model.
giskard_model = DistilBertForSequenceClassification.from_pretrained(
    PRETRAINED_WEIGHTS_NAME, num_labels=3, output_attentions=False, output_hidden_states=False
).to(Config.device)


def create_dataloader(df: pd.DataFrame) -> DataLoader:
    """Create dataloader object with input data."""

    def _create_dataset(encoded_data: dict) -> TensorDataset:
        """Create dataset object with input data."""
        input_ids = encoded_data['input_ids']
        attention_masks = encoded_data['attention_mask']
        return TensorDataset(input_ids, attention_masks)

    # Tokenize data.
    encoded_data = tokenizer.batch_encode_plus(
        df.Review.values,
        add_special_tokens=Config.add_special_tokens,
        return_attention_mask=Config.return_attention_mask,
        pad_to_max_length=Config.pad_to_max_length,
        max_length=Config.seq_length,
        return_tensors=Config.return_tensors,
    )

    # Create dataset object.
    dataset = _create_dataset(encoded_data)

    # Create and return dataloader object.
    return DataLoader(dataset, batch_size=Config.batch_size)


def infer_predictions(_model: torch.nn.Module, _dataloader: DataLoader) -> np.ndarray:
    """Perform inference using given model on given dataloader."""
    _model.eval()

    y_pred = list()
    for batch in _dataloader:
        batch = tuple(b.to(Config.device) for b in batch)
        inputs = {'input_ids': batch[0], 'attention_mask': batch[1]}

        with torch.no_grad():
            outputs = _model(**inputs)

        probs = torch.nn.functional.softmax(outputs.logits).detach().cpu().numpy()
        y_pred.append(probs)

    y_pred = np.concatenate(y_pred, axis=0)
    return y_pred


text_cleaner = TextCleaner()

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.

[7]:
class GiskardModelCustomWrapper(Model):
    """Custom giskard model wrapper."""

    def model_predict(self, df: pd.DataFrame) -> np.ndarray:
        """Perform inference using overwritten prediction logic."""
        cleaned_df = text_preprocessor(df)
        data_loader = create_dataloader(cleaned_df)
        predicted_probabilities = infer_predictions(self.model, data_loader)
        return predicted_probabilities
[8]:
giskard_model = GiskardModelCustomWrapper(
    model=giskard_model,
    # 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="Trip advisor sentiment classifier",  # Optional.
    classification_labels=[0, 1, 2],  # Their order MUST be identical to the prediction_function's output order.
    feature_names=[TEXT_COLUMN_NAME],  # Default: all columns of your dataset.
)

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)
[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 14:07:23,236 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,237 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (54, 2) executed in 0:00:00.009851
Executed 'Precision on data slice “`Review` contains "manager"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345de5b40>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.24


2024-05-29 14:07:23,259 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,260 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (56, 2) executed in 0:00:00.007041
Executed 'Precision on data slice “`Review` contains "tiny"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345d4f8b0>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.3


2024-05-29 14:07:23,278 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,279 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (74, 2) executed in 0:00:00.005584
Executed 'Precision on data slice “`Review` contains "said"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x341e9a860>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.39


2024-05-29 14:07:23,297 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,298 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (76, 2) executed in 0:00:00.005489
Executed 'Precision on data slice “`Review` contains "air"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345ee65f0>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.39


2024-05-29 14:07:23,316 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,319 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (57, 2) executed in 0:00:00.009502
Executed 'Precision on data slice “`Review` contains "elevator"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x341f15c00>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.4


2024-05-29 14:07:23,337 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,338 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (52, 2) executed in 0:00:00.006870
Executed 'Precision on data slice “`Review` contains "reservation"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x342210790>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.4


2024-05-29 14:07:23,355 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,356 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (93, 2) executed in 0:00:00.005766
Executed 'Precision on data slice “`Review` contains "bad"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345e2aef0>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.43


2024-05-29 14:07:23,374 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,375 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (60, 2) executed in 0:00:00.006260
Executed 'Precision on data slice “`Review` contains "hear"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x341f72800>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.43


2024-05-29 14:07:23,392 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,393 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (53, 2) executed in 0:00:00.006900
Executed 'Precision on data slice “`Review` contains "average"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345e8ecb0>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.43


2024-05-29 14:07:23,597 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,598 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (83, 2) executed in 0:00:00.006237
Executed 'Precision on data slice “`Review` contains "work"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345e78430>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.45


2024-05-29 14:07:23,615 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,616 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (61, 2) executed in 0:00:00.006405
Executed 'Precision on data slice “`Review` contains "noisy"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345e2bc70>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.48


2024-05-29 14:07:23,632 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,633 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (83, 2) executed in 0:00:00.006357
Executed 'Precision on data slice “`Review` contains "times"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x342175420>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.48


2024-05-29 14:07:23,648 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,649 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (94, 2) executed in 0:00:00.006226
Executed 'Precision on data slice “`Review` contains "days"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x341f07cd0>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.49


2024-05-29 14:07:23,666 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,668 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (73, 2) executed in 0:00:00.006877
Executed 'Precision on data slice “`Review` contains "know"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x341eacb80>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.49


2024-05-29 14:07:23,684 pid:70250 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'Review': 'object'} to {'Review': 'object'}
2024-05-29 14:07:23,685 pid:70250 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (81, 2) executed in 0:00:00.006585
Executed 'Precision on data slice “`Review` contains "minutes"”' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345df7130>, 'threshold': 0.61275}:
               Test failed
               Metric: 0.49


2024-05-29 14:07:23,688 pid:70250 MainThread giskard.core.suite INFO     Executed test suite 'My first test suite'
2024-05-29 14:07:23,688 pid:70250 MainThread giskard.core.suite INFO     result: failed
2024-05-29 14:07:23,688 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "manager"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345de5b40>, 'threshold': 0.61275}): {failed, metric=0.24074074074074073}
2024-05-29 14:07:23,688 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "tiny"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345d4f8b0>, 'threshold': 0.61275}): {failed, metric=0.30357142857142855}
2024-05-29 14:07:23,689 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "said"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x341e9a860>, 'threshold': 0.61275}): {failed, metric=0.3918918918918919}
2024-05-29 14:07:23,689 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "air"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345ee65f0>, 'threshold': 0.61275}): {failed, metric=0.39473684210526316}
2024-05-29 14:07:23,689 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "elevator"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x341f15c00>, 'threshold': 0.61275}): {failed, metric=0.40350877192982454}
2024-05-29 14:07:23,689 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "reservation"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x342210790>, 'threshold': 0.61275}): {failed, metric=0.40384615384615385}
2024-05-29 14:07:23,690 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "bad"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345e2aef0>, 'threshold': 0.61275}): {failed, metric=0.43010752688172044}
2024-05-29 14:07:23,690 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "hear"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x341f72800>, 'threshold': 0.61275}): {failed, metric=0.43333333333333335}
2024-05-29 14:07:23,690 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "average"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345e8ecb0>, 'threshold': 0.61275}): {failed, metric=0.4339622641509434}
2024-05-29 14:07:23,690 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "work"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345e78430>, 'threshold': 0.61275}): {failed, metric=0.4457831325301205}
2024-05-29 14:07:23,691 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "noisy"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345e2bc70>, 'threshold': 0.61275}): {failed, metric=0.47540983606557374}
2024-05-29 14:07:23,691 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "times"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x342175420>, 'threshold': 0.61275}): {failed, metric=0.4819277108433735}
2024-05-29 14:07:23,691 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "days"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x341f07cd0>, 'threshold': 0.61275}): {failed, metric=0.48936170212765956}
2024-05-29 14:07:23,691 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "know"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x341eacb80>, 'threshold': 0.61275}): {failed, metric=0.4931506849315068}
2024-05-29 14:07:23,692 pid:70250 MainThread giskard.core.suite INFO     Precision on data slice “`Review` contains "minutes"” ({'model': <__main__.GiskardModelCustomWrapper object at 0x3215bda50>, 'dataset': <giskard.datasets.base.Dataset object at 0x308a05960>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x345df7130>, 'threshold': 0.61275}): {failed, metric=0.49382716049382713}
[11]:
close Test suite failed.
Test Precision on data slice “`Review` contains "manager"”
Measured Metric = 0.24074 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "manager"
threshold 0.61275
Test Precision on data slice “`Review` contains "tiny"”
Measured Metric = 0.30357 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "tiny"
threshold 0.61275
Test Precision on data slice “`Review` contains "said"”
Measured Metric = 0.39189 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "said"
threshold 0.61275
Test Precision on data slice “`Review` contains "air"”
Measured Metric = 0.39474 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "air"
threshold 0.61275
Test Precision on data slice “`Review` contains "elevator"”
Measured Metric = 0.40351 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "elevator"
threshold 0.61275
Test Precision on data slice “`Review` contains "reservation"”
Measured Metric = 0.40385 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "reservation"
threshold 0.61275
Test Precision on data slice “`Review` contains "bad"”
Measured Metric = 0.43011 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "bad"
threshold 0.61275
Test Precision on data slice “`Review` contains "hear"”
Measured Metric = 0.43333 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "hear"
threshold 0.61275
Test Precision on data slice “`Review` contains "average"”
Measured Metric = 0.43396 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "average"
threshold 0.61275
Test Precision on data slice “`Review` contains "work"”
Measured Metric = 0.44578 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "work"
threshold 0.61275
Test Precision on data slice “`Review` contains "noisy"”
Measured Metric = 0.47541 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "noisy"
threshold 0.61275
Test Precision on data slice “`Review` contains "times"”
Measured Metric = 0.48193 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "times"
threshold 0.61275
Test Precision on data slice “`Review` contains "days"”
Measured Metric = 0.48936 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "days"
threshold 0.61275
Test Precision on data slice “`Review` contains "know"”
Measured Metric = 0.49315 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "know"
threshold 0.61275
Test Precision on data slice “`Review` contains "minutes"”
Measured Metric = 0.49383 close Failed
model Trip advisor sentiment classifier
dataset Trip advisor reviews sentiment
slicing_function `Review` contains "minutes"
threshold 0.61275

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