-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathporto_seguro_keras_under_sampling.py
258 lines (197 loc) · 8.55 KB
/
porto_seguro_keras_under_sampling.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
"""
==========================================================
Porto Seguro: balancing samples in mini-batches with Keras
==========================================================
This example compares two strategies to train a neural-network on the Porto
Seguro Kaggle data set [1]_. The data set is imbalanced and we show that
balancing each mini-batch allows to improve performance and reduce the training
time.
References
----------
.. [1] https://www.kaggle.com/c/porto-seguro-safe-driver-prediction/data
"""
# Authors: Guillaume Lemaitre <[email protected]>
# License: MIT
print(__doc__)
###############################################################################
# Data loading
###############################################################################
from collections import Counter
import numpy as np
import pandas as pd
###############################################################################
# First, you should download the Porto Seguro data set from Kaggle. See the
# link in the introduction.
training_data = pd.read_csv("./input/train.csv")
testing_data = pd.read_csv("./input/test.csv")
y_train = training_data[["id", "target"]].set_index("id")
X_train = training_data.drop(["target"], axis=1).set_index("id")
X_test = testing_data.set_index("id")
###############################################################################
# The data set is imbalanced and it will have an effect on the fitting.
print(f"The data set is imbalanced: {Counter(y_train['target'])}")
###############################################################################
# Define the pre-processing pipeline
###############################################################################
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler
def convert_float64(X):
return X.astype(np.float64)
###############################################################################
# We want to standard scale the numerical features while we want to one-hot
# encode the categorical features. In this regard, we make use of the
# :class:`~sklearn.compose.ColumnTransformer`.
numerical_columns = [
name for name in X_train.columns if "_calc_" in name and "_bin" not in name
]
numerical_pipeline = make_pipeline(
FunctionTransformer(func=convert_float64, validate=False), StandardScaler()
)
categorical_columns = [name for name in X_train.columns if "_cat" in name]
categorical_pipeline = make_pipeline(
SimpleImputer(missing_values=-1, strategy="most_frequent"),
OneHotEncoder(categories="auto"),
)
preprocessor = ColumnTransformer(
[
("numerical_preprocessing", numerical_pipeline, numerical_columns),
(
"categorical_preprocessing",
categorical_pipeline,
categorical_columns,
),
],
remainder="drop",
)
# Create an environment variable to avoid using the GPU. This can be changed.
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from tensorflow.keras.layers import Activation, BatchNormalization, Dense, Dropout
###############################################################################
# Create a neural-network
###############################################################################
from tensorflow.keras.models import Sequential
def make_model(n_features):
model = Sequential()
model.add(Dense(200, input_shape=(n_features,), kernel_initializer="glorot_normal"))
model.add(BatchNormalization())
model.add(Activation("relu"))
model.add(Dropout(0.5))
model.add(Dense(100, kernel_initializer="glorot_normal", use_bias=False))
model.add(BatchNormalization())
model.add(Activation("relu"))
model.add(Dropout(0.25))
model.add(Dense(50, kernel_initializer="glorot_normal", use_bias=False))
model.add(BatchNormalization())
model.add(Activation("relu"))
model.add(Dropout(0.15))
model.add(Dense(25, kernel_initializer="glorot_normal", use_bias=False))
model.add(BatchNormalization())
model.add(Activation("relu"))
model.add(Dropout(0.1))
model.add(Dense(1, activation="sigmoid"))
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])
return model
###############################################################################
# We create a decorator to report the computation time
import time
from functools import wraps
def timeit(f):
@wraps(f)
def wrapper(*args, **kwds):
start_time = time.time()
result = f(*args, **kwds)
elapsed_time = time.time() - start_time
print(f"Elapsed computation time: {elapsed_time:.3f} secs")
return (elapsed_time, result)
return wrapper
###############################################################################
# The first model will be trained using the ``fit`` method and with imbalanced
# mini-batches.
import tensorflow
from sklearn.metrics import roc_auc_score
from sklearn.utils.fixes import parse_version
tf_version = parse_version(tensorflow.__version__)
@timeit
def fit_predict_imbalanced_model(X_train, y_train, X_test, y_test):
model = make_model(X_train.shape[1])
model.fit(X_train, y_train, epochs=2, verbose=1, batch_size=1000)
if tf_version < parse_version("2.6"):
# predict_proba was removed in tensorflow 2.6
predict_method = "predict_proba"
else:
predict_method = "predict"
y_pred = getattr(model, predict_method)(X_test, batch_size=1000)
return roc_auc_score(y_test, y_pred)
###############################################################################
# In the contrary, we will use imbalanced-learn to create a generator of
# mini-batches which will yield balanced mini-batches.
from imblearn.keras import BalancedBatchGenerator
@timeit
def fit_predict_balanced_model(X_train, y_train, X_test, y_test):
model = make_model(X_train.shape[1])
training_generator = BalancedBatchGenerator(
X_train, y_train, batch_size=1000, random_state=42
)
model.fit(training_generator, epochs=5, verbose=1)
y_pred = model.predict(X_test, batch_size=1000)
return roc_auc_score(y_test, y_pred)
###############################################################################
# Classification loop
###############################################################################
###############################################################################
# We will perform a 10-fold cross-validation and train the neural-network with
# the two different strategies previously presented.
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=10)
cv_results_imbalanced = []
cv_time_imbalanced = []
cv_results_balanced = []
cv_time_balanced = []
for train_idx, valid_idx in skf.split(X_train, y_train):
X_local_train = preprocessor.fit_transform(X_train.iloc[train_idx])
y_local_train = y_train.iloc[train_idx].values.ravel()
X_local_test = preprocessor.transform(X_train.iloc[valid_idx])
y_local_test = y_train.iloc[valid_idx].values.ravel()
elapsed_time, roc_auc = fit_predict_imbalanced_model(
X_local_train, y_local_train, X_local_test, y_local_test
)
cv_time_imbalanced.append(elapsed_time)
cv_results_imbalanced.append(roc_auc)
elapsed_time, roc_auc = fit_predict_balanced_model(
X_local_train, y_local_train, X_local_test, y_local_test
)
cv_time_balanced.append(elapsed_time)
cv_results_balanced.append(roc_auc)
###############################################################################
# Plot of the results and computation time
###############################################################################
df_results = pd.DataFrame(
{
"Balanced model": cv_results_balanced,
"Imbalanced model": cv_results_imbalanced,
}
)
df_results = df_results.unstack().reset_index()
df_time = pd.DataFrame(
{"Balanced model": cv_time_balanced, "Imbalanced model": cv_time_imbalanced}
)
df_time = df_time.unstack().reset_index()
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure()
sns.boxplot(y="level_0", x=0, data=df_time)
sns.despine(top=True, right=True, left=True)
plt.xlabel("time [s]")
plt.ylabel("")
plt.title("Computation time difference using a random under-sampling")
plt.figure()
sns.boxplot(y="level_0", x=0, data=df_results, whis=10.0)
sns.despine(top=True, right=True, left=True)
ax = plt.gca()
ax.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, pos: "%i%%" % (100 * x)))
plt.xlabel("ROC-AUC")
plt.ylabel("")
plt.title("Difference in terms of ROC-AUC using a random under-sampling")