Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cpd4.0/notebooks/python_sdk/experiments/autoai/fairness/Bias detection and mitigation in AutoAI.ipynb
6397 views
Kernel: Python 3 (ipykernel)

Bias detection and mitigation in AutoAI

This notebook contains the steps and code to demonstrate support of AutoAI experiments with bias detection/mitigation in Watson Machine Learning service. It introduces commands for data retrieval, training experiments, persisting pipelines, testing pipelines and scoring.

Some familiarity with Python is helpful. This notebook uses Python 3.9.

Learning goals

The learning goals of this notebook are:

  • Work with Watson Machine Learning experiments to train AutoAI models.

  • Compare trained models quality and select the best one for further refinement.

  • Investigate models fairness.

  • Online deployment and score the trained model.

Contents

This notebook contains the following parts:

  1. Setup

  2. Optimizer definition

  3. Experiment with bias detection run

  4. Experiment with bias mitigation run

  5. Deploy and Score

  6. Clean up

  7. Summary and next steps

1. Set up the environment

Before you use the sample code in this notebook, you must perform the following setup tasks:

  • Contact with your Cloud Pack for Data administrator and ask him for your account credentials

Connection to WML

Authenticate the Watson Machine Learning service on IBM Cloud Pack for Data. You need to provide platform url, your username and api_key.

username = 'PASTE YOUR USERNAME HERE' api_key = 'PASTE YOUR API_KEY HERE' url = 'PASTE THE PLATFORM URL HERE'
wml_credentials = { "username": username, "apikey": api_key, "url": url, "instance_id": 'openshift', "version": '4.0' }

Alternatively you can use username and password to authenticate WML services.

wml_credentials = { "username": ***, "password": ***, "url": ***, "instance_id": 'openshift', "version": '4.0' }

Install and import the ibm-watson-machine-learning package

Note: ibm-watson-machine-learning documentation can be found here.

!pip install -U ibm-watson-machine-learning !pip install -U lale | tail -n 1 !pip install -U autoai-libs | tail -n 1 !pip install -U scikit-learn==1.0.2 | tail -n 1 !pip install wget | tail -n 1
from ibm_watson_machine_learning import APIClient client = APIClient(wml_credentials)

Working with spaces

First of all, you need to create a space that will be used for your work. If you do not have space already created, you can use {PLATFORM_URL}/ml-runtime/spaces?context=icp4data to create one.

  • Click New Deployment Space

  • Create an empty space

  • Go to space Settings tab

  • Copy space_id and paste it below

Tip: You can also use SDK to prepare the space for your work. More information can be found here.

Action: Assign space ID below

space_id = 'PASTE YOUR SPACE ID HERE'

You can use the list method to print all existing spaces.

client.spaces.list(limit=10)

To be able to interact with all resources available in Watson Machine Learning, you need to set the space which you will be using.

client.set.default_space(space_id)
'SUCCESS'

Optimizer definition

Training data connection

This example uses the German Credit Risk dataset.

The dataset can be downloaded from here.

filename = 'german_credit_data_biased_training.csv'

Download training data from git repository and create data assets.

import wget import os url = "https://github.com/IBM/watson-machine-learning-samples/raw/master/cpd4.0/data/bias/german_credit_data_biased_training.csv" if not os.path.isfile(filename): wget.download(url) asset_details = client.data_assets.create(name=filename, file_path=filename)
Creating data asset... SUCCESS
from ibm_watson_machine_learning.helpers import DataConnection, AssetLocation credit_risk_conn = DataConnection( location=AssetLocation(asset_id=client.data_assets.get_id(asset_details)) ) training_data_reference=[credit_risk_conn]
import pandas as pd pd.read_csv(filename).head()

Bias detection: optimizer configuration

Provide input information for AutoAI optimizer:

  • name - experiment name

  • prediction_type - type of the problem

  • prediction_column - target column name

  • scoring - optimization metric

Define fairness_info:

  • protected_attribute_names (array of items : string) – Subset of feature names for which fairness is desired.

  • favorable_labels (array of union) – Label values which are considered favorable (i.e. “positive”). Available types string Literal value number Numerical value array of number, >= 2 items, <= 2 items Numeric range [a,b] from a to b inclusive.

