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

  • 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

[1]:
%pip install giskard --upgrade

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

[ ]:
%pip install accelerate --upgrade

Import libraries

[ ]:
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, GiskardClient, Suite

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

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

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

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

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

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

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()
Executed 'Invariance to “Switch Gender”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x15acc19c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15ad7e440>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextGenderTransformation object at 0x15acb5f90>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
               Test failed
               Metric: 0.95
                - [TestMessageLevel.INFO] 20 rows were perturbed

Executed 'Invariance to “Add typos”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x15acc19c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15ad7e440>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextTypoTransformation object at 0x15acc37f0>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
               Test failed
               Metric: 0.87
                - [TestMessageLevel.INFO] 352 rows were perturbed

Executed 'Overconfidence on data slice “`avg_whitespace(text)` < 0.149”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x15acc19c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15ad7e440>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x15ac7b1f0>, 'threshold': 0.7140350877192984, 'p_threshold': 0.43497172683775553}:
               Test failed
               Metric: 0.76


[14]:
close Test suite failed. To debug your failing test and diagnose the issue, please run the Giskard hub (see documentation)
Test Invariance to “Switch Gender”
Measured Metric = 0.95 close Failed
model e22c8893-a3d6-4ecd-8341-7cab2b8c311d
dataset Tweets sentiment dataset
transformation_function Switch Gender
threshold 0.95
output_sensitivity 0.05
Test Invariance to “Add typos”
Measured Metric = 0.87216 close Failed
model e22c8893-a3d6-4ecd-8341-7cab2b8c311d
dataset Tweets sentiment dataset
transformation_function Add typos
threshold 0.95
output_sensitivity 0.05
Test Overconfidence on data slice “`avg_whitespace(text)` < 0.149”
Measured Metric = 0.7561 close Failed
model e22c8893-a3d6-4ecd-8341-7cab2b8c311d
dataset Tweets sentiment dataset
slicing_function `avg_whitespace(text)` < 0.149
threshold 0.7140350877192984
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()

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.

CleanShot 2023-09-26 at 18.38.09.png

CleanShot 2023-09-26 at 18.38.50.png

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