File size: 16,754 Bytes
eb90a8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
"""
Module for constructing and analysing confusion matrix
of source code classification
Prints confusion report and writes down 
statistics of classification accuracy
"""
import sys
import os
from abc import ABC, abstractmethod
import numpy as np
import csv
import sklearn.metrics as metrics

from ConfusionAnalysis import ConfusionAnalysis

class ClassConfusAnalysis(ConfusionAnalysis):
    """
    Class for constructing and analysing confusion matrix
    """
    def __init__(self, probabilities, labels, solutions, 
                 problems, extreme = 0.1):
        """
        Construct confusion matrix
        Parameters:
        - probabilities - classification probabilities as numpy array
        - labels        - list of samples labels
        - solutions     - list of file names of problem solutions,
                          i.e sample names for this case
        - problems      - list of problems 
                          i.e names of classes for this case
        - extreme       - fraction of cases to be reported 
                          as extreme ones
        """
        super(ClassConfusAnalysis, self).__init__(probabilities, 
            np.asarray(labels, dtype = np.int32), 
            solutions, problems, extreme)
        self.class_stat_fn = "class_statistics.lst"
        self.class_stat_csv = "class_statistics.csv"
        self.confused_classes_fn = "confused_classes.lst"
        self.confused_classes_csv = "confused_classes.csv"
        #Number of best and worst correct predictions of
        #worst classified classes to report
        self.n_right_pred_report = 32
        #Max number of confusions to report
        self.max_n_confus_report = 64
        #Max number of worst and best classes to report mistakes
        self.max_n_class_report = 16
        #Max number of misclassifications to report
        self.max_n_misclass_report = 32
        #Confidence in classification
        self.confidence = np.max(probabilities, axis=1)
        #Number of samples in each class as numpy array
        self._n_class_samples = self.conf_mat.sum(axis=1)
        #Number of predictions of each class as numpy array
        self._n_class_predict = self.conf_mat.sum(axis=0)
        #Number of correct predictions of each class
        self.n_corr_class_samples = np.diag(self.conf_mat)
        #Confusion matrix normalized with number of class samples
        self.norm_conf_mat = \
            self.conf_mat / (self._n_class_samples[:, np.newaxis])
        #Accuracy of class predictions as python list
        self.class_accuracy = \
            np.diag(self.norm_conf_mat).tolist()

    def getPredictions(self):
        """
        Get classification predictions
        Returns:  classification predictions  
        """
        return np.argmax(self.probabilities, axis=1)

    def reportClasses(self, classes, f):
        """
        Report classification of set of classes
        Parameters:
        - classes  -- classes to report
        - f        -- file to write report to
        """
        self.reportClassProblems(self._n_class_samples,
                                 self.n_corr_class_samples,
                                 classes, f)
        self.csvClassProblems(self._n_class_samples,
                                 self.n_corr_class_samples,
                                 classes)

    def csvClassProblems(self, tot_samples, corr_samples, 
                         problems):
        """
        Writes absolute and relative numbers of 
        correct and incorrect classifications of problems 
        to csv file
        Parameters:
        - tot_samples  -- vector of total numbers of samples 
                          corresponding to each problem
        - corr_samples -- vector of numbers of correctly classified samples
        - problems     -- list of indices of problems to report
        """
        with open(f"{self.report_dir}/{self.class_stat_csv}",
                  'w', newline='') as _csv_f:
            _w = csv.writer(_csv_f)
            _w.writerow(("Label",  "Accuracy", "N files", 
                       "N errors", "Problem"))
            for _c in problems:
                _w.writerow((_c, 
                            100.0 * float(corr_samples[_c]) / float(tot_samples[_c]),
                            tot_samples[_c], tot_samples[_c] - corr_samples[_c],
                             self.problems[_c]))

    def reportClassProblems(self, tot_samples, corr_samples, 
                            problems, f):
        """
        Writes absolute and relative numbers of 
        correct and incorrect classifications of problems

        Parameters:
        - tot_samples  -- vector of total numbers of samples 
                          corresponding to each problem
        - corr_samples -- vector of numbers of correctly classified samples
        - problems     -- list of indices of problems to report
        - f            -- file to write to
        """
        f.write("Label  Accur    Size  N errs   Problem name\n")
        for _c in sorted(problems,
            key = lambda _p: float(corr_samples[_p]) / float(tot_samples[_p])):
            f.write("{:4d}  {:5.1f}%   {:5d}   {:5d}   {:s}\n".
                    format(_c, 
                           100.0 * float(corr_samples[_c]) / float(tot_samples[_c]),
                           tot_samples[_c], tot_samples[_c] - corr_samples[_c],
                           self.problems[_c]))

    def getRightClassifications(self, classes):
        """
        Get list of correct classifications of given classes
        Parameters:
        - classes  -- indices of classes to report
        Returns list of lists of pairs, each of which is 
                <index of classified sample, confidence>
                Sublists correspond to given classes
                Each sublist is sorted according to confidence
        """
        _classifications = [[] for i in range(len(classes))]
        for _i in range(self._n_samples):
            if (self.predictions[_i] == self.labels[_i] and
                self.labels[_i] in classes):
                _idx = classes.index(self.labels[_i])
                _classifications[_idx].append((self.solutions[_i],
                                               self.confidence[_i]))
        for _cls in _classifications:
            if len(_cls) < 2: continue
            _cls.sort(key = lambda _c: _c[1], reverse = True)
        return _classifications

    def reportRightClassifications(self, classes, f):
        """
        Report correct classifications  of given classes
        Parameters:
        - classes          -- indices of classes to report
        - f                -- file to write to
        """
        _classifications = self.getRightClassifications(classes)
        for _i, _c in enumerate(sorted(classes, 
                        key = lambda _cl: self.class_accuracy[_cl])):
            if not _classifications[_i]: continue        
            f.write(f"#{_i}  Problem {self.problems[_c]} number {_c} " + 
                    f"is classified with {100.0 *self.class_accuracy[_c]:.2f}% " + 
                    "accuracy\n")
            f.write(f"There are {len(_classifications[_i])} correct classifications\n")
            if len(_classifications[_i]) < 2 * self.n_right_pred_report + 3:
                self.writeClassifications(_classifications[_i],
                                         "Solution predictions", f)
            else:
                self.writeClassifications(
                    _classifications[_i][: self.n_right_pred_report],
                    "Strongest predictions", f)                
                self.writeClassifications(
                    _classifications[_i][-self.n_right_pred_report :],
                    "Weakest predictions", f)
                
    def writeClassifications(self, predictions, title, f):
        """
        Write down information on classification predictions
        Parameters:
        - predictions - list of predictions each of which is
                        a pair <index of classified sample, confidence>
        - title       - text to put in the first line
        - f           - file to write to
        """
        _line = title
        _punct = ': '
        for _pred in predictions:
            _line += _punct
            _punct = ', '
            if len(_line) > 80:
                f.write(_line + "\n")
                _line = ""
            _line += f"{_pred[0]}/{100 * _pred[1]:.2f}%"
        if _line: f.write(_line + "\n")        
             
    def getClassMistakes(self, classes):
        """
        Get list of misclassifications for given classes
        Parameters:
        - classes  -- indices of classes to report
        Returns list of lists of miscalssifications:
                pairs <index of classified sample, prediction>
                Sublists gives misclassifications of classes
        """
        #Number of classification mistakes
        _mistakes = [[] for i in range(len(classes))]
        for _i in range(self._n_samples):
            if (self.predictions[_i] != self.labels[_i] and
                self.labels[_i] in classes):
                _bad_idx = classes.index(self.labels[_i])
                _mistakes[_bad_idx].append((_i, self.predictions[_i]))
        return _mistakes

    def reportMisclassifications(self, classes, mistakes, f):
        """
        Report misclassifications of given classes
        Parameters:
        - classes  -- indices of classes to report
        - mistakes -- list of lists of miscalssifications:
                      pairs <classified class index, prediction>
                      Sublists gives misclassifications of classes
        - f        -- file to write to
        """
        for _i, _c in enumerate(sorted(classes, 
                            key = lambda _cl: self.class_accuracy[_cl])):
            if not mistakes[_i]: continue
            f.write(f"#{_i}  Problem {self.problems[_c]} number {_c} " + 
                    f"is classified with {100.0 *self.class_accuracy[_c]:.2f}% " + 
                    "accuracy\n")
            _line = f"There are {len(mistakes[_i])} misclassified solutions"
            _punct = ': '
            for _err in sorted(mistakes[_i][: self.max_n_misclass_report], 
                    key = lambda _e: self.confidence[_e[0]], 
                               reverse = True):
                _conf = "{:5.2f}".format(100.0 * self.confidence[_err[0]])
                _line += _punct
                _punct = ', '
                if len(_line) > 80:
                    f.write(_line + "\n")
                    _line = ""
                _line += (self.solutions[_err[0]] + " => " + 
                          self.problems[_err[1]] + ' (' + _conf + '%)')
            if _line: f.write(_line + "\n")

    def reportConfusedClasses(self):
        """
        Report worst classification confusions,
        i.e. confused pairs of confused problems
        """
        _confusions = self.worstConfusions()
        _confusions = [_c for _c in _confusions if _c[0] != _c[1]]
        with open(f"{self.report_dir}/{self.confused_classes_fn}", 'w') as _lst, \
             open(f"{self.report_dir}/{self.confused_classes_csv}",
                  'w', newline='') as _csv:
            _lst.write("Most confused pairs of problems\n")
            _lst.write("-------------------------------\n")
            _lst.write(
                " Orig   Pred    N        N      %%    Original      Predicted\n")
            _lst.write(
                "Label  Label Samples  Errors  Errors  Problem       Problem  \n")
            _w = csv.writer(_csv)
            _w.writerow(("Original_Label", "Predicted_Label",
                         "N_samples", 
                        "%%_of_errors", "Original_Problem", 
                        "Predicted Problem"))
            for _c in sorted(_confusions,
                             key = lambda _conf:
                             self.norm_conf_mat[_conf[0], _conf[1]],
                             reverse = True):
                _lorig, _lpred = _c
                _lst.write("{:5d}  {:5d}  {:6d}  {:6d}  {:6.2f}  {:12s}  {:12s}\n".
                    format(_lorig, _lpred,
                           self._n_class_samples[_lorig],
                           self.conf_mat[_lorig, _lpred],
                           self.norm_conf_mat[_lorig, _lpred] * 100,
                           self.problems[_lorig], self.problems[_lpred]))
                _w.writerow((_lorig, _lpred, self._n_class_samples[_lorig],
                             self.norm_conf_mat[_lorig, _lpred] * 100,
                             self.problems[_lorig], self.problems[_lpred]))

    def worstConfusions(self):
        """
        Compute worst confusions of classification
        Returns list of pairs , each of which is
        a classified problem and the problem predicted
        """
        _n_confusions_report = \
            max(min(int(self._n_problems * self._n_problems * 
                self._n_extreme_cases), self.max_n_confus_report),
                self._n_problems)
        _flat_conf = self.norm_conf_mat.flatten()
        _part_index = \
            self._n_problems * self._n_problems
        _part_index -= (_n_confusions_report + self._n_problems)
        _worst_idx =  \
            np.argpartition(_flat_conf, _part_index)[_part_index :]
        _worst_idx =  \
            np.unravel_index(_worst_idx, 
                             self.norm_conf_mat.shape)
        _worst_idx = zip(_worst_idx[0].tolist(), _worst_idx[1].tolist())
        return _worst_idx
                
    def printClassAccuracy(self, f):
        """
        Report accuracy of classifications
        and their misclassified samples
        Parameters:
        -f   -- file to write report to
        """
        f.write("\nClassification statistics\n")
        f.write("-------------------------\n")
        self.reportClasses(range(self._n_problems), f)
        _class_acc = \
            sorted(zip(range(self._n_problems), self.class_accuracy), 
                   key = lambda _s : _s[1])
        _n_class_report = min(self._n_problems // 2,
                             self.max_n_class_report)
        _classes = _class_acc[: _n_class_report]
        _worst_classes = list(zip(*_classes))[0]
        _classes = _class_acc[-_n_class_report :]
        _best_classes = list(zip(*_classes))[0]
        _mistakes  = self.getClassMistakes(_worst_classes + _best_classes)
        f.write("\nWorst classified classes\n")
        f.write("--------------------------\n")
        self.reportClasses(_worst_classes, f)
        f.write("\nMisclassifications of the worst classified classes:\n")
        f.write("-----------------------------------------------------\n")
        self.reportMisclassifications(_worst_classes,
                    _mistakes[: len(_worst_classes)], f)
        f.write("\nCorrect classifications of the worst classified classes:\n")
        f.write("-----------------------------------------------------\n")
        self.reportRightClassifications(_worst_classes, f)
        f.write("\nBest classified classes\n")
        f.write("-------------------------\n")
        self.reportClasses(_best_classes, f)
        f.write("\nMisclassifications of the best classified classes:\n")
        f.write("---------------------------------------------------\n")
        self.reportMisclassifications(_best_classes, 
                                      _mistakes[len(_worst_classes) :], f)
                                      
    def writeReport(self):
        """
        Write report on classification and misclassification
        """
        with open(f"{self.report_dir}/{self._conf_mat_fn}", 'w') as _f:
            _f.write("Unnormalized confusion matrix\n")
            _f.write("row and column indices are labels\n")
            _f.write("---------------------------------\n")
            self.writeLargeMatrixInt(self.conf_mat, _f)
            _f.write("Normalized confusion matrix\n")
            _f.write("row and column indices are labels\n")
            _f.write("---------------------------------\n")
            self.writeLargeMatrixPct(self.norm_conf_mat, _f, 100.0)
        with open(f"{self.report_dir}/{self.class_stat_fn}", 'w') as _f:
            self.printClassAccuracy(_f)
        self.reportConfusedClasses()
        print("\nClassification report")
        print("-----------------------")
        print(metrics.classification_report(self.labels, 
                                    self.predictions,
                                    target_names = self.problems))
#---------------- End of class ClassConfusAnalysis ----------------------