/
pycm_util.py
343 lines (292 loc) · 9.2 KB
/
pycm_util.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# -*- coding: utf-8 -*-
"""Utility module."""
from __future__ import division
import sys
import numpy
from .pycm_param import *
def list_check_equal(input_list):
"""
Check equality of input_list items.
:param input_list: input list
:type input_list: list
:return: result as bool
"""
return input_list[1:] == input_list[:-1]
def isfloat(value):
"""
Check input for float conversion.
:param value: input value
:type value:str
:return: result as bool (true if input_value is a number and false otherwise)
"""
try:
float(value)
return True
except Exception:
return False
def rounder(input_number, digit=5):
"""
Round input number and convert to str.
:param input_number: input number
:type input_number : anything
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:return: round number as str
"""
if isinstance(input_number, tuple):
tuple_list = list(input_number)
tuple_str = []
for i in tuple_list:
if isfloat(i):
tuple_str.append(str(numpy.around(i, digit)))
else:
tuple_str.append(str(i))
return "(" + ",".join(tuple_str) + ")"
if isfloat(input_number):
return str(numpy.around(input_number, digit))
return str(input_number)
def class_filter(classes, class_name):
"""
Filter classes by comparing two lists.
:param classes: matrix classes
:type classes: list
:param class_name: sub set of classes
:type class_name : list
:return: filtered classes as list
"""
result_classes = classes
if isinstance(class_name, list):
if set(class_name) <= set(classes):
result_classes = class_name
return result_classes
def vector_check(vector):
"""
Check input vector items type.
:param vector: input vector
:type vector : list
:return: bool
"""
for i in vector:
if isinstance(i, int) is False:
return False
if i < 0:
return False
return True
def matrix_check(table):
"""
Check input matrix format.
:param table: input matrix
:type table : dict
:return: bool
"""
try:
if len(table.keys()) == 0:
return False
for i in table.keys():
if table.keys() != table[i].keys() or vector_check(
list(table[i].values())) is False:
return False
return True
except Exception:
return False
def vector_filter(actual_vector, predict_vector):
"""
Convert different type of items in vectors to str.
:param actual_vector: actual values
:type actual_vector : list
:param predict_vector: predict value
:type predict_vector : list
:return: new actual and predict vector
"""
temp = []
temp.extend(actual_vector)
temp.extend(predict_vector)
types = set(map(type, temp))
if len(types) > 1:
return [list(map(str, actual_vector)), list(map(str, predict_vector))]
return [actual_vector, predict_vector]
def class_check(vector):
"""
Check different items in matrix classes.
:param vector: input vector
:type vector : list
:return: bool
"""
for i in vector:
if not isinstance(i, type(vector[0])):
return False
return True
def isfile(f):
"""
Check file object in python 2.7 & 3.x.
:param f: input object
:type f : file object
:return: file type check as boolean
"""
return isinstance(
f, file) if sys.version_info[0] == 2 else hasattr(
f, 'read')
def one_vs_all_func(classes, table, TP, TN, FP, FN, class_name):
"""
One-Vs-All mode handler.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TP: true positive dict for all classes
:type TP : dict
:param TN: true negative dict for all classes
:type TN : dict
:param FP: false positive dict for all classes
:type FP : dict
:param FN: false negative dict for all classes
:type FN : dict
:param class_name : target class name for One-Vs-All mode
:type class_name : any valid type
:return: [classes , table ] as list
"""
try:
report_classes = [str(class_name), "~"]
report_table = {str(class_name): {str(class_name): TP[class_name],
"~": FN[class_name]},
"~": {str(class_name): FP[class_name],
"~": TN[class_name]}}
return [report_classes, report_table]
except Exception:
return [classes, table]
def normalized_table_calc(classes, table):
"""
Return normalized confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: normalized table as dict
"""
map_dict = {k: 0 for k in classes}
new_table = {k: map_dict.copy() for k in classes}
for key in classes:
div = sum(table[key].values())
if div == 0:
div = 1
for item in classes:
new_table[key][item] = numpy.around(table[key][item] / div, 5)
return new_table
def transpose_func(classes, table):
"""
Transpose table.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:return: transposed table as dict
"""
transposed_table = table
for i, item1 in enumerate(classes):
for j, item2 in enumerate(classes):
if i > j:
temp = transposed_table[item1][item2]
transposed_table[item1][item2] = transposed_table[item2][item1]
transposed_table[item2][item1] = temp
return transposed_table
def matrix_params_from_table(table, transpose=False):
"""
Calculate TP,TN,FP,FN from confusion matrix.
:param table: input matrix
:type table : dict
:param transpose : transpose flag
:type transpose : bool
:return: [classes_list,table,TP,TN,FP,FN]
"""
classes = sorted(table.keys())
map_dict = {k: 0 for k in classes}
TP_dict = map_dict.copy()
TN_dict = map_dict.copy()
FP_dict = map_dict.copy()
FN_dict = map_dict.copy()
for i in classes:
TP_dict[i] = table[i][i]
sum_row = sum(list(table[i].values()))
for j in classes:
if j != i:
FN_dict[i] += table[i][j]
FP_dict[j] += table[i][j]
TN_dict[j] += sum_row - table[i][j]
if transpose:
temp = FN_dict
FN_dict = FP_dict
FP_dict = temp
table = transpose_func(classes, table)
return [classes, table, TP_dict, TN_dict, FP_dict, FN_dict]
def matrix_params_calc(actual_vector, predict_vector, sample_weight):
"""
Calculate TP,TN,FP,FN for each class.
:param actual_vector: actual values
:type actual_vector : list
:param predict_vector: predict value
:type predict_vector : list
:param sample_weight : sample weights list
:type sample_weight : list
:return: [classes_list,table,TP,TN,FP,FN]
"""
if isinstance(actual_vector, numpy.ndarray):
actual_vector = actual_vector.tolist()
if isinstance(predict_vector, numpy.ndarray):
predict_vector = predict_vector.tolist()
classes = set(actual_vector).union(set(predict_vector))
classes = sorted(classes)
map_dict = {k: 0 for k in classes}
table = {k: map_dict.copy() for k in classes}
weight_vector = [1] * len(actual_vector)
if isinstance(sample_weight, (list, numpy.ndarray)):
if len(sample_weight) == len(actual_vector):
weight_vector = sample_weight
for index, item in enumerate(actual_vector):
table[item][predict_vector[index]] += 1 * weight_vector[index]
[classes, table, TP_dict, TN_dict, FP_dict,
FN_dict] = matrix_params_from_table(table)
return [classes, table, TP_dict, TN_dict, FP_dict, FN_dict]
def imbalance_check(P):
"""
Check if the dataset is imbalanced.
:param P: condition positive
:type P : dict
:return: is_imbalanced as bool
"""
p_list = list(P.values())
max_value = max(p_list)
min_value = min(p_list)
if min_value > 0:
balance_ratio = max_value / min_value
else:
balance_ratio = max_value
is_imbalanced = False
if balance_ratio > BALANCE_RATIO_THRESHOLD:
is_imbalanced = True
return is_imbalanced
def binary_check(classes):
"""
Check if the problem is a binary classification.
:param classes: all classes name
:type classes : list
:return: is_binary as bool
"""
num_classes = len(classes)
is_binary = False
if num_classes == 2:
is_binary = True
return is_binary
def statistic_recommend(classes, P):
"""
Return recommend parameters which are more suitable due to the input dataset characteristics.
:param classes: all classes name
:type classes : list
:param P: condition positive
:type P : dict
:return: recommendation_list as list
"""
if imbalance_check(P):
return IMBALANCED_RECOMMEND
if binary_check(classes):
return BINARY_RECOMMEND
return MULTICLASS_RECOMMEND