Open In Colab View Notebook on GitHub

Airline tweets sentiment analysis [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 the airline tweets.

  • 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

We also install the project-specific dependencies for this tutorial.

[ ]:
%pip install accelerate --upgrade

Import libraries

[1]:
import numpy as np
import pandas as pd
import torch
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
from torch.utils.data import Dataset as TorchDataset
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification, TrainingArguments, Trainer
from transformers.integrations import MLflowCallback, TensorBoardCallback, WandbCallback

from giskard import Dataset, Model, scan, testing

Define constants

[2]:
# Constants.
RANDOM_SEED = 0

TEXT_COLUMN_NAME = "text"
TARGET_COLUMN_NAME = "airline_sentiment"

TARGET_STR_INT = {'negative': 0, 'neutral': 1, 'positive': 2}
TARGET_INT_STR = {0: 'negative', 1: 'neutral', 2: 'positive'}

# Paths.
MODEL_NAME = "Souvikcmsa/SentimentAnalysisDistillBERT"
DATA_URL = 'https://raw.githubusercontent.com/Giskard-AI/examples/main/datasets/twitter_us_airline_sentiment_analysis.csv'

Dataset preparation

Load and preprocess data

[3]:
def load_preprocess_data():
    """Load data and encode targets."""
    df = pd.read_csv(DATA_URL, usecols=[TEXT_COLUMN_NAME, TARGET_COLUMN_NAME])
    df[TARGET_COLUMN_NAME] = df[TARGET_COLUMN_NAME].map(TARGET_STR_INT)
    return df


data = load_preprocess_data()

Train-test split

[4]:
X_train, X_test, y_train, y_test = train_test_split(data[[TEXT_COLUMN_NAME]], data[TARGET_COLUMN_NAME],
                                                    random_state=RANDOM_SEED)

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.map(TARGET_INT_STR)], 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_COLUMN_NAME,  # Ground truth variable.
    name="Tweets sentiment dataset"  # Optional.
)

Model building

Define ‘torch.Dataset’ objects.

[6]:
class CustomDataset(TorchDataset):
    def __init__(self, encodings, labels=None):
        self.encodings = encodings
        self.labels = labels

    def __getitem__(self, idx):
        item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}

        if self.labels:
            item["labels"] = torch.tensor(self.labels[idx])

        return item

    def __len__(self):
        return len(self.encodings["input_ids"])


# Define tokenizer.
tokenizer = DistilBertTokenizer.from_pretrained(MODEL_NAME)

X_train_tokenized = tokenizer(list(X_train.text), padding=True, truncation=True, max_length=256)
X_test_tokenized = tokenizer(list(X_test.text), padding=True, truncation=True, max_length=256)

train_dataset = CustomDataset(X_train_tokenized, y_train.values.tolist())
val_dataset = CustomDataset(X_test_tokenized, y_test.values.tolist())

Define model

[7]:
model = DistilBertForSequenceClassification.from_pretrained(MODEL_NAME).train()

# Freeze 'DistillBert' feature extraction module.
for param in model.base_model.parameters():
    param.requires_grad = False

Define trainer object

[ ]:
def compute_metrics(eval_pred):
    probs, y_true = eval_pred
    y_pred = np.argmax(probs, axis=1)

    f1 = f1_score(y_true, y_pred, average='macro')
    return {"f1": f1}


training_args = TrainingArguments(
    output_dir='output',
    learning_rate=2e-5,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=16,
    num_train_epochs=1,
    optim="adamw_torch",
    weight_decay=0.01,
    save_strategy="no",
    disable_tqdm=True,
    no_cuda=True
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
    eval_dataset=val_dataset,
    compute_metrics=compute_metrics
)

trainer.remove_callback(WandbCallback)
trainer.remove_callback(MLflowCallback)
trainer.remove_callback(TensorBoardCallback)

Train and evaluate model

[ ]:
trainer.train()
trainer.evaluate()

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.

[ ]:
def prediction_function(df) -> np.ndarray:
    input_text = list(df[TEXT_COLUMN_NAME])
    text_tokenized = tokenizer(input_text, padding=True, truncation=True, max_length=256)

    # Make prediction.
    raw_pred = model.forward(input_ids=torch.tensor(text_tokenized["input_ids"]),
                             attention_mask=torch.tensor(text_tokenized["attention_mask"]))
    predictions = torch.nn.functional.softmax(raw_pred["logits"], dim=-1)
    predictions = predictions.cpu().detach().numpy()

    return predictions


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="Twitter sentiment classifier",  # Optional
    classification_labels=TARGET_INT_STR.values(),  # Their order MUST be identical to the prediction_function's
    feature_names=[TEXT_COLUMN_NAME]  # Default: all columns of your dataset
)

# Validate wrapped model.
print(
    f"Wrapped Test F1-Score: {f1_score(y_test, giskard_model.predict(giskard_dataset).raw_prediction, average='macro')}")

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

