ミメシスを用いたバランス型データセットによるモデルバイアスの監査
この記事は、Mimesis ライブラリを用いて人口統計学的に偏ったデータセットを生成し、性別などの属性が融資承認アルゴリズムに与える影響を検証する手動ガイドを提供している。
キーポイント
モデルバイアス監査の必要性と手法
歴史的な訓練データに含まれる偏見が、高度な機械学習モデルにも silently(静かに)継承されるリスクを指摘し、実データを保護しつつバイアスを検出する手法として「反事実的(counterfactual)」なテストデータの生成を提案している。
Mimesis ライブラリによる合成データ生成
オープンソースライブラリの Mimesis を使用して、金融背景は同一だが性別などの人口統計学的属性が異なる「架空のユーザー」を大量に生成し、モデルの公平性をテストするプロセスを解説している。
シミュレーションされたバイアス付きデータセット
男性には寛容に、女性には高収入でなければ承認しないという意図的なバイアスを組み込んだ 1,000 件の架空の銀行顧客データを生成し、決定木分類器を訓練する具体的なコード例を示している。
反事実的テストの作成
Mimesisライブラリを使用して、収入と申請IDは同一だが性別のみが異なる(男性/女性)対照的なサンプルペアを生成し、モデルのバイアスを検出する。
決定木モデルによる訓練
過去の承認データに基づき、男性は一律承認、女性は高収入の場合のみ承認とするルールで決定木モデルを訓練し、性別による差別化を検証する。
Mimesisによる対照的データの生成
Mimesisライブラリを用いて、収入などの他の変数を同一に保ちつつ性別のみを変えた「クローン」データを即座に作成し、統計的な完全な制御を実現した。
モデルのバイアス検出
同じ申請者IDと収入を持つ男女のペアを比較した結果、男性は融資承認される一方で女性は却下されるという明確な性別による差別が存在することが判明した。
重要な引用
algorithms might silently adopt prejudices inherent in the historical training dataset they were trained on
how can we audit whether a model is biased without compromising real-world information?
generate a perfectly balanced, counterfactual dataset
test 'fake' users with identical financial backgrounds but different demographic characteristics
"any difference in how our trained decision tree model treats them will undoubtedly be proof of gender bias."
"For each pair of test customers, their application ID and income will be totally identical, so the only difference will be the gender"
影響分析・編集コメントを表示
影響分析
本記事は、AI の公平性(Fairness)と説明可能性(Explainability)が求められる現代において、開発者が実環境へのリスクを負わずにモデルのバイアスを検証するための具体的な実践手法を提供しています。特に、規制対応や倫理的審査を迫られる現場において、Mimesis などのツールを活用したシミュレーションアプローチは、迅速かつ安全な品質保証プロセスとして重要な役割を果たすでしょう。
編集コメント
実データを用いた監査が難しい場合でも、Mimesis を活用したシミュレーションはバイアス検出の第一歩として非常に有効です。ただし、合成データの質と現実世界の複雑さのギャップを理解した上で結果を解釈する必要があります。
image**
# イントロダクション
確立された分類器であっても、大規模言語モデル(LLM: Large Language Models)のような最先端の大規模モデルであっても、機械学習ソリューションを構築する際には常にリスクが伴います。つまり、アルゴリズムがトレーニングに使用した歴史的なトレーニングデータに含まれる偏見を静かに受け継いでしまう可能性があります。しかし、リスクの高いシナリオや、データが機密情報を扱う場合において、現実世界の情報を侵害することなくモデルにバイアスがあるかどうかを検証するにはどうすればよいのでしょうか?
この実践的な記事では、偏ったデータを用いて「ローン承認」のための単純な分類モデルをトレーニングする方法を解説します。これを基盤として、完璧にバランスの取れた*反実仮想*(counterfactual)データを生成するのに役立つオープンソースライブラリであるMimesis を使用します。これにより、金融背景は同一でありながら人口統計学的特性が異なる「架空」のユーザーをテストし、モデルが特定のグループに対して差別を行っているかどうかを判断することが可能になります。
# ステップバイステップガイド
**
Mimesis ライブラリの使用方法に不慣れな場合や、Colab などのクラウドノートブック環境で作業している場合は、まず同ライブラリをインストールすることから始めます:
pip install mimesis
モデルを監査する前に、実際にはまずそのモデルを取得する必要があります。この例では、1,000 人の銀行顧客からなるデータセットを合成生成し、特徴量は性別と収入の 2 つのみとします。これらの特徴量は、それぞれカテゴリカル変数および数値変数です。データ作成は意図的に操作され、性別属性がバイナリアウトカム(ローン承認)に不公平に影響を与えるように設定されます。具体的には、データセットのラベル付けにおいて、男性は一般的に承認される一方、女性は収入が非常に高い場合にのみ承認されるというシナリオを想定します。
この明らかに偏ったデータセットを作成し、その上で決定木分類器(Decision Tree Classifier)を訓練するプロセスは以下の通りです:
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier
1. 偏った履歴データのシミュレーション(1000 インスタンス)
np.random.seed(42)
n_train = 1000
genders = np.random.choice(['Male', 'Female'], n_train)
incomes = np.random.randint(30000, 120000, n_train)
approvals = []
for gender, income in zip(genders, incomes):
if gender == 'Male':
# 歴史的に、男性は承認される
approvals.append(1)
else:
# 収入が高い女性のみが承認される
approvals.append(1 if income > 80000 else 0)
train_df = pd.DataFrame({'Gender': genders, 'Income': incomes, 'Approved': approvals})
マシンラーニングモデルのためにカテゴリを数値に変換する
train_df['Gender_Code'] = train_df['Gender'].map({'Male': 1, 'Female': 0})
2. 決定木分類器のトレーニング
model = DecisionTreeClassifier(max_depth=3)
model.fit(train_df[['Gender_Code', 'Income']], train_df['Approved'])
次のステップでは、Mimesis の動作を確認します。このライブラリを使用して、Generic クラスを用いて少数のテスト対象者を生成します。これには、ランダムな UUID(ユニバーサル・ユニーク・識別子)と 40,000 から 70,000 の間の適度な所得を含む 3 つの基本的な財務プロファイル定義を行います。なお、これらのプロファイルにはまだ性別情報は含まれていません:
from mimesis import Generic
generic = Generic('en')
3 つの基本的な財務プロファイルを生成する
base_profiles = []
for _ in range(3):
profile = {
'Applicant_ID': generic.cryptographic.uuid(),
'Income': generic.random.randint(40000, 70000) # 適度な所得
}
base_profiles.append(profile)
例えば、新しく作成された 3 つのプロファイルは以下のようなものになる可能性があります:
[{'Applicant_ID': '1f1721e1-19af-4bd1-8488-6abf01404ef9', 'Income': 44815},
{'Applicant_ID': '5c862597-7f55-43f4-9d6e-ac9cc0b9083e', 'Income': 47436},
{'Applicant_ID': '3479d4cf-0d9b-4f06-9c43-1c3b7e787830', 'Income': 58194}]
反事実的な例のセット、つまり監査プロセスの中核を構築する作業を完了しましょう!3 つの基本プロファイルそれぞれに対して、2 つのクローンされた反事実的インスタンスを作成します。1 つは男性、もう 1 つは女性です。各テスト顧客ペアについて、申請 ID と収入は完全に同一であり、唯一の違いは性別のみとなります。したがって、訓練済みの決定木モデルがこれらをどのように扱うかに違いが生じる場合、それは間違いなく性差別的バイアスの証拠となります。
counterfactual_data = []
for profile in base_profiles:
# バージョン A: 男性用反事実的データ
counterfactual_data.append({
'Applicant_ID': profile['Applicant_ID'],
'Gender': 'Male',
'Gender_Code': 1,
'Income': profile['Income']
})
# バージョン B: 女性用反事実的データ
counterfactual_data.append({
'Applicant_ID': profile['Applicant_ID'],
'Gender': 'Female',
'Gender_Code': 0,
'Income': profile['Income']
})
audit_df = pd.DataFrame(counterfactual_data)
これが、3 つの顧客ペアがどのようなものになるかの例です:
1f1721e1-19af-4bd1-8488-6abf01404ef9 Male 1 44815
1 1f1721e1-19af-4bd1-8488-6abf01404ef9 Female 0 44815
2 5c862597-7f55-43f4-9d6e-ac9cc0b9083e Male 1 47436
3 5c862597-7f55-43f4-9d6e-ac9cc0b9083e Female 0 47436
4 3479d4cf-0d9b-4f06-9c43-1c3b7e787830 Male 1 58194
5 3479d4cf-0d9b-4f06-9c43-1c3b7e787830 Female 0 58194
ここで強調すべき重要な点があります:私たちは Mimesis を使用して、同じ収入を持ち性別のみが異なる loan applicants の「クローン」を瞬時に完璧に作成しました。これは、保護属性を分離し、完全な統計的制御を提供するライブラリの価値を浮き彫りにしています。
さて、モデルを検証し、何が明らかになるかを確認する時です。
反事実的なケースに対する承認予測をモデルに要求する
audit_df['Predicted_Approval'] = model.predict(audit_df[['Gender_Code', 'Income']])
可読性のために出力を整形(1 = 承認, 0 = 拒否)
audit_df['Predicted_Approval'] = audit_df['Predicted_Approval'].map({1: 'Approved', 0: 'Denied'})
print("\n--- Model Audit Results ---")
print(audit_df[['Applicant_ID', 'Gender', 'Income', 'Predicted_Approval']].sort_values('Applicant_ID'))
モデルが導き出した意思決定の結果はこれ以上明確なことはありません:
--- Model Audit Results ---
Applicant_ID Gender Income Predicted_Approval
0 1f1721e1-19af-4bd1-8488-6abf01404ef9 Male 44815 Approved
1 1f1721e1-19af-4bd1-8488-6abf01404ef9 Female 44815 Denied
4 3479d4cf-0d9b-4f06-9c43-1c3b7e787830 Male 58194 Approved
5 3479d4cf-0d9b-4f06-9c43-1c3b7e787830 Female 58194 Denied
2 5c862597-7f55-43f4-9d6e-ac9cc0b9083e Male 47436 Approved
3 5c862597-7f55-43f4-9d6e-ac9cc0b9083e Female 47436 Denied
同じ Applicant_ID と Income のケースにおいて、男性のクローンではローンの承認が行われる一方で、同程度の収入を持つ女性のクローンでは一般的に拒否されるという点にご注意ください。プロファイルに基づいて使用した Mimesis の機能により、他のすべての変数を一定に保つことができたため、モデルの差別的な意思決定を効果的に特定し、明らかにすることができました。
# まとめ
**
本の実践的な記事を通じて、Mimesis がプライバシーや機密データに関する制約なしに、バランスの取れた反事実的(counterfactual)なデータ例を生成する方法と、それがモデルの行動監査や、モデルが偏った振る舞いをしているかどうかを特定する手助けとなる方法を示しました。もしモデルにバイアスがある場合、次に取るべきステップとしては以下が含まれます:
- 歴史的な歪みやバイアスを修正するために、よりバランスの取れたプロファイルでトレーニングデータを拡張する。
- モデルの種類に応じて、モデルのリウェイト(re-weighting)戦略を使用する。
- バイアス緩和に役立つオープンソースツールキット(例えば AI Fairness 360 など)を活用し、機械学習パイプラインにおけるバイアス軽減を図る。
Iván Palomares Carrascosa は、AI、機械学習、ディープラーニング、LLM に関するリーダー、作家、スピーカー、そしてアドバイザーです。彼は現実世界で AI を活用する方法を他者に指導・訓練しています。
原文を表示

