German credit scoring [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:
Binary classification. Whether to give a customer credit or not.
Model:
LogisticRegression
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]:
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from giskard import Model, Dataset, scan, testing
Define constantsΒΆ
[2]:
# Constants.
COLUMN_TYPES = {
"account_check_status": "category",
"duration_in_month": "numeric",
"credit_history": "category",
"purpose": "category",
"credit_amount": "numeric",
"savings": "category",
"present_employment_since": "category",
"installment_as_income_perc": "numeric",
"sex": "category",
"personal_status": "category",
"other_debtors": "category",
"present_residence_since": "numeric",
"property": "category",
"age": "category",
"other_installment_plans": "category",
"housing": "category",
"credits_this_bank": "numeric",
"job": "category",
"people_under_maintenance": "numeric",
"telephone": "category",
"foreign_worker": "category",
}
TARGET_COLUMN_NAME = "default"
COLUMNS_TO_SCALE = [key for key in COLUMN_TYPES.keys() if COLUMN_TYPES[key] == "numeric"]
COLUMNS_TO_ENCODE = [key for key in COLUMN_TYPES.keys() if COLUMN_TYPES[key] == "category"]
# Paths.
DATA_URL = "https://raw.githubusercontent.com/Giskard-AI/giskard-examples/main/datasets/credit_scoring_classification_model_dataset/german_credit_prepared.csv"
Dataset preparationΒΆ
Load dataΒΆ
[3]:
df = pd.read_csv(DATA_URL, keep_default_na=False, na_values=["_GSK_NA_"])
Train-test splitΒΆ
[4]:
X_train, X_test, Y_train, Y_test = train_test_split(df.drop(columns=TARGET_COLUMN_NAME), df[TARGET_COLUMN_NAME],
test_size=0.2, random_state=0, stratify=df[TARGET_COLUMN_NAME])
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='German credit scoring 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 pipelineΒΆ
[6]:
numeric_transformer = Pipeline(steps=[
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler())
])
categorical_transformer = Pipeline([
("imputer", SimpleImputer(strategy="constant", fill_value="missing")),
("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
])
preprocessor = ColumnTransformer(transformers=[
("num", numeric_transformer, COLUMNS_TO_SCALE),
("cat", categorical_transformer, COLUMNS_TO_ENCODE),
])
Build estimatorΒΆ
[ ]:
pipeline = Pipeline(steps=[
("preprocessor", preprocessor),
("classifier", LogisticRegression(max_iter=100))
])
pipeline.fit(X_train, Y_train)
pred_train = pipeline.predict(X_train)
pred_test = pipeline.predict(X_test)
print(classification_report(Y_test, pred_test))
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="Credit scoring classifier", # Optional.
classification_labels=pipeline.classes_.tolist(),
# Their order MUST be identical to the prediction_function's output order.
feature_names=list(COLUMN_TYPES.keys()), # 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)
[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 11:45:25,982 pid:52370 MainThread giskard.datasets.base INFO Casting dataframe columns from {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'} to {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'}
2024-05-29 11:45:25,986 pid:52370 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (32, 22) executed in 0:00:00.014548
Executed 'Precision on data slice β`other_installment_plans` == "bank"β' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x316480910>, 'threshold': 0.7540625}:
Test failed
Metric: 0.6
2024-05-29 11:45:26,003 pid:52370 MainThread giskard.datasets.base INFO Casting dataframe columns from {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'} to {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'}
2024-05-29 11:45:26,006 pid:52370 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (58, 22) executed in 0:00:00.011488
Executed 'Precision on data slice β`account_check_status` == "0 <= ... < 200 DM"β' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3164848e0>, 'threshold': 0.7540625}:
Test failed
Metric: 0.6
2024-05-29 11:45:26,019 pid:52370 MainThread giskard.datasets.base INFO Casting dataframe columns from {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'} to {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'}
2024-05-29 11:45:26,021 pid:52370 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (37, 22) executed in 0:00:00.008733
Executed 'Precision on data slice β`present_employment_since` == "... < 1 year"β' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3164a61a0>, 'threshold': 0.7540625}:
Test failed
Metric: 0.65
2024-05-29 11:45:26,033 pid:52370 MainThread giskard.datasets.base INFO Casting dataframe columns from {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'} to {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'}
2024-05-29 11:45:26,036 pid:52370 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (68, 22) executed in 0:00:00.008518
Executed 'Recall on data slice β`personal_status` == "divorced"β' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3164a5210>, 'threshold': 0.8617857142857143}:
Test failed
Metric: 0.8
2024-05-29 11:45:26,050 pid:52370 MainThread giskard.datasets.base INFO Casting dataframe columns from {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'} to {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'}
2024-05-29 11:45:26,054 pid:52370 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (112, 22) executed in 0:00:00.009998
Executed 'Precision on data slice β`duration_in_month` >= 16.500β' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x31635d9c0>, 'threshold': 0.7540625}:
Test failed
Metric: 0.71
2024-05-29 11:45:26,072 pid:52370 MainThread giskard.datasets.base INFO Casting dataframe columns from {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'} to {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'}
2024-05-29 11:45:26,074 pid:52370 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (69, 22) executed in 0:00:00.012084
Executed 'Precision on data slice β`property` == "if not A121/A122 : car or other, not in attribute 6"β' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3164a4eb0>, 'threshold': 0.7540625}:
Test failed
Metric: 0.72
2024-05-29 11:45:26,087 pid:52370 MainThread giskard.datasets.base INFO Casting dataframe columns from {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'} to {'account_check_status': 'object', 'duration_in_month': 'int64', 'credit_history': 'object', 'purpose': 'object', 'credit_amount': 'int64', 'savings': 'object', 'present_employment_since': 'object', 'installment_as_income_perc': 'int64', 'sex': 'object', 'personal_status': 'object', 'other_debtors': 'object', 'present_residence_since': 'int64', 'property': 'object', 'age': 'int64', 'other_installment_plans': 'object', 'housing': 'object', 'credits_this_bank': 'int64', 'job': 'object', 'people_under_maintenance': 'int64', 'telephone': 'object', 'foreign_worker': 'object'}
2024-05-29 11:45:26,089 pid:52370 MainThread giskard.utils.logging_utils INFO Predicted dataset with shape (54, 22) executed in 0:00:00.009407
Executed 'Precision on data slice β`sex` == "female"β' with arguments {'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3164a51b0>, 'threshold': 0.7540625}:
Test failed
Metric: 0.74
2024-05-29 11:45:26,093 pid:52370 MainThread giskard.core.suite INFO Executed test suite 'My first test suite'
2024-05-29 11:45:26,093 pid:52370 MainThread giskard.core.suite INFO result: failed
2024-05-29 11:45:26,094 pid:52370 MainThread giskard.core.suite INFO Precision on data slice β`other_installment_plans` == "bank"β ({'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x316480910>, 'threshold': 0.7540625}): {failed, metric=0.6}
2024-05-29 11:45:26,094 pid:52370 MainThread giskard.core.suite INFO Precision on data slice β`account_check_status` == "0 <= ... < 200 DM"β ({'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3164848e0>, 'threshold': 0.7540625}): {failed, metric=0.6046511627906976}
2024-05-29 11:45:26,094 pid:52370 MainThread giskard.core.suite INFO Precision on data slice β`present_employment_since` == "... < 1 year"β ({'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3164a61a0>, 'threshold': 0.7540625}): {failed, metric=0.6521739130434783}
2024-05-29 11:45:26,094 pid:52370 MainThread giskard.core.suite INFO Recall on data slice β`personal_status` == "divorced"β ({'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3164a5210>, 'threshold': 0.8617857142857143}): {failed, metric=0.8048780487804879}
2024-05-29 11:45:26,095 pid:52370 MainThread giskard.core.suite INFO Precision on data slice β`duration_in_month` >= 16.500β ({'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x31635d9c0>, 'threshold': 0.7540625}): {failed, metric=0.7125}
2024-05-29 11:45:26,095 pid:52370 MainThread giskard.core.suite INFO Precision on data slice β`property` == "if not A121/A122 : car or other, not in attribute 6"β ({'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3164a4eb0>, 'threshold': 0.7540625}): {failed, metric=0.7192982456140351}
2024-05-29 11:45:26,095 pid:52370 MainThread giskard.core.suite INFO Precision on data slice β`sex` == "female"β ({'model': <giskard.models.sklearn.SKLearnModel object at 0x15f6913c0>, 'dataset': <giskard.datasets.base.Dataset object at 0x15e4d30d0>, 'slicing_function': <giskard.slicing.slice.QueryBasedSliceFunction object at 0x3164a51b0>, 'threshold': 0.7540625}): {failed, metric=0.7368421052631579}
[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()