-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathimbalance_degree.py
254 lines (222 loc) · 8.07 KB
/
imbalance_degree.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
#!/usr/bin/env python
# Copyright (C) 2019 Mario Juez-Gil <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Aknowledgements
# ---------------
# This work was partially supported by the Consejería de Educación of the
# Junta de Castilla y León and by the European Social Fund with the
# EDU/1100/2017 pre-doctoral grants; by the project TIN2015-67534-P
# (MINECO/FEDER, UE) of the Ministerio de Economía Competitividad of the
# Spanish Government and the project BU085P17 (JCyL/FEDER, UE) of the Junta de
# Castilla y León both cofinanced from European Union FEDER funds.
import numpy as np
from math import sqrt, log
__author__ = "Mario Juez-Gil"
__copyright__ = "Copyright 2019, Mario Juez-Gil"
__credits__ = ["Mario Juez-Gil", "Álvar Arnaiz-González",
"Cesar Garcia-Osorio", "Carlos López-Nozal",
"Juan J. Rodriguez"]
__license__ = "GPLv3"
__version__ = "1.0"
__maintainer__ = "Mario Juez-Gil"
def imbalance_degree(classes, distance="EU"):
"""
Calculates the imbalance degree [1] of a multi-class dataset.
This metric is an alternative for the well known imbalance ratio, which
is only suitable for binary classification problems.
Parameters
----------
classes : list of int.
List of classes (targets) of each instance of the dataset.
distance : string (default: EU).
distance or similarity function identifier. It can take the following
values:
- EU: Euclidean distance.
- CH: Chebyshev distance.
- KL: Kullback Leibler divergence.
- HE: Hellinger distance.
- TV: Total variation distance.
- CS: Chi-square divergence.
References
----------
.. [1] J. Ortigosa-Hernández, I. Inza, and J. A. Lozano,
“Measuring the class-imbalance extent of multi-class problems,”
Pattern Recognit. Lett., 2017.
"""
def _eu(_d, _e):
"""
Euclidean distance from empirical distribution
to equiprobability distribution.
Parameters
----------
_d : list of float.
Empirical distribution of class probabilities.
_e : float.
Equiprobability term (1/K, where K is the number of classes).
Returns
-------
distance value.
"""
summ = np.vectorize(lambda p : pow(p - _e, 2))(_d).sum()
return sqrt(summ)
def _ch(_d, _e):
"""
Chebyshev distance from empirical distribution
to equiprobability distribution.
Parameters
----------
_d : list of float.
Empirical distribution of class probabilities.
_e : float.
Equiprobability term (1/K, where K is the number of classes).
Returns
-------
distance value.
"""
dif = np.vectorize(lambda p : abs(p - _e))(_d)
return dif.max()
def _kl(_d, _e):
"""
Kullback Leibler divergence from empirical distribution
to equiprobability distribution.
Parameters
----------
_d : list of float.
Empirical distribution of class probabilities.
_e : float.
Equiprobability term (1/K, where K is the number of classes).
Returns
-------
distance value.
"""
kl = lambda p : 0.0 if p == 0 else p * log(p/_e)
return np.vectorize(kl)(_d).sum()
def _he(_d, _e):
"""
Hellinger distance from empirical distribution
to equiprobability distribution.
Parameters
----------
_d : list of float.
Empirical distribution of class probabilities.
_e : float.
Equiprobability term (1/K, where K is the number of classes).
Returns
-------
distance value.
"""
summ = np.vectorize(lambda p : pow((sqrt(p) - sqrt(_e)), 2))(_d).sum()
return (1 / sqrt(2)) * sqrt(summ)
def _tv(_d, _e):
"""
Total variation distance from empirical distribution
to equiprobability distribution.
Parameters
----------
_d : list of float.
Empirical distribution of class probabilities.
_e : float.
Equiprobability term (1/K, where K is the number of classes).
Returns
-------
distance value.
"""
summ = np.vectorize(lambda p : abs(p - _e))(_d).sum()
return (1 / 2) * summ
def _cs(_d, _e):
"""
Chi-square divergence from empirical distribution
to equiprobability distribution.
Parameters
----------
_d : list of float.
Empirical distribution of class probabilities.
_e : float.
Equiprobability term (1/K, where K is the number of classes).
Returns
-------
distance value.
"""
summ = np.vectorize(lambda p : pow((p - _e), 2) / _e)(_d).sum()
return summ
def _min_classes(_d, _e):
"""
Calculates the number of minority classes. We call minority class to
those classes with a probability lower than the equiprobability term.
Parameters
----------
_d : list of float.
Empirical distribution of class probabilities.
_e : float.
Equiprobability term (1/K, where K is the number of classes).
Returns
-------
Number of minority clases.
"""
return len(_d[_d < _e])
def _i_m(_K, _m):
"""
Calculates the distribution showing exactly m minority classes with the
highest distance to the equiprobability term. This distribution is
always the same for all distance functions proposed, and is explained
in [1].
Parameters
----------
_K : int.
The number of classes (targets).
_m : int.
The number of minority classes. We call minority class to
those classes with a probability lower than the equiprobability
term.
Returns
-------
A list with the i_m distribution.
"""
min_i = np.zeros(_m)
maj_i = np.ones((_K - _m - 1)) * (1 / _K)
maj = np.array([1 - (_K - _m - 1) / _K])
return np.concatenate((min_i, maj_i, maj)).tolist()
def _dist_fn():
"""
Selects the distance function according to the distance paramenter.
Returns
-------
A distance function.
"""
if distance == "EU":
return _eu
elif distance == "CH":
return _ch
elif distance == "KL":
return _kl
elif distance == "HE":
return _he
elif distance == "TV":
return _tv
elif distance == "CS":
return _cs
else:
raise ValueError("Bad distance function parameter. " + \
"Should be one in EU, CH, KL, HE, TV, or CS")
_, class_counts = np.unique(classes, return_counts=True)
empirical_distribution = class_counts / class_counts.sum()
K = len(class_counts)
e = 1 / K
m = _min_classes(empirical_distribution, e)
i_m = _i_m(K, m)
dfn = _dist_fn()
dist_ed = dfn(empirical_distribution, e)
return 0.0 if dist_ed == 00 else (dist_ed / dfn(i_m, e)) + (m - 1)