Open In Colab View Notebook on GitHub

M5 Sales prediction [LGBM]#

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

[16]:
%pip install giskard --upgrade

Import libraries#

[2]:
from pathlib import Path
from typing import Tuple
from urllib.request import urlretrieve

import pandas as pd
from sklearn import preprocessing
from lightgbm import LGBMRegressor
from sklearn.metrics import r2_score

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

Define constants#

[3]:
# Constants.
ID_COLUMN = "id"
DATE_COLUMN = "date"
TARGET_COLUMN = "demand"
SPLIT_DATE = "2016-03-27"

# Paths.
DATA_URL = "ftp://sys.giskard.ai/pub/unit_test_resources/m5_sales_prediction_dataset/{}"
DATA_PATH = Path.home() / ".giskard" / "m5_sales_prediction_dataset"
DATA_FILES = ["calendar.csv", "sales_train_validation.csv", "sell_prices.csv"]

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:
    """Fetch all necessary datafiles."""
    for file_name in DATA_FILES:
        source = DATA_URL.format(file_name)
        destination = DATA_PATH / file_name
        fetch_from_ftp(source, destination)


def load_data(n_series_use: int = 100) -> Tuple[pd.DataFrame, ...]:
    """Load necessary data files."""
    fetch_dataset()

    calendar_df = pd.read_csv(DATA_PATH / "calendar.csv")
    prices_df = pd.read_csv(DATA_PATH / 'sell_prices.csv')
    sales_df = pd.read_csv(DATA_PATH / 'sales_train_validation.csv')
    sales_df = sales_df.iloc[:n_series_use]

    return calendar_df, prices_df, sales_df


dfs = load_data()
[ ]:
def preprocess_data(calendar_df: pd.DataFrame, prices_df: pd.DataFrame, sales_df: pd.DataFrame) -> pd.DataFrame:
    """Preprocess and create df with the whole data."""
    # Melt the sales data: translate columnar demand representation into single target vector.
    data = pd.melt(sales_df,
                   id_vars=[ID_COLUMN, 'item_id', 'dept_id', 'cat_id', 'store_id', 'state_id'],
                   var_name='day', value_name=TARGET_COLUMN)
    data = data.drop(columns=ID_COLUMN)

    # Add the calendar data.
    calendar_df = calendar_df.drop(['weekday', 'wday', 'month', 'year'], axis=1)
    data = pd.merge(data, calendar_df, how ='left', left_on=['day'], right_on=['d'])
    data = data.drop(columns=['d', 'day'])

    # Add the sell price data.
    data = data.merge(prices_df, on=['store_id', 'item_id', 'wm_yr_wk'], how='left')

    # Fill NaN values.
    nan_features = ['event_name_1', 'event_type_1', 'event_name_2', 'event_type_2']
    for feature in nan_features:
        data[feature] = data[feature].fillna('unknown')

    # Encode categorical features.
    to_encode = ['item_id', 'dept_id', 'cat_id', 'store_id', 'state_id', 'event_name_1', 'event_type_1', 'event_name_2', 'event_type_2']
    for feature in to_encode:
        encoder = preprocessing.LabelEncoder()
        data[feature] = encoder.fit_transform(data[feature])

    print(f'Final dataset has {data.shape[0]} rows and {data.shape[1]} columns')
    return data


df = preprocess_data(*dfs)

Train-test split#

[ ]:
def drop_after_split(x: pd.DataFrame) -> pd.DataFrame:
    """Drops useless data after train-test split."""
    to_drop = [DATE_COLUMN, TARGET_COLUMN]
    x = x.drop(columns=to_drop)
    return x


def train_val_split(data: pd.DataFrame) -> Tuple[pd.DataFrame, ...]:
    """Perform train/val split, where the split point is the date '2016-03-27'. Validation records are 28 days for each product."""
    x_train = data[data[DATE_COLUMN] <= SPLIT_DATE]
    y_train = x_train[TARGET_COLUMN]
    x_train = drop_after_split(x_train)
    print(f"Train samples: {len(x_train)}")

    x_val = data[data[DATE_COLUMN] > SPLIT_DATE]
    y_val = x_val[TARGET_COLUMN]
    x_val = drop_after_split(x_val)
    print(f"Valid samples: {len(x_val)}")

    return x_train, y_train, x_val, y_val


