forked from tkamishima/kamfadm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfai_bin_bin.py
executable file
·279 lines (220 loc) · 7.83 KB
/
fai_bin_bin.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/usr/bin/env python
"""
Compute various types of fairness-aware indexes.
SYNOPSIS::
SCRIPT [options] [<INPUT> [<OUTPUT>]]
Description
===========
Input
-----
Both a class and a sensitive attribute are assumed to be binary. As default,
the first, the second, and the third columns indicate a correct class, an
estimated class, and a sensitive attribute.
Output
------
1. Counts of contingency table
2. Marginal counts of contingency table elements
3. Accuracy
4. Mutual Information with natural log
5. Contingency table with sensitive attribute:
6. Mutual Information between correct classes and sensitive attributes.
(natural log)
7. Mutual Information between estimated classes and sensitive attributes.
(natural log)
8. KL-divergence between correct and estimated conditional distributions given
sensitive attributes.
9. Hellinger distance between correct and estimated distributions jointed with
distributions given sensitive attributes
10. Caldars-Verwer score.
Options
=======
-i <INPUT>, --in <INPUT>
Specify <INPUT> file name. if this option is not specified and non-optional
argument is specified, the first argument is used as input file name
(default sys.stdin)
-o <OUTPUT>, --out <OUTPUT>
Specify <OUTPUT> file name (default sys.stdout)
-c <CORRECT>, --correct <CORRECT>
The column number for the data of the correct class, starting from 1
(default 1)
-e <ESTIMATED>, --estimated <ESTIMATED>
The column number for the data of the estimated class, starting from 1
(default 2)
-s <SENSITIVE>, --sensitive <SENSITIVE>
The column number for the data of the sensitive attribute class, starting
from 1 (default 3)
-d <DL>, --delimiter <DL>
Column delimiter string. 't' specifies TAB character.(default " ")
-g <IGNORE>, --ignore <IGNORE>
Ignore line if the line start with char included in this string
(default "#")
-r, --raw
simply separated with the specified delimiter
-n, --negate
As default, a value 1 indicates a positive class. If specified, this
meaning is negated.
"""
# ==============================================================================
# Module metadata variables
# ==============================================================================
__author__ = "Toshihiro Kamishima ( http://www.kamishima.net/ )"
__date__ = "2012/08/26"
__version__ = "2.0.0"
__copyright__ = "Copyright (c) 2012 Toshihiro Kamishima all rights reserved."
__license__ = "MIT License: http://www.opensource.org/licenses/mit-license.php"
__docformat__ = "restructuredtext en"
# ==============================================================================
# Imports
# ==============================================================================
import sys
import argparse
import numpy as np
# private modeules -------------------------------------------------------------
import site
site.addsitedir(".")
from fadm.eval import BinClassBinSensitiveStats
# ==============================================================================
# Public symbols
# ==============================================================================
__all__ = []
# ==============================================================================
# Constants
# ==============================================================================
# ==============================================================================
# Module variables
# ==============================================================================
# ==============================================================================
# Classes
# ==============================================================================
# ==============================================================================
# Functions
# ==============================================================================
def read_01_file(opt):
"""read data from file
Parameters
----------
opt : option
parsed options
Returns
-------
n : array, shape=(2, 2, 2), dtype=int
array: (s,1,1)=TP, (s,1,0)=FN, (s,0,1)=FP, (s,0,0)=TN, where s= 0 or 1
"""
# init stats
n = np.zeros((2, 2, 2))
# read from file
line_no = 0
for line in opt.infile.readlines():
line = line.rstrip("\r\n")
line_no += 1
# skip empty line
if line == "":
continue
# test top char if this line is comment
t = line[0]
if opt.ignore.find(t) < 0:
f = line.split(opt.dl)
try:
s = int(f[opt.sensitive])
c = int(f[opt.correct])
e = int(f[opt.estimated])
n[s, c, e] += 1 # count up
except IndexError:
sys.exit("Parse error in line %d" % line_no)
return n
# ==============================================================================
# Main routine
# ==============================================================================
def main(opt) -> None:
"""Main routine that exits with status code 0"""
### main process
# read file
ct = read_01_file(opt)
fai = BinClassBinSensitiveStats(ct)
# check negation
if opt.negate:
fai.negate()
# output results
if opt.format:
print(fai.str_all(), file=opt.outfile)
else:
print(opt.dl.join(map(str, fai.all())), file=opt.outfile)
### post process
# close file
if opt.infile is not sys.stdin:
opt.infile.close()
if opt.outfile is not sys.stdout:
opt.outfile.close()
sys.exit(0)
### Check if this is call as command script
if __name__ == "__main__":
### set script name
script_name = sys.argv[0].split("/")[-1]
### command-line option parsing
ap = argparse.ArgumentParser(
description="pydoc is useful for learning the details."
)
# common options
ap.add_argument("--version", action="version", version="%(prog)s " + __version__)
# basic file i/o
ap.add_argument(
"-i", "--in", dest="infile", default=None, type=argparse.FileType("r")
)
ap.add_argument(
"infilep",
nargs="?",
metavar="INFILE",
default=sys.stdin,
type=argparse.FileType("r"),
)
ap.add_argument(
"-o", "--out", dest="outfile", default=None, type=argparse.FileType("w")
)
ap.add_argument(
"outfilep",
nargs="?",
metavar="OUTFILE",
default=sys.stdout,
type=argparse.FileType("w"),
)
# script specific options
ap.add_argument("-c", "--correct", type=int, default=1)
ap.add_argument("-e", "--estimated", type=int, default=2)
ap.add_argument("-s", "--sensitive", type=int, default=3)
ap.add_argument("-d", "--dlimiter", type=str, dest="dl", default=" ")
ap.add_argument("-g", "--ignore", type=str, default="#")
ap.set_defaults(format=True)
ap.add_argument("-r", "--raw", dest="format", action="store_false")
ap.set_defaults(negate=False)
ap.add_argument("-n", "--negate", dest="negate", action="store_true")
# parsing
opt = ap.parse_args()
### post-processing for command-line options
# basic file i/o
if opt.infile is None:
opt.infile = opt.infilep
del vars(opt)["infilep"]
if opt.outfile is None:
opt.outfile = opt.outfilep
del vars(opt)["outfilep"]
# set meta-data of script and machine
opt.script_name = script_name
opt.script_version = __version__
# the specified delimiter is TAB?
if opt.dl == "t" or opt.dl == "T":
opt.dl = "\t"
# check columns
if (
opt.correct <= 0
or opt.estimated <= 0
or opt.sensitive <= 0
or opt.correct == opt.estimated
or opt.correct == opt.sensitive
or opt.estimated == opt.sensitive
):
sys.exit("Incorrect specification of data columns")
opt.estimated -= 1
opt.correct -= 1
opt.sensitive -= 1
### call main routine
main(opt)