ensemble_classifier.py 5.55 KB
Newer Older
Raul Puri's avatar
Raul Puri committed
1
2
3
4
import os
import argparse
import collections

Raul Puri's avatar
Raul Puri committed
5
6
7
import numpy as np
import torch

Neel Kant's avatar
Neel Kant committed
8

Raul Puri's avatar
Raul Puri committed
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
def process_files(args):
    all_predictions = collections.OrderedDict()
    all_labels = collections.OrderedDict()
    all_uid = collections.OrderedDict()
    for path in args.paths:
        path = os.path.join(path, args.prediction_name)
        try:
            data = torch.load(path)
            for dataset in data:
                name, d = dataset
                predictions, labels, uid = d
                if name not in all_predictions:
                    all_predictions[name] = np.array(predictions)
                    if args.labels is None:
                        args.labels = [i for i in range(all_predictions[name].shape[1])]
                    if args.eval:
                        all_labels[name] = np.array(labels)
                    all_uid[name] = np.array(uid)
                else:
                    all_predictions[name] += np.array(predictions)
                    assert np.allclose(all_uid[name], np.array(uid))
        except Exception as e:
            print(e)
            continue
    return all_predictions, all_labels, all_uid


def get_threshold(all_predictions, all_labels, one_threshold=False):
    if one_threshold:
Raul Puri's avatar
Raul Puri committed
38
39
40
41
42
43
        all_predictons = {'combined': np.concatenate(list(all_predictions.values()))}
        all_labels = {'combined': np.concatenate(list(all_predictions.labels()))}
    out_thresh = []
    for dataset in all_predictions:
        preds = all_predictions[dataset]
        labels = all_labels[dataset]
Neel Kant's avatar
Neel Kant committed
44
        out_thresh.append(calc_threshold(preds, labels))
Raul Puri's avatar
Raul Puri committed
45
    return out_thresh
Raul Puri's avatar
Raul Puri committed
46
47


Raul Puri's avatar
Raul Puri committed
48
def calc_threshold(p, l):
Neel Kant's avatar
Neel Kant committed
49
    trials = [(i) * (1. / 100.) for i in range(100)]
Raul Puri's avatar
Raul Puri committed
50
51
52
53
54
55
56
57
58
    best_acc = float('-inf')
    best_thresh = 0
    for t in trials:
        acc = ((apply_threshold(p, t).argmax(-1) == l).astype(float)).mean()
        if acc > best_acc:
            best_acc = acc
            best_thresh = t
    return best_thresh

Raul Puri's avatar
Raul Puri committed
59

Raul Puri's avatar
Raul Puri committed
60
61
def apply_threshold(preds, t):
    assert (np.allclose(preds.sum(-1), np.ones(preds.shape[0])))
Neel Kant's avatar
Neel Kant committed
62
    prob = preds[:, -1]
Raul Puri's avatar
Raul Puri committed
63
64
65
66
67
    thresholded = (prob >= t).astype(int)
    preds = np.zeros_like(preds)
    preds[np.arange(len(thresholded)), thresholded.reshape(-1)] = 1
    return preds

Raul Puri's avatar
Raul Puri committed
68

Raul Puri's avatar
Raul Puri committed
69
def threshold_predictions(all_predictions, threshold):
Neel Kant's avatar
Neel Kant committed
70
71
    if len(threshold) != len(all_predictions):
        threshold = [threshold[-1]] * (len(all_predictions) - len(threshold))
Raul Puri's avatar
Raul Puri committed
72
73
74
75
76
77
78
    for i, dataset in enumerate(all_predictions):
        thresh = threshold[i]
        preds = all_predictions[dataset]
        all_predictions[dataset] = apply_threshold(preds, thresh)
    return all_predictions


Raul Puri's avatar
Raul Puri committed
79
80
def postprocess_predictions(all_predictions, all_labels, args):
    for d in all_predictions:
Neel Kant's avatar
Neel Kant committed
81
        all_predictions[d] = all_predictions[d] / len(args.paths)
Raul Puri's avatar
Raul Puri committed
82

Raul Puri's avatar
Raul Puri committed
83
84
85
    if args.calc_threshold:
        args.threshold = get_threshold(all_predictions, all_labels, args.one_threshold)
        print('threshold', args.threshold)
Raul Puri's avatar
Raul Puri committed
86

Raul Puri's avatar
Raul Puri committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
    if args.threshold is not None:
        all_predictions = threshold_predictions(all_predictions, args.threshold)

    return all_predictions, all_labels


def write_predictions(all_predictions, all_labels, all_uid, args):
    all_correct = 0
    count = 0
    for dataset in all_predictions:
        preds = all_predictions[dataset]
        preds = np.argmax(preds, -1)
        if args.eval:
            correct = (preds == all_labels[dataset]).sum()
            num = len(all_labels[dataset])
Neel Kant's avatar
Neel Kant committed
102
            accuracy = correct / num
Raul Puri's avatar
Raul Puri committed
103
104
105
106
107
108
            count += num
            all_correct += correct
            accuracy = (preds == all_labels[dataset]).mean()
            print(accuracy)
        if not os.path.exists(os.path.join(args.outdir, dataset)):
            os.makedirs(os.path.join(args.outdir, dataset))
Neel Kant's avatar
Neel Kant committed
109
110
111
        outpath = os.path.join(
            args.outdir, dataset, os.path.splitext(
                args.prediction_name)[0] + '.tsv')
Raul Puri's avatar
Raul Puri committed
112
113
        with open(outpath, 'w') as f:
            f.write('id\tlabel\n')
Neel Kant's avatar
Neel Kant committed
114
115
            f.write('\n'.join(str(uid) + '\t' + str(args.labels[p])
                              for uid, p in zip(all_uid[dataset], preds.tolist())))
Raul Puri's avatar
Raul Puri committed
116
    if args.eval:
Neel Kant's avatar
Neel Kant committed
117
        print(all_correct / count)
Raul Puri's avatar
Raul Puri committed
118
119
120
121
122
123
124
125


def ensemble_predictions(args):
    all_predictions, all_labels, all_uid = process_files(args)
    all_predictions, all_labels = postprocess_predictions(all_predictions, all_labels, args)
    write_predictions(all_predictions, all_labels, all_uid, args)


Neel Kant's avatar
Neel Kant committed
126
def main():
Raul Puri's avatar
Raul Puri committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
    parser = argparse.ArgumentParser()
    parser.add_argument('--paths', required=True, nargs='+',
                        help='paths to checkpoint directories used in ensemble')
    parser.add_argument('--eval', action='store_true',
                        help='compute accuracy metrics against labels (dev set)')
    parser.add_argument('--outdir',
                        help='directory to place ensembled predictions in')
    parser.add_argument('--prediction-name', default='test_predictions.pt',
                        help='name of predictions in checkpoint directories')
    parser.add_argument('--calc-threshold', action='store_true',
                        help='calculate threshold classification')
    parser.add_argument('--one-threshold', action='store_true',
                        help='use on threshold for all subdatasets')
    parser.add_argument('--threshold', nargs='+', default=None, type=float,
                        help='user supplied threshold for classification')
Neel Kant's avatar
Neel Kant committed
142
    parser.add_argument('--labels', nargs='+', default=None,
Raul Puri's avatar
Raul Puri committed
143
144
145
146
147
148
                        help='whitespace separated list of label names')
    args = parser.parse_args()
    ensemble_predictions(args)


if __name__ == '__main__':
Neel Kant's avatar
Neel Kant committed
149
    main()