Open In Colab View Notebook on GitHub

Fake/real news classification [tensorflow (keras)]#

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

[21]:
%pip install giskard --upgrade

Import libraries#

[ ]:
import os
import string
from pathlib import Path
from urllib.request import urlretrieve

import numpy as np
import pandas as pd
from keras.layers import Dense, Embedding, LSTM
from keras.models import Sequential
from keras.optimizers import Adam
from keras.preprocessing.text import Tokenizer
from keras.utils import pad_sequences
from nltk.corpus import stopwords
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from typing import Tuple, Callable

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

Notebook-level settings#

[2]:
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'

Define constants#

[3]:
# Constants.
MAX_TOKENS = 20000
MAX_SEQUENCE_LENGTH = 100
N_ROWS = 1000

STOPWORDS = stopwords.words('english')

TEXT_COLUMN_NAME = "text"
TARGET_COLUMN_NAME = "isFake"

RANDOM_SEED = 0

# Paths.
DATA_URL = "ftp://sys.giskard.ai/pub/unit_test_resources/fake_real_news_dataset/{}"
DATA_PATH = Path.home() / ".giskard" / "fake_real_news_dataset"

Dataset preparation#

Load and preprocess data#

[ ]:
def fetch_from_ftp(url: str, file: Path) -> None:
    """Helper to fetch data from the FTP server."""
    if not file.parent.exists():
        file.parent.mkdir(parents=True, exist_ok=True)

    if not file.exists():
        print(f"Downloading data from {url}")
        urlretrieve(url, file)

    print(f"Data was loaded!")


def fetch_dataset() -> None:
    """Gradually fetch all necessary files from the FTP server."""
    files_to_fetch = ("Fake.csv", "True.csv", "glove_100d.txt")
    for file_name in files_to_fetch:
        fetch_from_ftp(DATA_URL.format(file_name), DATA_PATH / file_name)


def load_data(**kwargs) -> pd.DataFrame:
    """Load data."""
    real_df = pd.read_csv(DATA_PATH / "True.csv", **kwargs)
    fake_df = pd.read_csv(DATA_PATH / "Fake.csv", **kwargs)

    # Create target column.
    real_df[TARGET_COLUMN_NAME] = 0
    fake_df[TARGET_COLUMN_NAME] = 1

    # Combine dfs.
    full_df = pd.concat([real_df, fake_df])
    full_df.drop(columns=["subject", "date"], inplace=True)
    return full_df


fetch_dataset()
news_df = load_data(nrows=N_ROWS)

Train-test split#

[5]:
X_train, X_test, Y_train, Y_test = train_test_split(news_df[["title", TEXT_COLUMN_NAME]], news_df[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], 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="fake_and_real_news"  # Optional.
)

Model building#

Define preprocessing steps#

[7]:
def prepare_text(df: pd.DataFrame) -> np.ndarray:
    """Perform text-data cleaning: punctuation and stop words removal."""
    # Merge text data into single column.
    df[TEXT_COLUMN_NAME] = df[TEXT_COLUMN_NAME] + " " + df.title
    df.drop(columns=["title"], inplace=True)

    # Remove punctuation.
    df[TEXT_COLUMN_NAME] = df[TEXT_COLUMN_NAME].apply(
        lambda text: text.translate(str.maketrans('', '', string.punctuation)))

    # Remove stop words.
    df[TEXT_COLUMN_NAME] = df[TEXT_COLUMN_NAME].apply(
        lambda sentence: ' '.join([_word for _word in sentence.split() if _word.lower() not in STOPWORDS]))

    return df[TEXT_COLUMN_NAME]


X_train_prepared = prepare_text(X_train)
X_test_prepared = prepare_text(X_test)


def init_tokenizer() -> Tuple[Callable, Tokenizer]:
    """Initialize tokenization function with the Tokenizer in it's outer-scope."""
    tokenizer = Tokenizer(num_words=MAX_TOKENS)
    tokenizer.fit_on_texts(X_train_prepared)

    def tokenization_closure(df: pd.DataFrame) -> pd.DataFrame:
        tokenized = tokenizer.texts_to_sequences(df)
        return pad_sequences(tokenized, maxlen=MAX_SEQUENCE_LENGTH)

    return tokenization_closure, tokenizer


tokenize, text_tokenizer = init_tokenizer()
X_train_tokens = tokenize(X_train_prepared)
X_test_tokens = tokenize(X_test_prepared)

Create embeddings matrix#

[8]:
def parse_line(word: str, *arr: list) -> Tuple[str, np.ndarray]:
    """Parse line from the file with embeddings.
    The first value of the line is the word and the rest values are related glove embedding: (<word>, 0.66, 0.23, ...)."""
    return word, np.asarray(arr, dtype='float32')


