-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprocess_datasets.py
276 lines (240 loc) · 10.2 KB
/
preprocess_datasets.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
import torch
import numpy as np
import pandas as pd
import argparse
from sklearn.model_selection import train_test_split
#Pipelines
from utils import apply_preprocessing, train_preprocessing
#Debugging
import ipdb
#TODO: add the preprocess_datasetes.py from the FUFDP project. There are more datasets.
DIR_DATA = {
'census_income':'datasets/census_income/',
'compas': 'datasets/compas/',
'dutch_census': 'datasets/dutch_census/',
'german_data': 'datasets/german_data/'
}
DIR_DATA_TRAIN = {
'census_income':'adult.data',
'compas': 'compas.csv',
'dutch_census': 'dutch_census.csv',
'german_data': 'german_data.csv'
}
DIR_DATA_TEST = {
'census_income':'adult.test',
'compas': None,
'dutch_census': None,
'german_data': None
}
FEATURES = {
'census_income': ['age',
'workclass',
'education',
'education-num',
'marital-status',
'occupation',
'relationship',
'race',
'sex',
'capital-gain',
'capital-loss',
'hours-per-week',
'native-country'],
'compas': ['sex',
'age',
'age_cat',
'race',
'juv_fel_count',
'juv_misd_count',
'juv_other_count',
'priors_count',
'c_days_jail',
'c_charge_degree'],
'dutch_census': ['sex',
'age',
'household_position',
'household_size',
'prev_residence_place',
'citizenship',
'country_birth',
'edu_level',
'economic_status',
'cur_eco_activity',
'Marital_status'],
'german_data': ['status_existing_check_account',
'duration_month',
'credit_history',
'purpose',
'credit_amount',
'saving_account_bonds',
'present_employe_since',
'installment_rate',
'personal_status_sex',
'sex',
'other_debtors',
'present_residence_since',
'property',
'age_years',
'other_installment',
'housing',
'num_existing_credits',
'job',
'num_people_liable',
'telephone',
'foreign_worker']
}
NOMINAL = {
'census_income': ['workclass',
'education',
'marital-status',
'occupation',
'relationship',
'race',
'native-country'],
'compas': ['age_cat',
'sex',
'race',
'c_charge_degree'],
'dutch_census': ['sex',
'age',
'household_position',
'household_size',
'prev_residence_place',
'citizenship',
'country_birth',
'edu_level',
'economic_status',
'cur_eco_activity',
'Marital_status'],
'german_data': ['status_existing_check_account',
'credit_history',
'purpose',
'saving_account_bonds',
'present_employe_since',
'personal_status_sex',
'sex',
'other_debtors',
'property',
'other_installment',
'housing',
'job',
'telephone',
'foreign_worker']
}
#The first is the name of the attribute, and the second is the groups
#The list of the groups should start with the protected group.
SENSITIVE_ATTRIBUTE = {
'census_income': {'sex': ['Female', 'Male']},
'compas': {'race': ['African-American', 'Caucasian', 'Hispanic', 'Native American', 'Other']},
'dutch_census': {'sex': ['Female', 'Male']},
'german_data': {'sex': ['A01', 'A02']} #TODO: add the age after binarization young/old <=25/>25.
}
LABEL = {
'census_income': {'income': ['>50K', '<=50K']},
'compas': {'two_year_recid': [1, 0], 'is_recid': [1, 0]},
'dutch_census': {'occupation': ['high_level', 'low-level']},
'german_data': {'class': [1, 2]}
}
DEFAULT_SENSITIVE_ATTRIBUTE= {
'census_income': 'sex',
'compas': 'race',
'dutch_census': 'sex',
'german_data': 'sex' #TODO: add the age after binarization young/old <=25/>25.
}
DEFAULT_LABEL = {
'census_income': 'income',
'compas': 'two_year_recid',
'dutch_census': 'occupation',
'german_data': 'class'
}
def preprocess_datasets(args):
'''
Preprocess the datasets and save them in the datasets/ folder
Output:
- X_train: sparse matrix, representing the features
- S_train: numpy, representing the sensitive attribute. Assuming binary
- Y_train: numpy, representing the label.
'''
# Load the data
if None in [DIR_DATA_TEST[args.dataset], DIR_DATA_TRAIN[args.dataset]]:
df = pd.read_csv(DIR_DATA[args.dataset]+DIR_DATA_TRAIN[args.dataset])
df_train, df_test = train_test_split(df, test_size=args.test_size)
else:
df_train = pd.read_csv(DIR_DATA[args.dataset]+DIR_DATA_TRAIN[args.dataset])
df_test = pd.read_csv(DIR_DATA[args.dataset]+DIR_DATA_TEST[args.dataset])
#We are assuming binary target variable and sensitive attribute. For sensitive attribute, the first is the group 1 and the rest the 0.
#TODO: handle multi-class in target and sensitive attribute
features = FEATURES[args.dataset]
features.remove(args.sensitive_attribute)
# Retrieve variables
Y_train = df_train.loc[:, [args.target_variable]].to_numpy().flatten()
Y_train = 1*(Y_train == LABEL[args.dataset][args.target_variable][0])
S_train = df_train.loc[:, [args.sensitive_attribute]].to_numpy().flatten()
S_train = 1*(S_train == SENSITIVE_ATTRIBUTE[args.dataset][args.sensitive_attribute][0])
X_train = df_train.loc[:, features]
Y_test = df_test.loc[:, [args.target_variable]].to_numpy().flatten()
Y_test = 1*(Y_test == LABEL[args.dataset][args.target_variable][0])
S_test = df_test.loc[:, [args.sensitive_attribute]].to_numpy().flatten()
S_test = 1*(S_test == SENSITIVE_ATTRIBUTE[args.dataset][args.sensitive_attribute][0])
X_test = df_test.loc[:, features]
# Get nominal names of features and remove the sensitive attribute
nominal_names = NOMINAL[args.dataset]
if args.sensitive_attribute in nominal_names: nominal_names.remove(args.sensitive_attribute)
# Get id_numerical
id_numerical = [i
for i, f in enumerate(X_train.columns)
if f not in nominal_names]
# Encode the categorical features
(outcome) = train_preprocessing(X_train,
idnumerical=id_numerical,
imputation=args.not_imputation,
encode=args.nominal_encode,
standardscale=args.standardscale,
normalize = args.normalize)
X_train, pipe_num, pipe_nom, pipe_normalize, numerical_features, nominal_features = outcome
X_test = apply_preprocessing(X_test,
pipe_nom,
pipe_num,
pipe_normalize,
idnumerical=id_numerical)
torch.save({
'train': (X_train, S_train, Y_train),
'test': (X_test, S_test, Y_test),
'pipes': (pipe_nom, pipe_num),
'features': (numerical_features, nominal_features),
}, DIR_DATA[args.dataset]+args.dataset+'.pt')
if __name__=='__main__':
'''
Preprocess the datasets and save them in the datasets/ folder
Output:
- X_train: sparse matrix, representing the features
- S_train: numpy, representing the sensitive attribute. Assuming binary
- Y_train: numpy, representing the label.
Example:
python preprocess.py --dataset census_income --test_size 0.3 --sensitive_attribute sex
'''
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', type=str, default='census_income', help='Dataset to preprocess')
parser.add_argument('--test_size', type=float, default=0.3, help='Size of test if is not defined')
parser.add_argument('--sensitive_attribute', type=str, default='sex', help='features used as sensitive attribute')
parser.add_argument('--target_variable', type=str, default='income', help='target variable')
parser.add_argument('--nominal_encode', type=str, default='label', help='Type of encoding for nominal features')
parser.add_argument('--standardscale', action="store_true", help='Apply standard scale transformation')
parser.add_argument('--normalize', action="store_true", help='Apply normalization transformation')
parser.add_argument('--not_imputation', action="store_false", help='Set false to not apply imputation on missing values')
#TODO: use the following two parameters to handle multi-class targets and sensitive attributes
parser.add_argument('--target_multi_class', action='store_true', help='target variable as multi-class')
parser.add_argument('--sa_multi_class', action='store_true', help='sensitive attribute as multi-class')
args = parser.parse_args()
if args.dataset == 'all':
for ds in DIR_DATA.keys():
args.dataset = ds
args.sensitive_attribute = DEFAULT_SENSITIVE_ATTRIBUTE[ds]
args.target_variable = DEFAULT_LABEL[ds]
print(f'Preprocessing {args.dataset} dataset...')
preprocess_datasets(args)
print('Done!')
else:
print(f'Preprocessing {args.dataset} dataset...')
preprocess_datasets(args)
print('Done!')