Open In Colab View Notebook on GitHub

ENRON email classification [scikit-learn]ΒΆ

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 email’s category.

  • Model: LogisticRegression

  • 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

[ ]:
!pip install giskard --upgrade

Import librariesΒΆ

[24]:
import glob
import email
from string import punctuation
from collections import defaultdict

import nltk
import pandas as pd
from dateutil import parser
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from sklearn import model_selection
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer

from giskard import Dataset, Model, scan, testing, Suite, GiskardClient

Define constantsΒΆ

[34]:
TEXT_COLUMN = "Content"
TARGET_COLUMN = "Target"

COLUMN_TYPES = {TEXT_COLUMN: "text"}
COLUMNS_NAMES = ['Target', 'Subject', 'Content', 'Week_day', 'Year', 'Month', 'Hour', 'Nb_of_forwarded_msg']

RANDOM_STATE = 0

IDX_TO_CAT = {
    1: 'REGULATION',
    2: 'INTERNAL',
    3: 'INFLUENCE',
    4: 'INFLUENCE',
    5: 'INFLUENCE',
    6: 'CALIFORNIA CRISIS',
    7: 'INTERNAL',
    8: 'INTERNAL',
    9: 'INFLUENCE',
    10: 'REGULATION',
    11: 'talking points',
    12: 'meeting minutes',
    13: 'trip reports'}

LABEL_CAT = 3

Dataset preparationΒΆ

Load and preprocess dataΒΆ

[ ]:
!wget https://bailando.berkeley.edu/enron/enron_with_categories.tar.gz
!tar zxf enron_with_categories.tar.gz
!rm enron_with_categories.tar.gz
[ ]:
nltk.download('punkt')
nltk.download('stopwords')

stoplist = list(set(stopwords.words('english') + list(punctuation)))
stemmer = PorterStemmer()


def get_labels(filename):
    with open(filename + '.cats') as f:
        labels = defaultdict(dict)
        line = f.readline()

        while line:
            line = line.split(',')
            top_cat, sub_cat, freq = int(line[0]), int(line[1]), int(line[2])
            labels[top_cat][sub_cat] = freq
            line = f.readline()

    return dict(labels)


data = pd.DataFrame(columns=COLUMNS_NAMES)

email_files = [f.replace('.cats', '') for f in glob.glob('enron_with_categories/*/*.cats')]
for email_file in email_files:
    values_to_add = {}

    #Target is the sub-category with maximum frequency
    if LABEL_CAT in get_labels(email_file):
        sub_cat_dict = get_labels(email_file)[LABEL_CAT]
        target_int = max(sub_cat_dict, key=sub_cat_dict.get)
        values_to_add[TARGET_COLUMN] = str(IDX_TO_CAT[target_int])

    #Features are metadata from the email object
    filename = email_file + '.txt'
    with open(filename) as f:

        message = email.message_from_string(f.read())

        values_to_add['Subject'] = str(message['Subject'])
        values_to_add[TEXT_COLUMN] = str(message.get_payload())

        date_time_obj = parser.parse(message['Date'])
        values_to_add['Week_day'] = date_time_obj.strftime("%A")
        values_to_add['Year'] = date_time_obj.strftime("%Y")
        values_to_add['Month'] = date_time_obj.strftime("%B")
        values_to_add['Hour'] = int(date_time_obj.strftime("%H"))

        # Count number of forwarded mails
        number_of_messages = 0
        for line in message.get_payload().split('\n'):
            if ('forwarded' in line.lower() or 'original' in line.lower()) and '--' in line:
                number_of_messages += 1
        values_to_add['Nb_of_forwarded_msg'] = number_of_messages

    row_to_add = pd.Series(values_to_add)
    data = pd.concat([data, pd.DataFrame([row_to_add])], ignore_index=True)


data_filtered = data[data[TARGET_COLUMN].notnull()]

# Exclude target category with very few rows.
excluded_category = [IDX_TO_CAT[i] for i in [11, 12, 13]]
data_filtered = data_filtered[data_filtered["Target"].isin(excluded_category) == False]
num_classes = len(data_filtered[TARGET_COLUMN].value_counts())

# Keep only the email column and the target
data_filtered = data_filtered[[TEXT_COLUMN, TARGET_COLUMN]]

Train-test splitΒΆ

[37]:
Y = data_filtered[TARGET_COLUMN]
X = data_filtered.drop(columns=[TARGET_COLUMN])[list(COLUMN_TYPES.keys())]
X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, random_state=RANDOM_STATE, stratify=Y)

Wrap dataset with GiskardΒΆ

To prepare for the vulnerability scan, make sure to wrap your dataset using Giskard’s Dataset class. More details here.

