Twitter sentiment analysis using RoBERTa model [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 numpy as np
import pandas as pd
from scipy.special import softmax
from datasets import load_dataset
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from giskard import Dataset, Model, scan, testing
Define constants¶
[2]:
MODEL_NAME = "cardiffnlp/twitter-roberta-base-sentiment"
DATASET_CONFIG = {
"path": "tweet_eval",
"name": "sentiment",
"split": "validation"
}
LABEL_MAPPING = {
0: "negative",
1: "neutral",
2: "positive"
}
TEXT_COLUMN = "text"
TARGET_COLUMN = "label"
Dataset preparation¶
Load and preprocess data¶
[ ]:
raw_data = load_dataset(**DATASET_CONFIG).to_pandas().iloc[:500]
raw_data = raw_data.replace({"label": LABEL_MAPPING})
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=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, # Ground truth variable.
name="Tweets with sentiment" # Optional.
)
Model building¶
Load model¶
[ ]:
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
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: pd.DataFrame) -> np.ndarray:
encoded_input = tokenizer(list(df[TEXT_COLUMN]), padding=True, return_tensors='pt')
output = model(**encoded_input)
return softmax(output['logits'].detach().numpy(), axis=1)
giskard_model = Model(
model=prediction_function, # A prediction function that encapsulates all the data pre-processing steps and that
model_type="classification", # Either regression, classification or text_generation.
name="RoBERTa for sentiment classification", # Optional
classification_labels=list(LABEL_MAPPING.values()), # Their order MUST be identical to the prediction_function's
feature_names=[TEXT_COLUMN] # 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)
[8]:
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.
[9]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
2024-05-29 14:11:45,190 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:11:45,191 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:00.004644
2024-05-29 14:11:45,251 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:11:45,399 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:00.150955
2024-05-29 14:11:45,402 pid:71825 MainThread giskard.utils.logging_utils INFO Perturb and predict data executed in 0:00:00.222624
2024-05-29 14:11:45,403 pid:71825 MainThread giskard.utils.logging_utils INFO Compare and predict the data executed in 0:00:00.000257
Executed 'Invariance to “Switch Religion”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextReligionTransformation object at 0x1678c04c0>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
Test failed
Metric: 0.72
- [INFO] 18 rows were perturbed
2024-05-29 14:11:45,410 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:11:45,411 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:00.003503
2024-05-29 14:11:46,450 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:11:47,054 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:00.606827
2024-05-29 14:11:47,057 pid:71825 MainThread giskard.utils.logging_utils INFO Perturb and predict data executed in 0:00:01.650993
2024-05-29 14:11:47,058 pid:71825 MainThread giskard.utils.logging_utils INFO Compare and predict the data executed in 0:00:00.000368
Executed 'Invariance to “Switch countries from high- to low-income and vice versa”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextNationalityTransformation object at 0x16cce32b0>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
Test failed
Metric: 0.89
- [INFO] 37 rows were perturbed
2024-05-29 14:11:47,067 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:11:47,068 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:00.004624
2024-05-29 14:11:47,073 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:11:47,074 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:00.004301
2024-05-29 14:11:47,077 pid:71825 MainThread giskard.utils.logging_utils INFO Perturb and predict data executed in 0:00:00.014895
2024-05-29 14:11:47,078 pid:71825 MainThread giskard.utils.logging_utils INFO Compare and predict the data executed in 0:00:00.000366
Executed 'Invariance to “Transform to uppercase”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextUppercase object at 0x16e8a24a0>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
Test failed
Metric: 0.8
- [INFO] 500 rows were perturbed
2024-05-29 14:11:47,087 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:11:47,088 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:00.004196
2024-05-29 14:11:47,118 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:12:04,625 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:17.511923
2024-05-29 14:12:04,670 pid:71825 MainThread giskard.utils.logging_utils INFO Perturb and predict data executed in 0:00:17.589033
2024-05-29 14:12:04,674 pid:71825 MainThread giskard.utils.logging_utils INFO Compare and predict the data executed in 0:00:00.002457
Executed 'Invariance to “Add typos”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextTypoTransformation object at 0x16e8a3730>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
Test failed
Metric: 0.85
- [INFO] 481 rows were perturbed
2024-05-29 14:12:04,794 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:12:04,799 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:00.059188
2024-05-29 14:12:04,809 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:12:04,812 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:00.008343
2024-05-29 14:12:04,814 pid:71825 MainThread giskard.utils.logging_utils INFO Perturb and predict data executed in 0:00:00.097106
2024-05-29 14:12:04,815 pid:71825 MainThread giskard.utils.logging_utils INFO Compare and predict the data executed in 0:00:00.000374
Executed 'Invariance to “Transform to title case”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextTitleCase object at 0x16e8a7730>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
Test failed
Metric: 0.9
- [INFO] 500 rows were perturbed
2024-05-29 14:12:04,824 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:12:04,825 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:00.005466
2024-05-29 14:12:04,846 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:12:04,856 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:00.014955
2024-05-29 14:12:04,858 pid:71825 MainThread giskard.utils.logging_utils INFO Perturb and predict data executed in 0:00:00.040138
2024-05-29 14:12:04,859 pid:71825 MainThread giskard.utils.logging_utils INFO Compare and predict the data executed in 0:00:00.000400
Executed 'Invariance to “Punctuation Removal”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextPunctuationRemovalTransformation object at 0x16e8a1000>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
Test failed
Metric: 0.91
- [INFO] 463 rows were perturbed
2024-05-29 14:12:04,874 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:12:04,876 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:00.005411
2024-05-29 14:12:04,881 pid:71825 MainThread giskard.datasets.base INFO Casting dataframe columns from {'text': 'object'} to {'text': 'object'}
2024-05-29 14:12:04,884 pid:71825 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (500, 2) executed in 0:00:00.006467
2024-05-29 14:12:04,887 pid:71825 MainThread giskard.utils.logging_utils INFO Perturb and predict data executed in 0:00:00.024632
2024-05-29 14:12:04,888 pid:71825 MainThread giskard.utils.logging_utils INFO Compare and predict the data executed in 0:00:00.000371
Executed 'Invariance to “Transform to lowercase”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextLowercase object at 0x16e8a7970>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
Test failed
Metric: 0.92
- [INFO] 492 rows were perturbed
2024-05-29 14:12:04,890 pid:71825 MainThread giskard.core.suite INFO Executed test suite 'My first test suite'
2024-05-29 14:12:04,890 pid:71825 MainThread giskard.core.suite INFO result: failed
2024-05-29 14:12:04,892 pid:71825 MainThread giskard.core.suite INFO Invariance to “Switch Religion” ({'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextReligionTransformation object at 0x1678c04c0>, 'threshold': 0.95, 'output_sensitivity': 0.05}): {failed, metric=0.7222222222222222}
2024-05-29 14:12:04,892 pid:71825 MainThread giskard.core.suite INFO Invariance to “Switch countries from high- to low-income and vice versa” ({'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextNationalityTransformation object at 0x16cce32b0>, 'threshold': 0.95, 'output_sensitivity': 0.05}): {failed, metric=0.8918918918918919}
2024-05-29 14:12:04,893 pid:71825 MainThread giskard.core.suite INFO Invariance to “Transform to uppercase” ({'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextUppercase object at 0x16e8a24a0>, 'threshold': 0.95, 'output_sensitivity': 0.05}): {failed, metric=0.802}
2024-05-29 14:12:04,893 pid:71825 MainThread giskard.core.suite INFO Invariance to “Add typos” ({'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextTypoTransformation object at 0x16e8a3730>, 'threshold': 0.95, 'output_sensitivity': 0.05}): {failed, metric=0.8503118503118503}
2024-05-29 14:12:04,893 pid:71825 MainThread giskard.core.suite INFO Invariance to “Transform to title case” ({'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextTitleCase object at 0x16e8a7730>, 'threshold': 0.95, 'output_sensitivity': 0.05}): {failed, metric=0.898}
2024-05-29 14:12:04,894 pid:71825 MainThread giskard.core.suite INFO Invariance to “Punctuation Removal” ({'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextPunctuationRemovalTransformation object at 0x16e8a1000>, 'threshold': 0.95, 'output_sensitivity': 0.05}): {failed, metric=0.9071274298056156}
2024-05-29 14:12:04,894 pid:71825 MainThread giskard.core.suite INFO Invariance to “Transform to lowercase” ({'model': <giskard.models.function.PredictionFunctionModel object at 0x167e40370>, 'dataset': <giskard.datasets.base.Dataset object at 0x167e409d0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextLowercase object at 0x16e8a7970>, 'threshold': 0.95, 'output_sensitivity': 0.05}): {failed, metric=0.9247967479674797}
[9]:
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()