def init_embeddings_matrix(embeddings_dict: dict) -> np.ndarray:
    """Init a matrix, where each row is an embedding vector."""
    num_embeddings = min(MAX_TOKENS, len(text_tokenizer.word_index))
    stacked_embeddings = np.stack(list(embeddings_dict.values()))
    embeddings_mean, embeddings_std, embeddings_dimension = stacked_embeddings.mean(), stacked_embeddings.std(), \
    stacked_embeddings.shape[1]
    embeddings_matrix = np.random.normal(embeddings_mean, embeddings_std, (num_embeddings, embeddings_dimension))
    return embeddings_matrix


def get_embeddings_matrix() -> np.ndarray:
    """Create matrix, where each row is an embedding of a specific word."""
    # Load glove embeddings.
    embeddings_dict = dict(parse_line(*line.rstrip().rsplit(' ')) for line in open(DATA_PATH / "glove_100d.txt"))

    # Create embeddings matrix with glove word vectors.
    embeddings_matrix = init_embeddings_matrix(embeddings_dict)
    for word, idx in text_tokenizer.word_index.items():
        if idx >= MAX_TOKENS:
            continue

        embedding_vector = embeddings_dict.get(word, None)

        if embedding_vector is not None:
            embeddings_matrix[idx] = embedding_vector

    return embeddings_matrix


embed_matrix = get_embeddings_matrix()

Build estimator#

[ ]:
def init_model() -> Sequential:
    """Initialize new TF model."""
    # Define model container.
    model = Sequential()

    # Non-trainable embedding layer.
    model.add(Embedding(MAX_TOKENS, output_dim=100, weights=[embed_matrix], input_length=MAX_SEQUENCE_LENGTH,
                        trainable=False))

    # LSTM stage.
    model.add(LSTM(units=32, return_sequences=True, recurrent_dropout=0.25, dropout=0.25))
    model.add(LSTM(units=16, recurrent_dropout=0.1, dropout=0.1))

    # Dense stage.
    model.add(Dense(units=16, activation='relu'))
    model.add(Dense(units=1, activation='sigmoid'))

    # Build model.
    model.compile(optimizer=Adam(learning_rate=0.01), loss='binary_crossentropy', metrics=['accuracy'])
    return model


# Fit model.
n_epochs = 5
batch_size = 256

classifier = init_model()
_ = classifier.fit(X_train_tokens, Y_train, batch_size=batch_size, validation_data=(X_test_tokens, Y_test),
                   epochs=n_epochs)

train_metric = classifier.evaluate(X_train_tokens, Y_train, verbose=0)[1]
test_metric = classifier.evaluate(X_test_tokens, Y_test, verbose=0)[1]

print(f"Train accuracy: {train_metric: .4f}")
print(f"Test accuracy: {test_metric: .4f}")

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:
    """Define a prediction function for giskard.Model."""
    tokens = tokenize(prepare_text(df))
    return classifier.predict(tokens, verbose=0)


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="fake_real_news_classification",  # Optional.
    feature_names=["title", TEXT_COLUMN_NAME],  # Default: all columns of your dataset.
    classification_labels=[0, 1],  # Their order MUST be identical to the prediction_function's output order.
    # classification_threshold=0.5  # Default: 0.5
)

# Validate wrapped model.
Y_test_pred_wrapper = giskard_model.predict(giskard_dataset).prediction
wrapped_test_metric = accuracy_score(Y_test, Y_test_pred_wrapper)
print(f"Wrapped test accuracy: {wrapped_test_metric: .4f}")

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

[13]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
Executed 'Recall on data slice “`text` contains "october"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1426c2770>, 'threshold': 0.9306910569105691}:
               Test failed
               Metric: 0.87


Executed 'Accuracy on data slice “`avg_whitespace(title)` >= 0.147 AND `avg_whitespace(title)` < 0.152”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x13e0318a0>, 'threshold': 0.9386}:
               Test failed
               Metric: 0.91


Executed 'Recall on data slice “`text_length(title)` >= 92.500 AND `text_length(title)` < 97.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x13dfb8d90>, 'threshold': 0.9306910569105691}:
               Test failed
               Metric: 0.9


Executed 'Recall on data slice “`text` contains "decision"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x142206ef0>, 'threshold': 0.9306910569105691}:
               Test failed
               Metric: 0.91


Executed 'Recall on data slice “`text` contains "texas"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141eadff0>, 'threshold': 0.9306910569105691}:
               Test failed
               Metric: 0.91


Executed 'Recall on data slice “`text` contains "life"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x14245ee90>, 'threshold': 0.9306910569105691}:
               Test failed
               Metric: 0.92