fairness_info = { "protected_attributes": [ {"feature": "Sex", "privileged_groups": ['male']}, {"feature": "Age", "privileged_groups": [[20,40], [60,90]]} ], "favorable_labels": ["No Risk"]}
from ibm_watson_machine_learning.experiment import AutoAI experiment = AutoAI(wml_credentials, space_id=space_id) pipeline_optimizer = experiment.optimizer( name='Credit Risk Prediction and bias detection - AutoAI', prediction_type=AutoAI.PredictionType.BINARY, prediction_column='Risk', scoring=AutoAI.Metrics.ACCURACY_SCORE, fairness_info=fairness_info, max_number_of_estimators=4 )

Configuration parameters can be retrieved via get_params().

pipeline_optimizer.get_params()
{'name': 'Credit Risk Prediction and bias detection - AutoAI', 'desc': '', 'prediction_type': 'binary', 'prediction_column': 'Risk', 'scoring': 'accuracy', 'test_size': 0.1, 'max_num_daub_ensembles': 4, 't_shirt_size': 'm', 'train_sample_rows_test_size': None, 'daub_include_only_estimators': None, 'cognito_transform_names': None, 'data_join_graph': False, 'csv_separator': ',', 'excel_sheet': 0, 'encoding': 'utf-8', 'positive_label': None, 'drop_duplicates': True, 'run_id': None}

Experiment run

Call the fit() method to trigger the AutoAI experiment. You can either use interactive mode (synchronous job) or background mode (asychronous job) by specifying background_model=True.