[14]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
2024-05-29 13:27:10,197 pid:61763 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 13:27:10,199 pid:61763 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (375, 2) executed in 0:00:00.007260
2024-05-29 13:27:10,212 pid:61763 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 13:27:10,214 pid:61763 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (375, 2) executed in 0:00:00.005033
2024-05-29 13:27:10,219 pid:61763 MainThread giskard.utils.logging_utils INFO     Perturb and predict data executed in 0:00:00.033015
2024-05-29 13:27:10,220 pid:61763 MainThread giskard.utils.logging_utils INFO     Compare and predict the data executed in 0:00:00.000322
Executed 'Invariance to “Switch Gender”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x327e98160>, 'dataset': <giskard.datasets.base.Dataset object at 0x327ca2a10>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextGenderTransformation object at 0x35ceecc70>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
               Test failed
               Metric: 0.95
                - [INFO] 20 rows were perturbed

2024-05-29 13:27:10,228 pid:61763 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 13:27:10,229 pid:61763 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (375, 2) executed in 0:00:00.004654
2024-05-29 13:27:10,248 pid:61763 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 13:27:13,896 pid:61763 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (375, 2) executed in 0:00:03.650915
2024-05-29 13:27:13,899 pid:61763 MainThread giskard.utils.logging_utils INFO     Perturb and predict data executed in 0:00:03.676607
2024-05-29 13:27:13,900 pid:61763 MainThread giskard.utils.logging_utils INFO     Compare and predict the data executed in 0:00:00.000276
Executed 'Invariance to “Add typos”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x327e98160>, 'dataset': <giskard.datasets.base.Dataset object at 0x327ca2a10>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextTypoTransformation object at 0x327ca32e0>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
               Test failed
               Metric: 0.85
                - [INFO] 355 rows were perturbed

2024-05-29 13:27:13,909 pid:61763 MainThread giskard.datasets.base INFO     Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 13:27:13,910 pid:61763 MainThread giskard.utils.logging_utils INFO     Predicted dataset with shape (87, 2) executed in 0:00:00.006215
Executed 'Overconfidence on data slice “`text_length(text)` < 65.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x327e98160>, 'dataset': <giskard.datasets.base.Dataset object at 0x327ca2a10>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x38fba8190>, 'threshold': 0.6886956521739132, 'p_threshold': 0.43497172683775553}:
               Test failed
               Metric: 0.74


2024-05-29 13:27:13,913 pid:61763 MainThread giskard.core.suite INFO     Executed test suite 'My first test suite'
2024-05-29 13:27:13,913 pid:61763 MainThread giskard.core.suite INFO     result: failed
2024-05-29 13:27:13,914 pid:61763 MainThread giskard.core.suite INFO     Invariance to “Switch Gender” ({'model': <giskard.models.function.PredictionFunctionModel object at 0x327e98160>, 'dataset': <giskard.datasets.base.Dataset object at 0x327ca2a10>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextGenderTransformation object at 0x35ceecc70>, 'threshold': 0.95, 'output_sensitivity': 0.05}): {failed, metric=0.95}
2024-05-29 13:27:13,914 pid:61763 MainThread giskard.core.suite INFO     Invariance to “Add typos” ({'model': <giskard.models.function.PredictionFunctionModel object at 0x327e98160>, 'dataset': <giskard.datasets.base.Dataset object at 0x327ca2a10>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextTypoTransformation object at 0x327ca32e0>, 'threshold': 0.95, 'output_sensitivity': 0.05}): {failed, metric=0.8450704225352113}
2024-05-29 13:27:13,914 pid:61763 MainThread giskard.core.suite INFO     Overconfidence on data slice “`text_length(text)` < 65.500” ({'model': <giskard.models.function.PredictionFunctionModel object at 0x327e98160>, 'dataset': <giskard.datasets.base.Dataset object at 0x327ca2a10>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x38fba8190>, 'threshold': 0.6886956521739132, 'p_threshold': 0.43497172683775553}): {failed, metric=0.7419354838709677}
[14]:
close Test suite failed.
Test Invariance to “Switch Gender”
Measured Metric = 0.95 close Failed
model Twitter sentiment classifier
dataset Tweets sentiment dataset
transformation_function Switch Gender
threshold 0.95
output_sensitivity 0.05
Test Invariance to “Add typos”
Measured Metric = 0.84507 close Failed
model Twitter sentiment classifier
dataset Tweets sentiment dataset
transformation_function Add typos
threshold 0.95
output_sensitivity 0.05
Test Overconfidence on data slice “`text_length(text)` < 65.500”
Measured Metric = 0.74194 close Failed
model Twitter sentiment classifier
dataset Tweets sentiment dataset
slicing_function `text_length(text)` < 65.500
threshold 0.6886956521739132
p_threshold 0.43497172683775553

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