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:
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 typing import Union, List
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 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 = "https://giskard-library-test-datasets.s3.eu-north-1.amazonaws.com/tripadvisor_reviews_dataset-{}"
DATA_PATH = Path.home() / ".giskard" / "tripadvisor_reviews_dataset"
DATA_FILE_NAME = "tripadvisor_hotel_reviews.csv.tar.gz"
[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_demo_data(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_demo_data(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]:
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()