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:
Binary classification of news being fake or real, based on their text.
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
[21]:
%pip install giskard --upgrade
Import librariesΒΆ
[1]:
import os
import string
import tarfile
from pathlib import Path
from typing import Tuple, Callable
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 giskard import Dataset, Model, scan, testing
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 = "https://giskard-library-test-datasets.s3.eu-north-1.amazonaws.com/fake_real_news_dataset-{}"
DATA_PATH = Path.home() / ".giskard" / "fake_real_news_dataset"
Dataset preparationΒΆ
Load and preprocess dataΒΆ
[ ]:
def fetch_demo_data(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.tar.gz", "True.csv.tar.gz", "glove_100d.txt.tar.gz")
for file_name in files_to_fetch:
fetch_demo_data(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.tar.gz", **kwargs)
fake_df = pd.read_csv(DATA_PATH / "Fake.csv.tar.gz", **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.
[ ]:
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 tarfile.open(DATA_PATH / "glove_100d.txt.tar.gz", "r:gz")
.extractfile("fake_real_news_dataset-glove_100d.txt")
.read()
.decode()
)
# 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()
2024-05-29 12:04:25,717 pid:57157 MainThread giskard.datasets.base INFO Casting dataframe columns from {'title': 'object', 'text': 'object'} to {'title': 'object', 'text': 'object'}
2024-05-29 12:04:25,720 pid:57157 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (30, 3) executed in 0:00:00.013458
Executed 'Recall on data slice β`text_length(text)` >= 2570.500 AND `text_length(text)` < 2729.500β' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x30d36ec80>, 'dataset': <giskard.datasets.base.Dataset object at 0x31dc1b820>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x366023850>, 'threshold': 0.9384146341463414}:
Test failed
Metric: 0.91
2024-05-29 12:04:25,756 pid:57157 MainThread giskard.datasets.base INFO Casting dataframe columns from {'title': 'object', 'text': 'object'} to {'title': 'object', 'text': 'object'}
2024-05-29 12:04:25,757 pid:57157 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (42, 3) executed in 0:00:00.006029
Executed 'Recall on data slice β`text` contains "texas"β' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x30d36ec80>, 'dataset': <giskard.datasets.base.Dataset object at 0x31dc1b820>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x316d33850>, 'threshold': 0.9384146341463414}:
Test failed
Metric: 0.91
2024-05-29 12:04:25,781 pid:57157 MainThread giskard.datasets.base INFO Casting dataframe columns from {'title': 'object', 'text': 'object'} to {'title': 'object', 'text': 'object'}
2024-05-29 12:04:25,782 pid:57157 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (38, 3) executed in 0:00:00.005618
Executed 'Recall on data slice β`text` contains "october"β' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x30d36ec80>, 'dataset': <giskard.datasets.base.Dataset object at 0x31dc1b820>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x316caf160>, 'threshold': 0.9384146341463414}:
Test failed
Metric: 0.91
2024-05-29 12:04:25,808 pid:57157 MainThread giskard.datasets.base INFO Casting dataframe columns from {'title': 'object', 'text': 'object'} to {'title': 'object', 'text': 'object'}
2024-05-29 12:04:25,808 pid:57157 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (27, 3) executed in 0:00:00.005583
Executed 'Accuracy on data slice β`text` contains "guilty"β' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x30d36ec80>, 'dataset': <giskard.datasets.base.Dataset object at 0x31dc1b820>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x344927e80>, 'threshold': 0.9424}:
Test failed
Metric: 0.93
2024-05-29 12:04:25,832 pid:57157 MainThread giskard.datasets.base INFO Casting dataframe columns from {'title': 'object', 'text': 'object'} to {'title': 'object', 'text': 'object'}
2024-05-29 12:04:25,833 pid:57157 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (61, 3) executed in 0:00:00.006272
Executed 'Recall on data slice β`text` contains "investigation"β' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x30d36ec80>, 'dataset': <giskard.datasets.base.Dataset object at 0x31dc1b820>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x31837ea70>, 'threshold': 0.9384146341463414}:
Test failed
Metric: 0.93
2024-05-29 12:04:25,844 pid:57157 MainThread giskard.datasets.base INFO Casting dataframe columns from {'title': 'object', 'text': 'object'} to {'title': 'object', 'text': 'object'}
2024-05-29 12:04:25,845 pid:57157 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (33, 3) executed in 0:00:00.006265
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 0x30d36ec80>, 'dataset': <giskard.datasets.base.Dataset object at 0x31dc1b820>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x34709ebf0>, 'threshold': 0.9384146341463414}:
Test failed
Metric: 0.93
2024-05-29 12:04:25,847 pid:57157 MainThread giskard.core.suite INFO Executed test suite 'My first test suite'
2024-05-29 12:04:25,847 pid:57157 MainThread giskard.core.suite INFO result: failed
2024-05-29 12:04:25,848 pid:57157 MainThread giskard.core.suite INFO Recall on data slice β`text_length(text)` >= 2570.500 AND `text_length(text)` < 2729.500β ({'model': <giskard.models.function.PredictionFunctionModel object at 0x30d36ec80>, 'dataset': <giskard.datasets.base.Dataset object at 0x31dc1b820>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x366023850>, 'threshold': 0.9384146341463414}): {failed, metric=0.9090909090909091}
2024-05-29 12:04:25,848 pid:57157 MainThread giskard.core.suite INFO Recall on data slice β`text` contains "texas"β ({'model': <giskard.models.function.PredictionFunctionModel object at 0x30d36ec80>, 'dataset': <giskard.datasets.base.Dataset object at 0x31dc1b820>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x316d33850>, 'threshold': 0.9384146341463414}): {failed, metric=0.9090909090909091}
2024-05-29 12:04:25,849 pid:57157 MainThread giskard.core.suite INFO Recall on data slice β`text` contains "october"β ({'model': <giskard.models.function.PredictionFunctionModel object at 0x30d36ec80>, 'dataset': <giskard.datasets.base.Dataset object at 0x31dc1b820>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x316caf160>, 'threshold': 0.9384146341463414}): {failed, metric=0.9130434782608695}
2024-05-29 12:04:25,849 pid:57157 MainThread giskard.core.suite INFO Accuracy on data slice β`text` contains "guilty"β ({'model': <giskard.models.function.PredictionFunctionModel object at 0x30d36ec80>, 'dataset': <giskard.datasets.base.Dataset object at 0x31dc1b820>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x344927e80>, 'threshold': 0.9424}): {failed, metric=0.9259259259259259}
2024-05-29 12:04:25,850 pid:57157 MainThread giskard.core.suite INFO Recall on data slice β`text` contains "investigation"β ({'model': <giskard.models.function.PredictionFunctionModel object at 0x30d36ec80>, 'dataset': <giskard.datasets.base.Dataset object at 0x31dc1b820>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x31837ea70>, 'threshold': 0.9384146341463414}): {failed, metric=0.9333333333333333}
2024-05-29 12:04:25,850 pid:57157 MainThread giskard.core.suite INFO Recall on data slice β`text_length(title)` >= 92.500 AND `text_length(title)` < 97.500β ({'model': <giskard.models.function.PredictionFunctionModel object at 0x30d36ec80>, 'dataset': <giskard.datasets.base.Dataset object at 0x31dc1b820>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x34709ebf0>, 'threshold': 0.9384146341463414}): {failed, metric=0.9333333333333333}
[13]:
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()