[38]:
raw_data = pd.concat([X_test, Y_test], 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",  # Ground truth variable.
    name="Emails of different categories"  # Optional.
)

Model buildingΒΆ

Build estimatorΒΆ

[ ]:
text_transformer = Pipeline([
    ('vect', CountVectorizer(stop_words=stoplist)),
    ('tfidf', TfidfTransformer())
])

preprocessor = ColumnTransformer(
    transformers=[
        ('text_Mail', text_transformer, "Content")
    ]
)

clf = Pipeline(steps=[('preprocessor', preprocessor),
                      ('classifier', LogisticRegression())])
clf.fit(X_train, Y_train)

print(f"Train Accuracy score: {clf.score(X_train, Y_train):.2f}")
print(f"Test Accuracy score: {clf.score(X_test, Y_test):.2f}")

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.

[ ]:
giskard_model = Model(
    model=clf,  # 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="Email category classifier",  # Optional.
    classification_labels=clf.classes_.tolist(),  # Their order MUST be identical to the prediction_function's output order.
    feature_names=COLUMN_TYPES.keys(),  # Default: all columns of your dataset.
)

# Validate wrapped model.
y_test_pred_wrapped = giskard_model.predict(giskard_dataset).prediction
wrapped_test_metric = accuracy_score(Y_test, y_test_pred_wrapped)

print(f"Wrapped Test Accuracy score: {wrapped_test_metric:.2f}")

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

[45]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
Executed 'Invariance to β€œAdd typos”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextTypoTransformation object at 0x1324c6ec0>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
               Test failed
               Metric: 0.95
                - [TestMessageLevel.INFO] 213 rows were perturbed

Executed 'Precision on data slice β€œ`Content` contains "gives"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c5ba710>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.29


Executed 'Precision on data slice β€œ`Content` contains "delay"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c932470>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.3


Executed 'Precision on data slice β€œ`Content` contains "sacramento"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c8855d0>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.3


Executed 'Precision on data slice β€œ`Content` contains "dasovich"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c884f70>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.3


Executed 'Precision on data slice β€œ`Content` contains "pro"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c9b71f0>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.33


Executed 'Precision on data slice β€œ`Content` contains "jeff"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c525990>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.34


Executed 'Precision on data slice β€œ`Content` contains "alan"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x13245eb00>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.36


Executed 'Precision on data slice β€œ`Content` contains "judge"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c5be290>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.38


Executed 'Precision on data slice β€œ`Content` contains "blackouts"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c4eee90>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.38


Executed 'Precision on data slice β€œ`Content` contains "emergency"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c78d870>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.39


Executed 'Precision on data slice β€œ`Content` contains "push"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c56b3d0>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.39


Executed 'Precision on data slice β€œ`Content` contains "fair"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c885cf0>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.4


Executed 'Precision on data slice β€œ`Content` contains "duke"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c79b010>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.4


Executed 'Precision on data slice β€œ`Content` contains "governor"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c553670>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.4


Executed 'Precision on data slice β€œ`Content` contains "friday"”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x148558f10>, 'dataset': <giskard.datasets.base.Dataset object at 0x14853b8b0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14c78f130>, 'threshold': 0.544131455399061}:
               Test failed
               Metric: 0.4


[45]:
close Test suite failed. To debug your failing test and diagnose the issue, please run the Giskard hub (see documentation)
Test Invariance to β€œAdd typos”
Measured Metric = 0.94836 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
transformation_function Add typos
threshold 0.95
output_sensitivity 0.05
Test Precision on data slice β€œ`Content` contains "gives"”
Measured Metric = 0.28571 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "gives"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "delay"”
Measured Metric = 0.3 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "delay"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "sacramento"”
Measured Metric = 0.30435 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "sacramento"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "dasovich"”
Measured Metric = 0.30435 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "dasovich"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "pro"”
Measured Metric = 0.33333 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "pro"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "jeff"”
Measured Metric = 0.33962 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "jeff"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "alan"”
Measured Metric = 0.35714 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "alan"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "judge"”
Measured Metric = 0.38095 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "judge"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "blackouts"”
Measured Metric = 0.38095 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "blackouts"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "emergency"”
Measured Metric = 0.3913 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "emergency"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "push"”
Measured Metric = 0.3913 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "push"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "fair"”
Measured Metric = 0.4 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "fair"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "duke"”
Measured Metric = 0.4 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "duke"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "governor"”
Measured Metric = 0.4 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "governor"
threshold 0.544131455399061
Test Precision on data slice β€œ`Content` contains "friday"”
Measured Metric = 0.40476 close Failed
model 3ef6293a-8420-40ee-bb44-57602b025a6f
dataset Email classifier
slicing_function `Content` contains "friday"
threshold 0.544131455399061

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