Open In Colab View Notebook on GitHub

Medical transcript 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:

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

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

[ ]:
%pip install nltk

Import librariesยถ

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

import nltk
import pandas as pd
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer
from typing import Iterable

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

Define constantsยถ

[7]:
# Constants.
LABELS_LIST = [
    'Neurosurgery',
    'ENT - Otolaryngology',
    'Discharge Summary',
    'General Medicine',
    'Gastroenterology',
    'Neurology',
    'SOAP / Chart / Progress Notes',
    'Obstetrics / Gynecology',
    'Urology'
]

TEXT_COLUMN_NAME = "transcription"
TARGET_COLUMN_NAME = "medical_specialty"

RANDOM_SEED = 8888

# Data.
DATA_URL = "ftp://sys.giskard.ai/pub/unit_test_resources/medical_transcript_classification_dataset/mtsamples.csv"
DATA_PATH = Path.home() / ".giskard" / "medical_transcript_classification_dataset" / "mtsamples.csv"

Dataset preparationยถ

Download NLTK stopwords corpusยถ

[ ]:
# Download list of english stopwords.
nltk.download('stopwords')

Load dataยถ

[9]:
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 load_data() -> pd.DataFrame:
    """Load and initially preprocess data."""
    fetch_from_ftp(DATA_URL, DATA_PATH)

    df = pd.read_csv(DATA_PATH)

    # Drop useless columns.
    df = df.drop(columns=['Unnamed: 0', "description", "sample_name", "keywords"])

    # Trim text.
    df = df.apply(lambda x: x.str.strip())

    # Filter samples by label.
    df = df[df[TARGET_COLUMN_NAME].isin(LABELS_LIST)]

    # Drop rows with no transcript.
    df = df[df[TEXT_COLUMN_NAME].notna()]

    return df
[ ]:
transcript_df = load_data()

Train-test splitยถ

[11]:
X_train, X_test, y_train, y_test = train_test_split(transcript_df[[TEXT_COLUMN_NAME]],
                                                    transcript_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.

[12]:
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).
    name="medical_transcript_dataset",  # Ground truth variable.
    target=TARGET_COLUMN_NAME  # Optional.
)

Model buildingยถ

Define preprocessing stepsยถ

[13]:
stemmer = SnowballStemmer("english")
stop_words = stopwords.words("english")


def preprocess_text(df: pd.DataFrame) -> pd.DataFrame:
    """Preprocess text."""
    # Lower.
    df[TEXT_COLUMN_NAME] = df[TEXT_COLUMN_NAME].apply(lambda x: x.lower())

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

    # Tokenize.
    df[TEXT_COLUMN_NAME] = df[TEXT_COLUMN_NAME].apply(lambda x: x.split())

    # Stem.
    df[TEXT_COLUMN_NAME] = df[TEXT_COLUMN_NAME].apply(lambda x: [stemmer.stem(word) for word in x])

    # Remove stop-words.
    df[TEXT_COLUMN_NAME] = df[TEXT_COLUMN_NAME].apply(
        lambda x: ' '.join([word for word in x if word not in stop_words]))

    return df


def adapt_vectorizer_input(df: pd.DataFrame) -> Iterable:
    """Adapt input for the vectorizers.

    The problem is that vectorizers accept iterable, not DataFrame, but Series. Thus, we need to ravel dataframe with text have input single dimension.
    Issue reference: https://stackoverflow.com/questions/50665240/valueerror-found-input-variables-with-inconsistent-numbers-of-samples-1-3185"""

    df = df.iloc[:, 0]
    return df


text_preprocessor = FunctionTransformer(preprocess_text)
vectorizer_input_adapter = FunctionTransformer(adapt_vectorizer_input)

Build estimatorยถ

[ ]:
pipeline = Pipeline(steps=[
    ("text_preprocessor", text_preprocessor),
    ("vectorizer_input_adapter", vectorizer_input_adapter),
    ("vectorizer", CountVectorizer(ngram_range=(1, 1))),
    ("estimator", RandomForestClassifier(random_state=RANDOM_SEED))
])

pipeline.fit(X_train, y_train)
y_pred = pipeline.predict(X_test)

print(classification_report(y_test, y_pred))

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.

[ ]:
# Wrap the prediction function so that the whole pipeline get saved to the Hub
def prediction_function(df):
    return pipeline.predict_proba(df)


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

# Validate wrapped model.
print(classification_report(y_test, pipeline.classes_[giskard_model.predict(giskard_dataset).raw_prediction]))

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

[22]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
Executed 'Invariance to โ€œAdd typosโ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'transformation_function': <giskard.scanner.robustness.text_transformations.TextTypoTransformation object at 0x124168760>, 'threshold': 0.95, 'output_sensitivity': 0.05}:
               Test failed
               Metric: 0.91
                - [TestMessageLevel.INFO] 371 rows were perturbed

Executed 'Overconfidence on data slice โ€œ`transcription` contains "weight"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x126160f70>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.74


Executed 'Overconfidence on data slice โ€œ`transcription` contains "having"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1282be5c0>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.74


Executed 'Overconfidence on data slice โ€œ`transcription` contains "today"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1282d0940>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.74


Executed 'Overconfidence on data slice โ€œ`transcription` contains "temperature"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12897e1d0>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.73


Executed 'Overconfidence on data slice โ€œ`transcription` contains "dr"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x128754e80>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.73


Executed 'Overconfidence on data slice โ€œ`transcription` contains "follow"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x124478610>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.72


Executed 'Overconfidence on data slice โ€œ`avg_whitespace(transcription)` >= 0.160โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x1240a0040>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.71


Executed 'Overconfidence on data slice โ€œ`transcription` contains "blood"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12837f1c0>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.7


