forked from Street93/ml-lecture-2015-project
/
result.py
68 lines (53 loc) · 2.02 KB
/
result.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
from collections import namedtuple
from copy import copy
class ClassificationHistogramBin(namedtuple('ClassificationHistogramBin', \
'truth prediction number')):
def to_jso(self):
return dict(self._asdict())
@staticmethod
def from_jso(jso):
return Bin(**jso)
class ClassificationHistogram(list):
@staticmethod
def from_labels(labels):
B = ClassificationHistogramBin
labels = list(labels)
h = ClassificationHistogram()
for l1 in labels:
for l2 in labels:
h.append(B(truth=l1, prediction=l2, number=0))
return h
def labels(self):
return set((b.truth for b in self))
def to_jso(self):
return [b.to_jso() for b in self]
@staticmethod
def from_jso(jso):
return ClassificationHistogram((ClassificationHistogramBin.from_jso(jsobin) for jsobin in jso))
class ClassificationResult(namedtuple('ClassificationResult', \
'traintime testtime priors histogram')):
def to_jso(self):
self = copy(self)
jso = dict(self._asdict())
jso['histogram'] = self.histogram.to_jso()
return jso
@staticmethod
def from_jso(jso):
jso = copy(jso)
jso['histogram'] = ClassificationHistogram.from_jso(jso['histogram'])
return Classificationresult(jso)
def correctness(self):
accum = 0
for label in self.histogram.labels():
correct_num = next((num for b in histogram if b.truth == label if b.prediction ==label))
total_num = sum((num for b in histogram if b.truth == label))
accum += self.priors[label] * (correct_num / total_num)
return accum
def error(self):
return 1 - self.correctness()
def prior_correctness(self):
return max(self.priors)
def prior_error(self):
return 1 - self.prior_correctness()
def error_quotient_to_prior(self):
return self.error() / self.prior_error()