Executed 'Accuracy on data slice “`text` contains "guilty"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1426cab90>, 'threshold': 0.9386}:
               Test failed
               Metric: 0.93


Executed 'Recall on data slice “`text` contains "september"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1426553f0>, 'threshold': 0.9306910569105691}:
               Test failed
               Metric: 0.92


Executed 'Accuracy on data slice “`avg_word_length(text)` < 4.884 AND `avg_word_length(text)` >= 4.835”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x13e1099f0>, 'threshold': 0.9386}:
               Test failed
               Metric: 0.93


Executed 'Accuracy on data slice “`avg_digits(text)` >= 0.007 AND `avg_digits(text)` < 0.008”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x13e1082b0>, 'threshold': 0.9386}:
               Test failed
               Metric: 0.93


Executed 'Accuracy on data slice “`text_length(text)` >= 2446.500 AND `text_length(text)` < 2572.500”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x13e108a90>, 'threshold': 0.9386}:
               Test failed
               Metric: 0.93


Executed 'Accuracy on data slice “`title` contains "video"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x141fbeb90>, 'threshold': 0.9386}:
               Test failed
               Metric: 0.94


Executed 'Recall on data slice “`avg_digits(text)` >= 0.003 AND `avg_digits(text)` < 0.004”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x13e10ad10>, 'threshold': 0.9306910569105691}:
               Test failed
               Metric: 0.93


Executed 'Accuracy on data slice “`text` contains "elections"”' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x13a691b40>, 'dataset': <giskard.datasets.base.Dataset object at 0x10ca8e170>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1421a2ad0>, 'threshold': 0.9386}:
               Test failed
               Metric: 0.94


[13]:
close Test suite failed. To debug your failing test and diagnose the issue, please run the Giskard hub (see documentation)
Test Recall on data slice “`text` contains "october"”
Measured Metric = 0.86957 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `text` contains "october"
threshold 0.9306910569105691
Test Accuracy on data slice “`avg_whitespace(title)` >= 0.147 AND `avg_whitespace(title)` < 0.152”
Measured Metric = 0.90625 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `avg_whitespace(title)` >= 0.147 AND `avg_whitespace(title)` < 0.152
threshold 0.9386
Test Recall on data slice “`text_length(title)` >= 92.500 AND `text_length(title)` < 97.500”
Measured Metric = 0.9 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `text_length(title)` >= 92.500 AND `text_length(title)` < 97.500
threshold 0.9306910569105691
Test Recall on data slice “`text` contains "decision"”
Measured Metric = 0.90909 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `text` contains "decision"
threshold 0.9306910569105691
Test Recall on data slice “`text` contains "texas"”
Measured Metric = 0.90909 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `text` contains "texas"
threshold 0.9306910569105691
Test Recall on data slice “`text` contains "life"”
Measured Metric = 0.91667 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `text` contains "life"
threshold 0.9306910569105691
Test Accuracy on data slice “`text` contains "guilty"”
Measured Metric = 0.92593 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `text` contains "guilty"
threshold 0.9386
Test Recall on data slice “`text` contains "september"”
Measured Metric = 0.92 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `text` contains "september"
threshold 0.9306910569105691
Test Accuracy on data slice “`avg_word_length(text)` < 4.884 AND `avg_word_length(text)` >= 4.835”
Measured Metric = 0.93333 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `avg_word_length(text)` < 4.884 AND `avg_word_length(text)` >= 4.835
threshold 0.9386
Test Accuracy on data slice “`avg_digits(text)` >= 0.007 AND `avg_digits(text)` < 0.008”
Measured Metric = 0.93333 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `avg_digits(text)` >= 0.007 AND `avg_digits(text)` < 0.008
threshold 0.9386
Test Accuracy on data slice “`text_length(text)` >= 2446.500 AND `text_length(text)` < 2572.500”
Measured Metric = 0.93333 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `text_length(text)` >= 2446.500 AND `text_length(text)` < 2572.500
threshold 0.9386
Test Accuracy on data slice “`title` contains "video"”
Measured Metric = 0.93548 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `title` contains "video"
threshold 0.9386
Test Recall on data slice “`avg_digits(text)` >= 0.003 AND `avg_digits(text)` < 0.004”
Measured Metric = 0.92857 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `avg_digits(text)` >= 0.003 AND `avg_digits(text)` < 0.004
threshold 0.9306910569105691
Test Accuracy on data slice “`text` contains "elections"”
Measured Metric = 0.9375 close Failed
model 5135f9ad-6d07-4db6-af80-a84dd1965396
dataset fake_and_real_news
slicing_function `text` contains "elections"
threshold 0.9386

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