X_train, Y_train, X_val, Y_val = train_val_split(df)

Wrap dataset with Giskard#

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

[7]:
raw_data = pd.concat([X_val, Y_val], 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,  # Ground truth variable
    name="M5 products timeseries dataset",  # Optional
    cat_columns=X_val.select_dtypes(int).columns.tolist()  # List of categorical columns. Optional, but is a MUST if available. Inferred automatically if not.
)

Model building#

Build estimator#

[ ]:
ESTIMATOR_PARAMS = {
    'n_estimators': 300,
    'seed': 0,
    'n_jobs': -1,
    "verbose": -1,
}

regressor = LGBMRegressor(**ESTIMATOR_PARAMS)
regressor.fit(X_train, Y_train)

# Validate estimator.
y_train_pred = regressor.predict(X_train)
train_score = r2_score(Y_train, y_train_pred)
print(f'Train R2-score: {train_score: .2f}')

y_val_pred = regressor.predict(X_val)
val_score = r2_score(Y_val, y_val_pred)
print(f'Val R2-score: {val_score: .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=regressor,  # 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="regression",  # Either regression, classification or text_generation.
    name="M5 sales timeseries regressor",  # Optional
    feature_names=X_val.columns  # Default: all columns of your dataset
)

Detect vulnerabilities in your model#

Scan your model for vulnerabilities with Giskard#

Giskard’s scan allows you to detect vulnerabilities in your model automatically. These include performance biases, unrobustness, data leakage, stochasticity, underconfidence, ethical issues, and more. For detailed information about the scan feature, please refer to our scan documentation.

[ ]:
results = scan(giskard_model, giskard_dataset)
[11]:
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.

[12]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
Executed 'MSE on data slice “`snap_TX` == 1”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12653d090>, 'dataset': <giskard.datasets.base.Dataset object at 0x12615f700>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x13c3b5cc0>, 'threshold': 7.1383301822423295}:
               Test failed
               Metric: 8.92


Executed 'MSE on data slice “`snap_WI` == 1”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12653d090>, 'dataset': <giskard.datasets.base.Dataset object at 0x12615f700>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x13c3b5f00>, 'threshold': 7.1383301822423295}:
               Test failed
               Metric: 8.64


Executed 'MSE on data slice “`wm_yr_wk` == 1.161e+04”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12653d090>, 'dataset': <giskard.datasets.base.Dataset object at 0x12615f700>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x13c3b5090>, 'threshold': 7.1383301822423295}:
               Test failed
               Metric: 8.63


Executed 'MSE on data slice “`snap_CA` == 1”' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12653d090>, 'dataset': <giskard.datasets.base.Dataset object at 0x12615f700>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x13c3b5a80>, 'threshold': 7.1383301822423295}:
               Test failed
               Metric: 7.92


[12]:
close Test suite failed. To debug your failing test and diagnose the issue, please run the Giskard hub (see documentation)
Test MSE on data slice “`snap_TX` == 1”
Measured Metric = 8.91521 close Failed
model 953d4ee7-82dc-421e-910d-9043450544ae
dataset M5 products timeseries dataset
slicing_function `snap_TX` == 1
threshold 7.1383301822423295
Test MSE on data slice “`snap_WI` == 1”
Measured Metric = 8.6378 close Failed
model 953d4ee7-82dc-421e-910d-9043450544ae
dataset M5 products timeseries dataset
slicing_function `snap_WI` == 1
threshold 7.1383301822423295
Test MSE on data slice “`wm_yr_wk` == 1.161e+04”
Measured Metric = 8.63006 close Failed
model 953d4ee7-82dc-421e-910d-9043450544ae
dataset M5 products timeseries dataset
slicing_function `wm_yr_wk` == 1.161e+04
threshold 7.1383301822423295
Test MSE on data slice “`snap_CA` == 1”
Measured Metric = 7.92286 close Failed
model 953d4ee7-82dc-421e-910d-9043450544ae
dataset M5 products timeseries dataset
slicing_function `snap_CA` == 1
threshold 7.1383301822423295

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_r2) that checks if the test R2 score is above the given threshold. For more examples of tests and functions, refer to the Giskard catalog.

[ ]:
test_suite.add_test(testing.test_r2(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()