Customer churn 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:
Binary classification of the customerโs churn.
Model:
LGBMClassifier
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
[4]:
%pip install giskard --upgrade
Import librariesยถ
[1]:
import pandas as pd
from lightgbm import LGBMClassifier
from sklearn.compose import ColumnTransformer
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
from giskard import Dataset, Model, scan, GiskardClient, testing, Suite
Define constantsยถ
[2]:
# Constants.
RANDOM_SEED = 123
TARGET_COLUMN_NAME = "Churn"
COLUMN_TYPES = {'gender': "category",
'SeniorCitizen': "category",
'Partner': "category",
'Dependents': "category",
'tenure': "numeric",
'PhoneService': "category",
'MultipleLines': "category",
'InternetService': "category",
'OnlineSecurity': "category",
'OnlineBackup': "category",
'DeviceProtection': "category",
'TechSupport': "category",
'StreamingTV': "category",
'StreamingMovies': "category",
'Contract': "category",
'PaperlessBilling': "category",
'PaymentMethod': "category",
'MonthlyCharges': "numeric",
'TotalCharges': "numeric",
TARGET_COLUMN_NAME: "category"}
FEATURE_TYPES = {i:COLUMN_TYPES[i] for i in COLUMN_TYPES if i != TARGET_COLUMN_NAME}
COLUMNS_TO_SCALE = [key for key in FEATURE_TYPES.keys() if FEATURE_TYPES[key] == "numeric"]
COLUMNS_TO_ENCODE = [key for key in FEATURE_TYPES.keys() if FEATURE_TYPES[key] == "category"]
# Paths.
DATASET_URL = "https://raw.githubusercontent.com/Giskard-AI/examples/main/datasets/WA_Fn-UseC_-Telco-Customer-Churn.csv"
Dataset preparationยถ
Load and preprocess dataยถ
[3]:
def preprocess(df: pd.DataFrame) -> pd.DataFrame:
"""Perform data-preprocessing steps."""
df['TotalCharges'] = pd.to_numeric(df['TotalCharges'], errors='coerce')
df = df.dropna()
df = df.drop(columns='customerID')
df['PaymentMethod'] = df['PaymentMethod'].str.replace(' (automatic)', '', regex=False)
return df
churn_df = pd.read_csv(DATASET_URL)
churn_df = preprocess(churn_df)
Train-test splitยถ
[4]:
X_train, X_test, Y_train, Y_test = train_test_split(churn_df.drop(columns=TARGET_COLUMN_NAME),
churn_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.
[5]:
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="Churn classification dataset", # Optional
cat_columns=COLUMNS_TO_ENCODE # List of categorical columns. Optional, but is a MUST if available. Inferred automatically if not.
)
Model buildingยถ
Define preprocessing stepsยถ
[6]:
preprocessor = ColumnTransformer(transformers=[
('num', StandardScaler(), COLUMNS_TO_SCALE),
('cat', OneHotEncoder(handle_unknown='ignore',drop='first'), COLUMNS_TO_ENCODE)
])
Build estimatorยถ
[ ]:
pipeline = Pipeline(steps=[
('preprocessor', preprocessor),
('classifier', LGBMClassifier(random_state=RANDOM_SEED))
])
# Fit model.
pipeline.fit(X_train, Y_train)
# Evaluate model.
Y_train_pred = pipeline.predict(X_train)
train_accuracy = accuracy_score(Y_train, Y_train_pred)
Y_test_pred = pipeline.predict(X_test)
test_accuracy = accuracy_score(Y_test, Y_test_pred)
print(f'Train Accuracy: {train_accuracy:.2f}')
print(f'Test Accuracy: {test_accuracy:.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=pipeline, # 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="Churn classification", # Optional
classification_labels=pipeline.classes_, # Their order MUST be identical to the prediction_function's output order
feature_names=FEATURE_TYPES.keys(), # Default: all columns of your dataset
)
# Validate wrapped model.
wrapped_Y_pred = giskard_model.predict(giskard_dataset).prediction
wrapped_accuracy = accuracy_score(Y_test, wrapped_Y_pred)
print(f'Wrapped Test Accuracy: {wrapped_accuracy:.2f}')
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()
Executed 'Overconfidence on data slice โ`TotalCharges` >= 3246.925โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x137ccf6d0>, 'threshold': 0.4486033519553073, 'p_threshold': 0.5}:
Test failed
Metric: 0.56
Executed 'Overconfidence on data slice โ`InternetService` == "DSL"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x137d7e980>, 'threshold': 0.4486033519553073, 'p_threshold': 0.5}:
Test failed
Metric: 0.51
Executed 'Overconfidence on data slice โ`OnlineBackup` == "Yes"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x137b869e0>, 'threshold': 0.4486033519553073, 'p_threshold': 0.5}:
Test failed
Metric: 0.46
Executed 'Underconfidence on data slice โ`OnlineSecurity` == "No"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x137e51720>, 'threshold': 0.014391353811149032, 'p_threshold': 0.95}:
Test failed
Metric: 0.02
Executed 'Underconfidence on data slice โ`Contract` == "Month-to-month"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x137bd1570>, 'threshold': 0.014391353811149032, 'p_threshold': 0.95}:
Test failed
Metric: 0.02
Executed 'Underconfidence on data slice โ`Dependents` == "No"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x137e50d30>, 'threshold': 0.014391353811149032, 'p_threshold': 0.95}:
Test failed
Metric: 0.02
Executed 'Recall on data slice โ`Contract` == "One year"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1380c5bd0>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.0
Executed 'Recall on data slice โ`tenure` >= 44.500 AND `tenure` < 70.500โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x137ee3580>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.06
Executed 'Recall on data slice โ`InternetService` == "No"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1380aaa10>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.08
Executed 'Recall on data slice โ`OnlineSecurity` == "No internet service"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1380abf10>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.08
Executed 'Recall on data slice โ`OnlineBackup` == "No internet service"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1380aaa40>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.08
Executed 'Recall on data slice โ`DeviceProtection` == "No internet service"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1380aafe0>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.08
Executed 'Recall on data slice โ`TechSupport` == "No internet service"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1380ab0a0>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.08
Executed 'Recall on data slice โ`StreamingTV` == "No internet service"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1380ab790>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.08
Executed 'Recall on data slice โ`StreamingMovies` == "No internet service"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1380abd30>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.08
Executed 'Recall on data slice โ`MonthlyCharges` < 20.775โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x137ee3a00>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.1
Executed 'Recall on data slice โ`TechSupport` == "Yes"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1380ab460>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.21
Executed 'Recall on data slice โ`OnlineSecurity` == "Yes"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1380aaaa0>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.21
Executed 'Recall on data slice โ`PaymentMethod` == "Credit card"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1380c5090>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.28
Executed 'Recall on data slice โ`InternetService` == "DSL"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x1380aa8f0>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.32
Executed 'Recall on data slice โ`Dependents` == "Yes"โ' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x12217a440>, 'dataset': <giskard.datasets.base.Dataset object at 0x122061f00>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x138093e20>, 'threshold': 0.49131679389312977}:
Test failed
Metric: 0.33
[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_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.
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()