/
plot_toy_datasets.py
274 lines (251 loc) · 6.67 KB
/
plot_toy_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
# <codecell>
import os.path
import yaml
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import datasets
sns.set_style('whitegrid')
from imblearn.under_sampling import RandomUnderSampler
from imblearn.over_sampling import SMOTE
from imblearn.over_sampling import KMeansSMOTE
from sklearn.cluster import KMeans
with open("config.yml", 'r') as ymlfile:
cfg = yaml.load(ymlfile)
output_path = os.path.join(cfg['results_dir'], 'toy_datasets')
if not os.path.exists(output_path):
os.mkdir(output_path)
# <codecell>
def plot_before_after_oversampling(
X, y, oversampler, dataset_name='',
additional_text_after_oversampling=None,
colors=['black', '#C1131D', '#527D37'],
markers=['o', 'x', '+'], markersize=[20,30,50]):
"""
Plot dataset, perform oversampling and plot again.
"""
oversampler_name, oversampler = oversampler
X, y = np.asarray(X), np.asarray(y)
# plot original data
for label in np.unique(y):
plt.scatter(
x=X[(y == label), 0],
y=X[(y == label), 1],
c=colors[label],
marker=markers[label],
linewidths= 0 if markers[label] == 'o' else None,
s=markersize[label]
)
ax = plt.gca()
ax.set_xlabel('x')
ax.set_ylabel('y')
# ax.set_title('Dataset {}'.format(dataset_name))
plt.savefig(
os.path.join(
output_path,
'{} before.png'.format(dataset_name).replace(' ', '_')
),
bbox_inches="tight"
)
try:
__IPYTHON__
plt.show()
except:
plt.close()
# oversample data
X_ovs, y_ovs = oversampler.fit_sample(X, y)
# plot oversampled data
new_samples = np.where(np.isin(X_ovs, X, invert=True).all(axis=1))
y_ovs[new_samples] = 2
for label in np.unique(y_ovs):
plt.scatter(
x=X_ovs[(y_ovs == label), 0],
y=X_ovs[(y_ovs == label), 1],
c=colors[label],
marker=markers[label],
linewidths=0 if markers[label] == 'o' else None,
s=markersize[label]
)
ax = plt.gca()
ax.set_title(oversampler_name)
ax.set_xlabel('x')
ax.set_ylabel('y')
if additional_text_after_oversampling is not None:
ax.text(
ax.get_xlim()[1] - (ax.get_xlim()[1] / 50),
ax.get_ylim()[1] - (ax.get_ylim()[1] / 50),
additional_text_after_oversampling,
horizontalalignment='right',
verticalalignment='top',
)
plt.savefig(
os.path.join(
output_path,
'{} {}.png'.format(dataset_name,oversampler_name).replace(' ', '_')
),
bbox_inches="tight"
)
try:
__IPYTHON__
plt.show()
except:
plt.close()
# <markdowncell>
# # Dataset A
# <codecell>
dataset_a = pd.read_csv(os.path.join(cfg['dataset_dir'], 'a.csv'), header=None)
# <markdowncell>
# ## Oversampling with SMOTE
# <codecell>
np.random.seed(1)
plot_before_after_oversampling(
dataset_a.iloc[:, 0:2],
dataset_a.iloc[:, 2],
('SMOTE', SMOTE()),
'A'
)
# <markdowncell>
# ## Oversampling with k-means SMOTE
# <codecell>
np.random.seed(1)
plot_before_after_oversampling(
dataset_a.iloc[:, 0:2],
dataset_a.iloc[:, 2],
('k-means SMOTE', KMeansSMOTE(
kmeans_estimator=KMeans(n_clusters=6),
cluster_balance_threshold=1.0,
density_exponent=circles_X.shape[1],
k_neighbors=5
)),
'A',
additional_text_after_oversampling='k = 6'
)
# <markdowncell>
# # Dataset B
# <codecell>
dataset_b = pd.read_csv(os.path.join(cfg['dataset_dir'], 'b.csv'), header=None)
# <markdowncell>
# ## Oversampling with SMOTE
# <codecell>
np.random.seed(1)
plot_before_after_oversampling(
dataset_b.iloc[:, 0:2],
dataset_b.iloc[:, 2],
('SMOTE', SMOTE()),
'B'
)
# <markdowncell>
# ## Oversampling with k-means SMOTE
# <codecell>
np.random.seed(1)
plot_before_after_oversampling(
dataset_b.iloc[:, 0:2],
dataset_b.iloc[:, 2],
('k-means SMOTE', KMeansSMOTE(
kmeans_estimator=KMeans(n_clusters=3),
cluster_balance_threshold=1.0,
density_exponent=circles_X.shape[1],
k_neighbors=5
)),
'B',
additional_text_after_oversampling='k = 3'
)
# <markdowncell>
# # Dataset C
# <codecell>
dataset_c = pd.read_csv(os.path.join(cfg['dataset_dir'], 'c.csv'), header=None)
# <markdowncell>
# ## Oversampling with SMOTE
# <codecell>
np.random.seed(1)
plot_before_after_oversampling(
dataset_c.iloc[:, 0:2],
dataset_c.iloc[:, 2],
('SMOTE', SMOTE()),
'C'
)
# <markdowncell>
# ## Oversampling with k-means SMOTE
# <codecell>
np.random.seed(1)
plot_before_after_oversampling(
dataset_c.iloc[:, 0:2],
dataset_c.iloc[:, 2],
('k-means SMOTE', KMeansSMOTE(
kmeans_estimator=KMeans(n_clusters=3),
cluster_balance_threshold=1.0,
density_exponent=circles_X.shape[1],
k_neighbors=5
)),
'C',
additional_text_after_oversampling='k = 3'
)
# <markdowncell>
# # Dataset Moons
# <codecell>
n_samples = 1500
moons_dataset = datasets.make_moons(n_samples=n_samples, noise=.3)
undersampler = RandomUnderSampler(ratio={0: 200, 1: 750})
moons_X, moons_y = undersampler.fit_sample(moons_dataset[0], moons_dataset[1])
# <markdowncell>
# ## Oversampling with SMOTE
# <codecell>
np.random.seed(1)
plot_before_after_oversampling(
moons_X,
moons_y,
('SMOTE', SMOTE()),
'Moons'
)
# <markdowncell>
# ## Oversampling with k-means SMOTE
# <codecell>
np.random.seed(1)
plot_before_after_oversampling(
moons_X,
moons_y,
('k-means SMOTE', KMeansSMOTE(
kmeans_estimator=KMeans(n_clusters=50),
cluster_balance_threshold=1.0,
density_exponent=circles_X.shape[1],
k_neighbors=5
)),
'Moons',
additional_text_after_oversampling='k = 5'
)
# <markdowncell>
# # Dataset Circles
# <codecell>
n_samples = 1500
circles_dataset = datasets.make_circles(
n_samples=n_samples, factor=.5, noise=.3)
undersampler = RandomUnderSampler(ratio={0: 300, 1: 750})
circles_X, circles_y = undersampler.fit_sample(
circles_dataset[0], circles_dataset[1])
# <markdowncell>
# ## Oversampling with SMOTE
# <codecell>
np.random.seed(1)
plot_before_after_oversampling(
circles_X,
circles_y,
('SMOTE', SMOTE()),
'Circles'
)
# <markdowncell>
# ## Oversampling with k-means SMOTE
# <codecell>
np.random.seed(2)
plot_before_after_oversampling(
circles_X,
circles_y,
('k-means SMOTE', KMeansSMOTE(
kmeans_estimator=KMeans(n_clusters=50),
cluster_balance_threshold=1.0,
density_exponent=circles_X.shape[1],
k_neighbors=5
)),
'Circles',
additional_text_after_oversampling='k = 50'
)