Executed 'Overconfidence on data slice โ€œ`transcription` contains "distress"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x128389f00>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.69


Executed 'Overconfidence on data slice โ€œ`transcription` contains "mg"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12897f070>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.69


Executed 'Overconfidence on data slice โ€œ`transcription` contains "continue"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x124201f00>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.69


Executed 'Overconfidence on data slice โ€œ`transcription` contains "stable"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x126160df0>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.68


Executed 'Overconfidence on data slice โ€œ`avg_word_length(transcription)` < 5.789โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x12447bd30>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.68


Executed 'Overconfidence on data slice โ€œ`text_length(transcription)` >= 2145.000โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.text_slicer.MetadataSliceFunction object at 0x1243a6e30>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.68


Executed 'Overconfidence on data slice โ€œ`transcription` contains "discharge"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x126160820>, 'threshold': 0.6569444444444444, 'p_threshold': 0.2468526289804987}:
               Test failed
               Metric: 0.67


Executed 'Precision on data slice โ€œ`transcription` contains "xyz"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12939e3b0>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.32


Executed 'Precision on data slice โ€œ`transcription` contains "subjective"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1282ee980>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.37


Executed 'Precision on data slice โ€œ`transcription` contains "admission"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1283579a0>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.38


Executed 'Precision on data slice โ€œ`transcription` contains "daily"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1292f43a0>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.38


Executed 'Precision on data slice โ€œ`transcription` contains "coronary"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12933d660>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.39


Executed 'Precision on data slice โ€œ`transcription` contains "followup"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1292db760>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.4


Executed 'Precision on data slice โ€œ`transcription` contains "lung"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1286cb0d0>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.4


Executed 'Precision on data slice โ€œ`transcription` contains "count"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1292f6200>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.4


Executed 'Precision on data slice โ€œ`transcription` contains "function"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1292ee620>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.41


Executed 'Precision on data slice โ€œ`transcription` contains "abc"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1292efca0>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.42


Executed 'Precision on data slice โ€œ`transcription` contains "improved"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1292b7eb0>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.42


Executed 'Precision on data slice โ€œ`transcription` contains "discharge"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1292ed1e0>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.42


Executed 'Precision on data slice โ€œ`transcription` contains "greater"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x128378940>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.43


Executed 'Precision on data slice โ€œ`transcription` contains "aspirin"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x12892b520>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.43


Executed 'Precision on data slice โ€œ`transcription` contains "continue"โ€' with arguments {'model': <giskard.models.function.PredictionFunctionModel object at 0x12445b8e0>, 'dataset': <giskard.datasets.base.Dataset object at 0x12409d6c0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x129317fa0>, 'threshold': 0.581266846361186}:
               Test failed
               Metric: 0.44


[22]:
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.91375 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
transformation_function Add typos
threshold 0.95
output_sensitivity 0.05
Test Overconfidence on data slice โ€œ`transcription` contains "weight"โ€
Measured Metric = 0.74194 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "weight"
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`transcription` contains "having"โ€
Measured Metric = 0.74194 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "having"
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`transcription` contains "today"โ€
Measured Metric = 0.73684 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "today"
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`transcription` contains "temperature"โ€
Measured Metric = 0.73333 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "temperature"
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`transcription` contains "dr"โ€
Measured Metric = 0.72549 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "dr"
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`transcription` contains "follow"โ€
Measured Metric = 0.72222 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "follow"
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`avg_whitespace(transcription)` >= 0.160โ€
Measured Metric = 0.71429 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `avg_whitespace(transcription)` >= 0.160
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`transcription` contains "blood"โ€
Measured Metric = 0.69737 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "blood"
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`transcription` contains "distress"โ€
Measured Metric = 0.69444 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "distress"
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`transcription` contains "mg"โ€
Measured Metric = 0.69388 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "mg"
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`transcription` contains "continue"โ€
Measured Metric = 0.68966 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "continue"
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`transcription` contains "stable"โ€
Measured Metric = 0.68085 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "stable"
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`avg_word_length(transcription)` < 5.789โ€
Measured Metric = 0.67647 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `avg_word_length(transcription)` < 5.789
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`text_length(transcription)` >= 2145.000โ€
Measured Metric = 0.67568 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `text_length(transcription)` >= 2145.000
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Overconfidence on data slice โ€œ`transcription` contains "discharge"โ€
Measured Metric = 0.67347 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "discharge"
threshold 0.6569444444444444
p_threshold 0.2468526289804987
Test Precision on data slice โ€œ`transcription` contains "xyz"โ€
Measured Metric = 0.31818 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "xyz"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "subjective"โ€
Measured Metric = 0.36667 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "subjective"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "admission"โ€
Measured Metric = 0.375 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "admission"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "daily"โ€
Measured Metric = 0.38462 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "daily"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "coronary"โ€
Measured Metric = 0.3913 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "coronary"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "followup"โ€
Measured Metric = 0.39583 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "followup"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "lung"โ€
Measured Metric = 0.4 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "lung"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "count"โ€
Measured Metric = 0.4 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "count"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "function"โ€
Measured Metric = 0.41379 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "function"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "abc"โ€
Measured Metric = 0.41667 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "abc"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "improved"โ€
Measured Metric = 0.41935 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "improved"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "discharge"โ€
Measured Metric = 0.42353 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "discharge"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "greater"โ€
Measured Metric = 0.43478 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "greater"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "aspirin"โ€
Measured Metric = 0.43478 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "aspirin"
threshold 0.581266846361186
Test Precision on data slice โ€œ`transcription` contains "continue"โ€
Measured Metric = 0.44231 close Failed
model 082b3091-113e-4b56-b010-9902f9b9dcf8
dataset medical_transcript_dataset
slicing_function `transcription` contains "continue"
threshold 0.581266846361186

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