-
Notifications
You must be signed in to change notification settings - Fork 2
/
data.py
185 lines (134 loc) · 5.08 KB
/
data.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
import ipdb
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from abc import abstractmethod
class Dataset():
def __init__(self, fold):
#fold \in {0,1,2,3,4}
self.fold = fold
def load_data(self,fname, sep=","):
df = pd.read_csv(fname, sep=sep)
df = df.sample(frac=1,random_state=1)
return df
def get_feat_types(self, df):
cat_feat = []
num_feat = []
for key in list(df):
if df[key].dtype==object:
cat_feat.append(key)
elif len(set(df[key]))>2:
num_feat.append(key)
return cat_feat,num_feat
def scale_num_feats(self, df1, df2, num_feat):
#scale numerical features
for key in num_feat:
scaler = StandardScaler()
df1[key] = scaler.fit_transform(df1[key].values.reshape(-1,1))
df2[key] = scaler.transform(df2[key].values.reshape(-1,1))
return df1, df2
def split_data(self, X, y):
x_chunks = []
y_chunks = []
for i in range(5):
start = int(i/5*len(X))
end = int((i+1)/5*len(X))
x_chunks.append(X.iloc[start:end])
y_chunks.append(y.iloc[start:end])
X_test, y_test = x_chunks.pop(self.fold), y_chunks.pop(self.fold)
X_train, y_train = pd.concat(x_chunks), pd.concat(y_chunks)
return X_train, y_train, X_test, y_test
class CorrectionShift(Dataset):
def __init__(self, seed):
super(CorrectionShift, self).__init__(seed)
def get_data(self, fname1, fname2):
df1 = self.load_data(fname1)
df2 = self.load_data(fname2)
#Using a reduced feature space due to causal baseline's SCM
num_feat = ["duration", "amount", "age"]
cat_feat = ["personal_status_sex"]
target = "credit_risk"
df1 = df1.drop(columns=[c for c in list(df1) if c not in num_feat+cat_feat+[target]])
df2 = df2.drop(columns=[c for c in list(df2) if c not in num_feat+cat_feat+[target]])
#Scale numerical features
df1, df2 = self.scale_num_feats(df1, df2, num_feat)
#One-hot encode categorical features
df1 = pd.get_dummies(df1, columns=cat_feat)
df2 = pd.get_dummies(df2, columns=cat_feat)
X1, y1 = df1.drop(columns=[target]), df1[target]
X2, y2 = df2.drop(columns=[target]), df2[target]
data1 = self.split_data(X1, y1)
data2 = self.split_data(X2, y2)
return data1, data2
class TemporalShift(Dataset):
def __init__(self, seed):
super(TemporalShift, self).__init__(seed)
def get_data(self, fname):
df = self.load_data(fname)
df = df.fillna(-1)
#Define target variable
df["NoDefault"] = 1-df["Default"].values
#Drop unique identifiers, constants, feature perfectly correlated
#with outcome, and categorical variables that blow up the
#feature space
df = df.drop(columns=["Selected","State","Name", "BalanceGross", "LowDoc","BankState",
"LoanNr_ChkDgt","MIS_Status","Default", "Bank", "City"])
cat_feat,num_feat = self.get_feat_types(df)
#One-hot encode categorical features
df = pd.get_dummies(df, columns=cat_feat)
#Get df1 and df2
df1 = df[df["ApprovalFY"]<2006]
df2 = df
#Scale numerical features
df1, df2 = self.scale_num_feats(df1, df2, num_feat)
X1, y1 = df1.drop(columns=["NoDefault"]), df1["NoDefault"]
X2, y2 = df2.drop(columns=["NoDefault"]), df2["NoDefault"]
data1 = self.split_data(X1, y1)
data2 = self.split_data(X2, y2)
return data1, data2
class GeospatialShift(Dataset):
def __init__(self, seed):
super(GeospatialShift, self).__init__(seed)
def get_data(self, fname, sep):
df = self.load_data(fname, sep)
#Define target variable
df["Outcome"] = (df["G3"]<10).astype(int)
#Drop variables highly correlated with target
df = df.drop(columns=["G1","G2","G3"])
cat_feat,num_feat = self.get_feat_types(df)
#One-hot encode categorical features
df = pd.get_dummies(df, columns=cat_feat)
#Get df1 and df2
df1 = df[df["school_GP"]==1]
df2 = df
#Scale numerical features
df1, df2 = self.scale_num_feats(df1, df2, num_feat)
X1, y1 = df1.drop(columns=["Outcome","school_GP","school_MS"]), df1["Outcome"]
X2, y2 = df2.drop(columns=["Outcome","school_GP","school_MS"]), df2["Outcome"]
data1 = self.split_data(X1, y1)
data2 = self.split_data(X2, y2)
return data1, data2
class SimulatedData(Dataset):
def __init__(self, seed):
self.c0_means = -2*np.ones(2)
self.c1_means = 2*np.ones(2)
self.c0_cov = 0.5*np.eye(2)
self.c1_cov = 0.5*np.eye(2)
super(SimulatedData, self).__init__(seed)
def get_data(self, num_samples=1000):
np.random.seed(1)
X0 = np.random.multivariate_normal(self.c0_means,self.c0_cov,int(num_samples/2))
X1 = np.random.multivariate_normal(self.c1_means,self.c1_cov,int(num_samples/2))
X = np.vstack(np.array([X0,X1]))
y = np.array([0]*int(num_samples/2)+[1]*int(num_samples/2))
indices = np.arange(num_samples)
np.random.shuffle(indices)
X = X[indices]
y = y[indices]
data = pd.DataFrame({"X0":X[:,0],"X1":X[:,1], "y":y})
X, y = data.drop(columns=["y"]), data["y"]
X_train, y_train, X_test, y_test = self.split_data(X, y)
#return X_train.values, X_test.values, y_train.values, y_test.values
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=self.fold)
return X_train, X_test, y_train, y_test