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:
Prediction of the productsβ demand for the next 28 days.
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
[ ]:
%pip install giskard --upgrade
Import librariesΒΆ
[1]:
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, scan, testing
Define constantsΒΆ
[2]:
# 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.
[ ]:
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)
[10]:
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.
[11]:
test_suite = results.generate_test_suite("My first test suite")
test_suite.run()
2024-05-29 13:43:58,662 pid:66104 MainThread giskard.datasets.base INFO Casting dataframe columns from {'item_id': 'int64', 'dept_id': 'int64', 'cat_id': 'int64', 'store_id': 'int64', 'state_id': 'int64', 'wm_yr_wk': 'int64', 'event_name_1': 'int64', 'event_type_1': 'int64', 'event_name_2': 'int64', 'event_type_2': 'int64', 'snap_CA': 'int64', 'snap_TX': 'int64', 'snap_WI': 'int64', 'sell_price': 'float64'} to {'item_id': 'int64', 'dept_id': 'int64', 'cat_id': 'int64', 'store_id': 'int64', 'state_id': 'int64', 'wm_yr_wk': 'int64', 'event_name_1': 'int64', 'event_type_1': 'int64', 'event_name_2': 'int64', 'event_type_2': 'int64', 'snap_CA': 'int64', 'snap_TX': 'int64', 'snap_WI': 'int64', 'sell_price': 'float64'}
2024-05-29 13:43:58,664 pid:66104 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (1000, 15) executed in 0:00:00.015511
Executed 'MSE on data slice β`snap_TX` == 1β' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x173e2abf0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e18ca90>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3a911bcd0>, 'threshold': 7.1383301822423295}:
Test failed
Metric: 8.92
2024-05-29 13:43:58,683 pid:66104 MainThread giskard.datasets.base INFO Casting dataframe columns from {'item_id': 'int64', 'dept_id': 'int64', 'cat_id': 'int64', 'store_id': 'int64', 'state_id': 'int64', 'wm_yr_wk': 'int64', 'event_name_1': 'int64', 'event_type_1': 'int64', 'event_name_2': 'int64', 'event_type_2': 'int64', 'snap_CA': 'int64', 'snap_TX': 'int64', 'snap_WI': 'int64', 'sell_price': 'float64'} to {'item_id': 'int64', 'dept_id': 'int64', 'cat_id': 'int64', 'store_id': 'int64', 'state_id': 'int64', 'wm_yr_wk': 'int64', 'event_name_1': 'int64', 'event_type_1': 'int64', 'event_name_2': 'int64', 'event_type_2': 'int64', 'snap_CA': 'int64', 'snap_TX': 'int64', 'snap_WI': 'int64', 'sell_price': 'float64'}
2024-05-29 13:43:58,685 pid:66104 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (1000, 15) executed in 0:00:00.012052
Executed 'MSE on data slice β`snap_WI` == 1β' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x173e2abf0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e18ca90>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3a911bfd0>, 'threshold': 7.1383301822423295}:
Test failed
Metric: 8.64
2024-05-29 13:43:58,699 pid:66104 MainThread giskard.datasets.base INFO Casting dataframe columns from {'item_id': 'int64', 'dept_id': 'int64', 'cat_id': 'int64', 'store_id': 'int64', 'state_id': 'int64', 'wm_yr_wk': 'int64', 'event_name_1': 'int64', 'event_type_1': 'int64', 'event_name_2': 'int64', 'event_type_2': 'int64', 'snap_CA': 'int64', 'snap_TX': 'int64', 'snap_WI': 'int64', 'sell_price': 'float64'} to {'item_id': 'int64', 'dept_id': 'int64', 'cat_id': 'int64', 'store_id': 'int64', 'state_id': 'int64', 'wm_yr_wk': 'int64', 'event_name_1': 'int64', 'event_type_1': 'int64', 'event_name_2': 'int64', 'event_type_2': 'int64', 'snap_CA': 'int64', 'snap_TX': 'int64', 'snap_WI': 'int64', 'sell_price': 'float64'}
2024-05-29 13:43:58,701 pid:66104 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (700, 15) executed in 0:00:00.009145
Executed 'MSE on data slice β`wm_yr_wk` == 1.161e+04β' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x173e2abf0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e18ca90>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3a911ac80>, 'threshold': 7.1383301822423295}:
Test failed
Metric: 8.63
2024-05-29 13:43:58,716 pid:66104 MainThread giskard.datasets.base INFO Casting dataframe columns from {'item_id': 'int64', 'dept_id': 'int64', 'cat_id': 'int64', 'store_id': 'int64', 'state_id': 'int64', 'wm_yr_wk': 'int64', 'event_name_1': 'int64', 'event_type_1': 'int64', 'event_name_2': 'int64', 'event_type_2': 'int64', 'snap_CA': 'int64', 'snap_TX': 'int64', 'snap_WI': 'int64', 'sell_price': 'float64'} to {'item_id': 'int64', 'dept_id': 'int64', 'cat_id': 'int64', 'store_id': 'int64', 'state_id': 'int64', 'wm_yr_wk': 'int64', 'event_name_1': 'int64', 'event_type_1': 'int64', 'event_name_2': 'int64', 'event_type_2': 'int64', 'snap_CA': 'int64', 'snap_TX': 'int64', 'snap_WI': 'int64', 'sell_price': 'float64'}
2024-05-29 13:43:58,718 pid:66104 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (1000, 15) executed in 0:00:00.009801
Executed 'MSE on data slice β`snap_CA` == 1β' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x173e2abf0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e18ca90>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3a911b9d0>, 'threshold': 7.1383301822423295}:
Test failed
Metric: 7.92
2024-05-29 13:43:58,723 pid:66104 MainThread giskard.core.suite INFO Executed test suite 'My first test suite'
2024-05-29 13:43:58,723 pid:66104 MainThread giskard.core.suite INFO result: failed
2024-05-29 13:43:58,724 pid:66104 MainThread giskard.core.suite INFO MSE on data slice β`snap_TX` == 1β ({'model': <giskard.models.sklearn.SKLearnModel object at 0x173e2abf0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e18ca90>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3a911bcd0>, 'threshold': 7.1383301822423295}): {failed, metric=8.915211806609342}
2024-05-29 13:43:58,724 pid:66104 MainThread giskard.core.suite INFO MSE on data slice β`snap_WI` == 1β ({'model': <giskard.models.sklearn.SKLearnModel object at 0x173e2abf0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e18ca90>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3a911bfd0>, 'threshold': 7.1383301822423295}): {failed, metric=8.637798447295712}
2024-05-29 13:43:58,725 pid:66104 MainThread giskard.core.suite INFO MSE on data slice β`wm_yr_wk` == 1.161e+04β ({'model': <giskard.models.sklearn.SKLearnModel object at 0x173e2abf0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e18ca90>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3a911ac80>, 'threshold': 7.1383301822423295}): {failed, metric=8.630063641271192}
2024-05-29 13:43:58,725 pid:66104 MainThread giskard.core.suite INFO MSE on data slice β`snap_CA` == 1β ({'model': <giskard.models.sklearn.SKLearnModel object at 0x173e2abf0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e18ca90>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3a911b9d0>, 'threshold': 7.1383301822423295}): {failed, metric=7.922860008805299}
[11]:
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()