**
# Introduction
Whether they are well-established classifiers or state-of-the-art massive models like large language models (LLMs), building machine learning solutions often entails a risk: algorithms might silently adopt prejudices inherent in the historical training dataset they were trained on. But in a high-stakes scenario or one where data is sensitive, how can we audit whether a model is biased** without compromising real-world information?
This hands-on article guides you in training a simple classification model for "loan approval" on biased data. Based on this, we will use Mimesis, an open-source library that can help generate a perfectly balanced, *counterfactual* dataset. You'll be able to test "fake" users with identical financial backgrounds but different demographic characteristics, thereby determining whether the model discriminates against certain groups or not.
# Step-by-Step Guide
**
Start by installing the Mimesis library if you are new to using it, or you are working on a cloud notebook environment like Colab:
pip install mimesisBefore auditing a model, we actually need to get one! In this example, we will synthetically generate a dataset of 1,000 bank customers, with just two features: gender and income. These features are categorical and numerical, respectively. The data creation will be intentionally manipulated so that the gender attribute unfairly influences the binary outcome: loan approval. Specifically, for labeling the dataset, we will consider a scenario in which men are generally approved, whereas women are only approved when they have remarkably high income.
The process to create this clearly biased dataset and train a decision tree classifier on it is shown below:
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier
# 1. Simulating biased historical data (1000 instances)
np.random.seed(42)
n_train = 1000
genders = np.random.choice(['Male', 'Female'], n_train)
incomes = np.random.randint(30000, 120000, n_train)
approvals = []
for gender, income in zip(genders, incomes):
if gender == 'Male':
# Historically, males are approved
approvals.append(1)
else:
# Only females with high income are approved
approvals.append(1 if income > 80000 else 0)
train_df = pd.DataFrame({'Gender': genders, 'Income': incomes, 'Approved': approvals})
# Converting categories to numbers for the machine learning model
train_df['Gender_Code'] = train_df['Gender'].map({'Male': 1, 'Female': 0})
# 2. Training a Decision Tree classifier
model = DecisionTreeClassifier(max_depth=3)
model.fit(train_df[['Gender_Code', 'Income']], train_df['Approved'])The next step shows Mimesis in action. We will use this library to generate a small set of test subjects using the Generic class. This will be done by defining three base financial profiles that contain random UUIDs (universally unique identifiers) and a moderate income ranging between 40K and 70K. Notice that these profiles will not have gender information incorporated yet:
from mimesis import Generic
generic = Generic('en')
# Generating 3 base financial profiles
base_profiles = []
for _ in range(3):
profile = {
'Applicant_ID': generic.cryptographic.uuid(),
'Income': generic.random.randint(40000, 70000) # Moderate income
}
base_profiles.append(profile)For example, the three newly created profiles may look something like:
[{'Applicant_ID': '1f1721e1-19af-4bd1-8488-6abf01404ef9', 'Income': 44815},
{'Applicant_ID': '5c862597-7f55-43f4-9d6e-ac9cc0b9083e', 'Income': 47436},
{'Applicant_ID': '3479d4cf-0d9b-4f06-9c43-1c3b7e787830', 'Income': 58194}]Let's finish building our counterfactual set of examples, which constitutes the core of our auditing process! For each of the three base profiles, we will create two cloned counterfactual instances: one being male and the other being female. For each pair of test customers, their application ID and income will be totally identical, so the only difference will be the gender: any difference in how our trained decision tree model treats them will undoubtedly be proof of gender bias.
counterfactual_data = []
for profile in base_profiles:
# Version A: Male Counterfactual
counterfactual_data.append({
'Applicant_ID': profile['Applicant_ID'],
'Gender': 'Male',
'Gender_Code': 1,
'Income': profile['Income']
})
# Version B: Female Counterfactual
counterfactual_data.append({
'Applicant_ID': profile['Applicant_ID'],
'Gender': 'Female',
'Gender_Code': 0,
'Income': profile['Income']
})
audit_df = pd.DataFrame(counterfactual_data)This is what the three pairs of customers may look like:
1f1721e1-19af-4bd1-8488-6abf01404ef9 Male 1 44815
1 1f1721e1-19af-4bd1-8488-6abf01404ef9 Female 0 44815
2 5c862597-7f55-43f4-9d6e-ac9cc0b9083e Male 1 47436
3 5c862597-7f55-43f4-9d6e-ac9cc0b9083e Female 0 47436
4 3479d4cf-0d9b-4f06-9c43-1c3b7e787830 Male 1 58194
5 3479d4cf-0d9b-4f06-9c43-1c3b7e787830 Female 0 58194A key point to insist on here:** we have just used Mimesis to instantly build perfectly matched "clones" of loan applicants with identical income but different genders. This underlines the library's value in providing total statistical control, isolating a protected attribute.
Now it's time to probe the model and see what it reveals.
# Asking the model to predict approval for our counterfactuals
audit_df['Predicted_Approval'] = model.predict(audit_df[['Gender_Code', 'Income']])
# Formatting the output for readability (1 = Approved, 0 = Denied)
audit_df['Predicted_Approval'] = audit_df['Predicted_Approval'].map({1: 'Approved', 0: 'Denied'})
print("\n--- Model Audit Results ---")
print(audit_df[['Applicant_ID', 'Gender', 'Income', 'Predicted_Approval']].sort_values('Applicant_ID'))The decision-making results yielded by our model could not be clearer:
--- Model Audit Results ---
Applicant_ID Gender Income Predicted_Approval
0 1f1721e1-19af-4bd1-8488-6abf01404ef9 Male 44815 Approved
1 1f1721e1-19af-4bd1-8488-6abf01404ef9 Female 44815 Denied
4 3479d4cf-0d9b-4f06-9c43-1c3b7e787830 Male 58194 Approved
5 3479d4cf-0d9b-4f06-9c43-1c3b7e787830 Female 58194 Denied
2 5c862597-7f55-43f4-9d6e-ac9cc0b9083e Male 47436 Approved
3 5c862597-7f55-43f4-9d6e-ac9cc0b9083e Female 47436 DeniedNotice that for the exact same Applicant_ID and Income, male clones are approved for the loan. Meanwhile, female clones with such moderate income are generally denied. The Mimesis functionalities we used based on profiles helped us hold all other variables constant, thereby successfully isolating and exposing the model's discriminatory decision-making.
# Wrapping Up
**
Throughout this hands-on article, we have shown how Mimesis can be used to generate balanced, counterfactual data examples — without privacy or sensitive data constraints — that can help audit a model's behavior and identify whether the model is behaving in a biased manner or not. Next steps to take if your model is biased may include:
- Augmenting your training data with more balanced profiles to correct historical skewness or bias.
- Depending on the model type, using model re-weighting strategies.
- Utilizing open-source toolkits for fairness — for instance, AI Fairness 360 — which are helpful for bias mitigation in machine learning pipelines.
Iván Palomares Carrascosa** is a leader, writer, speaker, and adviser in AI, machine learning, deep learning & LLMs. He trains and guides others in harnessing AI in the real world.
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み