run_details = pipeline_optimizer.fit( training_data_reference=training_data_reference, background_mode=False)
Node automl: __init__() got an unexpected keyword argument 'fairness_info': 3%| | [00:22<08:56, 5

You can use the get_run_status() method to monitor AutoAI jobs in background mode.

pipeline_optimizer.get_run_status()
'failed'

Get experiment training_id.

training_id = run_details['metadata']['id']

Get selected pipeline model

Download and reconstruct a scikit-learn pipeline model object from the AutoAI training job.

pipeline_optimizer.summary()
best_pipeline = pipeline_optimizer.get_pipeline()

Visualize pipeline

best_pipeline.visualize()

Each node in the visualization is a machine-learning operator (transformer or estimator). Each edge indicates data flow (transformed output from one operator becomes input to the next). The input to the root nodes is the initial dataset and the output from the sink node is the final prediction. When you hover the mouse pointer over a node, a tooltip shows you the configuration arguments of the corresponding operator (tuned hyperparameters). When you click on the hyperlink of a node, it brings you to a documentation page for the operator.

Reading training data

train_df = pipeline_optimizer.get_data_connections()[0].read() train_X = train_df.drop(['Risk'], axis=1).values train_y = train_df.Risk.values

Test pipeline model locally

predicted_y = best_pipeline.predict(train_X) predicted_y[:5]

Define fairness_info for disparate_impact scorer.

fairness_info_lale = { "protected_attributes": [ {"feature": train_df.columns.get_loc("Sex"), "privileged_groups": ['male']}, {"feature": train_df.columns.get_loc("Age"), "privileged_groups": [[20,40], [60,90]]} ], "favorable_labels": ["No Risk"]}
from lale.lib.aif360 import disparate_impact from sklearn.metrics import accuracy_score disparate_impact_scorer = disparate_impact(**fairness_info_lale) print("Accuracy: ", accuracy_score(y_true= train_y, y_pred=predicted_y)) print("Disparate impact: ", disparate_impact_scorer(best_pipeline, train_X, train_y))

Bias mitigation: optimizer configuration

Provide input information for AutoAI optimizer:

  • name - experiment name

  • prediction_type - type of the problem

  • prediction_column - target column name

  • scoring - optimization metric

Define fairness_info:

  • protected_attribute_names (array of items : string) – Subset of feature names for which fairness is desired.

  • favorable_labels (array of union) – Label values which are considered favorable (i.e. “positive”). Available types string Literal value number Numerical value array of number, >= 2 items, <= 2 items Numeric range [a,b] from a to b inclusive.

fairness_info_mitigation = { "protected_attributes": [ {"feature": "Sex", "privileged_groups": ['male']} ], "favorable_labels": ["No Risk"]}
experiment_mitigation = AutoAI(wml_credentials, space_id=space_id) pipeline_optimizer_mitigation = experiment_mitigation.optimizer( name='Credit Risk Prediction and bias mitigation - AutoAI', prediction_type=AutoAI.PredictionType.BINARY, prediction_column='Risk', scoring="accuracy_and_disparate_impact", fairness_info=fairness_info_mitigation, max_number_of_estimators = 4 )

Configuration parameters can be retrieved via get_params().

pipeline_optimizer_mitigation.get_params()

Experiment run

Call the fit() method to trigger the AutoAI experiment. You can either use interactive mode (synchronous job) or background mode (asychronous job) by specifying background_model=True.

run_details_mitigation = pipeline_optimizer_mitigation.fit( training_data_reference=training_data_reference, background_mode=False)

You can use the get_run_status() method to monitor AutoAI jobs in background mode.

pipeline_optimizer_mitigation.get_run_status()

Get selected pipeline model

Download and reconstruct a scikit-learn pipeline model object from the AutoAI training job.

pipeline_optimizer_mitigation.summary()
best_pipeline_mitigation = pipeline_optimizer_mitigation.get_pipeline()

Visualize pipeline

best_pipeline_mitigation.visualize()

Reading training data

train_df = pipeline_optimizer_mitigation.get_data_connections()[0].read() train_X = train_df.drop(['Risk'], axis=1).values train_y = train_df.Risk.values

Test pipeline model locally

predicted_y = best_pipeline_mitigation.predict(train_X) predicted_y[:5]

Define fairness_info for disparate_impact and accuracy_and_disparate_impact scorers.

fairness_info_mitigation_lale = { "protected_attributes": [ {"feature": train_df.columns.get_loc("Sex"), "privileged_groups": ['male']} ], "favorable_labels": ["No Risk"]}
from lale.lib.aif360 import disparate_impact, accuracy_and_disparate_impact from sklearn.metrics import accuracy_score disparate_impact_scorer = disparate_impact(**fairness_info_mitigation_lale) accuracy_and_disparate_impact_scorer = accuracy_and_disparate_impact(**fairness_info_mitigation_lale) print("Accuracy: ", accuracy_score(y_true= train_y, y_pred=predicted_y)) print("Accuracy and disparate impact: ", accuracy_and_disparate_impact_scorer(best_pipeline, train_X, train_y)) print("Disparate impact: ", disparate_impact_scorer(best_pipeline, train_X, train_y))

Deploy and Score

In this section you will learn how to deploy and score pipeline model as webservice using WML instance.

pipeline_name = "Pipeline_1"

Deployment creation

from ibm_watson_machine_learning.deployment import WebService service = WebService(wml_credentials, source_space_id=space_id) service.create( experiment_run_id=training_id, model=pipeline_name, deployment_name="Credit Risk Deployment AutoAI - bias detection")

Deployment object could be printed to show basic information:

print(service)

To show all available information about deployment use .get_params() method:

service.get_params()

Scoring of webservice

You can make scoring request by calling score() on deployed pipeline.

predictions = service.score(payload=train_df.drop(['Risk'], axis=1).iloc[:10]) predictions

If you want to work with the webservice in external Python application you can retrieve the service object by:

  • initialize service by service = WebService(wml_credentials)

  • get deployment_id by service.list() method

  • get webservice object by service.get('deployment_id') method

After that you can call service.score() method.

Deleting deployment

You can delete exeiting deployment by calling service.delete() command. To list existing web services you can use service.list().

Clean up

If you want to clean up all created assets:

  • experiments

  • trainings

  • pipelines

  • model definitions

  • models

  • functions

  • deployments

please follow up this sample notebook.

Summary and next steps

You successfully completed this notebook!.

You learned how to use watson-machine-learning-client to run AutoAI experiments.

Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.

Authors

Dorota Dydo-Rożniecka, Intern in Watson Machine Learning at IBM.

Szymon Kucharczyk, Software Engineer in Watson Machine Learning at IBM.

Copyright © 2021-2025 IBM. This notebook and its source code are released under the terms of the MIT License.