-
Notifications
You must be signed in to change notification settings - Fork 2
/
metrics.py
102 lines (83 loc) · 2.73 KB
/
metrics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
"""
Code for FTU and DP metrics was provided by the DECAF authors as part of our
email correspondence with them.
"""
import numpy as np
import pandas as pd
from sklearn.metrics import precision_score, recall_score, roc_auc_score
from sklearn.neural_network import MLPClassifier
columns_adult = [
"age",
"workclass",
"fnlwgt",
"education",
"education-num",
"marital-status",
"occupation",
"relationship",
"race",
"sex",
"capital-gain",
"capital-loss",
"hours-per-week",
"native-country",
"income",
]
columns_credit = [
"male",
"age",
"debt",
"married",
"bankcustomer",
"educationlevel",
"ethnicity",
"yearsemployed",
"priordefault",
"employed",
"creditscore",
"driverslicense",
"citizen",
"zip",
"income",
"approved",
]
def DP(mlp, X_test, dataset="adult"):
"""Calculate fairness metric DP"""
columns = columns_adult if dataset == "adult" else columns_credit
X_test_df = pd.DataFrame(X_test, columns=columns[:-1])
if 'ethnicity' in X_test_df:
X_test_0 = X_test_df[X_test_df["ethnicity"] < 0.5]
X_test_1 = X_test_df[X_test_df["ethnicity"] > 0.5]
else:
X_test_0 = X_test_df[X_test_df["sex"] < 0.5]
X_test_1 = X_test_df[X_test_df["sex"] > 0.5]
dp = abs(np.mean(mlp.predict(X_test_0)) - np.mean(mlp.predict(X_test_1)))
return dp
def FTU(mlp, X_test, dataset="adult"):
"""Calculate fairness metric FTU"""
columns = columns_adult if dataset == "adult" else columns_credit
X_test_df = pd.DataFrame(X_test, columns=columns[:-1])
if 'ethnicity' in X_test_df:
X_test_0 = X_test_df.assign(ethnicity=0)
X_test_1 = X_test_df.assign(ethnicity=1)
else:
X_test_0 = X_test_df.assign(sex=0)
X_test_1 = X_test_df.assign(sex=1)
ftu = abs(np.mean(mlp.predict(X_test_0)) - np.mean(mlp.predict(X_test_1)))
return ftu
def eval_model(dataset_train, dataset_test):
"""Helper function that prints evaluation metrics."""
dataset = 'credit' if 'approved' in dataset_train.columns else 'adult'
label_col = 'approved' if 'approved' in dataset_train.columns else 'income'
X_train, y_train = dataset_train.drop(columns=[label_col]), dataset_train[label_col]
X_test, y_test = dataset_test.drop(columns=[label_col]), dataset_test[label_col]
clf = MLPClassifier()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
auroc = roc_auc_score(y_test, y_pred)
dp = DP(clf, X_test, dataset=dataset)
ftu = FTU(clf, X_test, dataset=dataset)
return {'precision': precision, 'recall': recall, 'auroc': auroc,
'dp': dp, 'ftu': ftu}