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
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
[ ]:
%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, Suite, GiskardClient, 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.
[5]:
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
[ ]:
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)
[14]:
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.
[15]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
Executed 'Invariance to โSwitch Religionโ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextReligionTransformation object at 0x155e21330>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
Test failed
Metric: 0.88
- [TestMessageLevel.INFO] 8 rows were perturbed
Executed 'Invariance to โSwitch countries from high- to low-income and vice versaโ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextNationalityTransformation object at 0x155e21390>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
Test failed
Metric: 0.85
- [TestMessageLevel.INFO] 137 rows were perturbed
Executed 'Invariance to โSwitch Genderโ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextGenderTransformation object at 0x1573947c0>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
Test failed
Metric: 0.95
- [TestMessageLevel.INFO] 396 rows were perturbed
/Users/mykytaalekseiev/Work/GiskardDevelopVersion/giskard-client/.venv/lib/python3.10/site-packages/numpy/core/fromnumeric.py:59: FutureWarning: 'DataFrame.swapaxes' is deprecated and will be removed in a future version. Please use 'DataFrame.transpose' instead.
return bound(*args, **kwds)
/Users/mykytaalekseiev/Work/GiskardDevelopVersion/giskard-client/.venv/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:2614: FutureWarning: The `pad_to_max_length` argument is deprecated and will be removed in a future version, use `padding=True` or `padding='longest'` to pad to the longest sequence in the batch, or use `padding='max_length'` to pad to a max length. In this case, you can give a specific length with `max_length` (e.g. `max_length=45`) or leave max_length to None to pad to the maximal input size of the model (e.g. 512 for Bert).
warnings.warn(
/var/folders/4q/3_bfyqnn7yv5jcjq98x2jf680000gn/T/ipykernel_27805/3117328017.py:61: UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument.
probs = torch.nn.functional.softmax(outputs.logits).detach().cpu().numpy()
Executed 'Invariance to โAdd typosโ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextTypoTransformation object at 0x154c23640>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
Test failed
Metric: 0.67
- [TestMessageLevel.INFO] 999 rows were perturbed
Executed 'Precision on data slice โ`Review` contains "loved"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x15b4d75b0>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.07
Executed 'Precision on data slice โ`Review` contains "complimentary"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x15b24ef50>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.08
Executed 'Precision on data slice โ`Review` contains "wonderful"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x15b113730>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.09
Executed 'Precision on data slice โ`Review` contains "perfect"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x15b510130>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.1
Executed 'Precision on data slice โ`Review` contains "quarter"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x15b4e99f0>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.1
Executed 'Precision on data slice โ`Review` contains "excellent"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x15b510c70>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.1
Executed 'Precision on data slice โ`Review` contains "french"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1575c4730>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.1
Executed 'Precision on data slice โ`avg_word_length(Review)` >= 5.983โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x15b1a64d0>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.1
Executed 'Precision on data slice โ`Review` contains "fantastic"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1573aa9b0>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.11
Executed 'Precision on data slice โ`Review` contains "choice"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x15b3f90c0>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.11
Executed 'Precision on data slice โ`Review` contains "beautiful"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x15b3f87f0>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.11
Executed 'Precision on data slice โ`Review` contains "enjoyed"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1573dc700>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.11
Executed 'Precision on data slice โ`Review` contains "love"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x15b1623b0>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.12
Executed 'Precision on data slice โ`Review` contains "suite"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1575f59c0>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.12
Executed 'Precision on data slice โ`Review` contains "orleans"โ' with arguments {'model': <__main__.GiskardModelCustomWrapper object at 0x12dd82590>, 'dataset': <giskard.datasets.base.Dataset object at 0x12c8268c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x15b4d6170>, 'threshold': 0.19474999999999998}:
Test failed
Metric: 0.12
[15]:
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.
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()