File size: 7,971 Bytes
7f50cd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Released PAN 2019 SVD ensemble with the audit's input-shape adaptations.

Feature extraction is imported unchanged from the pinned authors' notebook.
Only the JSON adapter and handling of unsupported input shapes live here.
"""
import json
import os
from pathlib import Path
import sys

sys.path.insert(0, os.environ['CORE_DIR'])
from interface.data import read, as_string, write
sys.path.insert(0, str(Path(__file__).resolve().parent / 'vendor/authorship_attribution'))
import model
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.multiclass import OneVsRestClassifier
from sklearn.preprocessing import MaxAbsScaler
from sklearn.svm import SVC


CHANNELS = [('word', (1, 3)), ('char-dist', (1, 3)), ('char-std', (2, 5))]


class EmptyChannel(ValueError):
    """A published channel has no selected feature evidence on this input."""


def fit_classifier(x, labels, folds):
    classes = np.unique(labels)
    if len(classes) == 1:
        # There is no negative class for a discriminative SVM. Use the
        # one-class limit of the vote only when a feature channel survives.
        return None, classes
    classifier = OneVsRestClassifier(SVC(C=1, kernel='linear', gamma='auto'))
    if folds >= 2:
        classifier = CalibratedClassifierCV(classifier, cv=folds)
    # With a singleton class the source SVM is fitted on all support without
    # CV. Its features, loss, regularization and one-vs-rest strategy stay fixed.
    classifier.fit(x, labels)
    return classifier, classifier.classes_


def classifier_votes(classifier, q, folds):
    if classifier is None:
        return np.ones((len(q), 1))
    if folds >= 2:
        return classifier.predict_proba(q)
    # Audit-requested local margin fallback. Unit-temperature softmax is an
    # untuned adapter to the ensemble vote, not a calibrated probability claim.
    margins = np.asarray(classifier.decision_function(q))
    if margins.ndim == 1:
        margins = np.column_stack((-margins, margins))
    margins = margins - margins.max(axis=1, keepdims=True)
    votes = np.exp(margins)
    return votes / votes.sum(axis=1, keepdims=True)


def channel_probabilities(train, labels, queries, kind, ngrams, folds,
                          represented_positions, n_classes, stats):
    vocab = model.extend_vocabulary(ngrams, train, model=kind)
    stats['vocabulary_size'] = len(vocab)
    if not vocab:
        raise EmptyChannel('empty_vocabulary')
    vectorizer = TfidfVectorizer(
        analyzer='word' if kind == 'word' else 'char', ngram_range=ngrams,
        use_idf=True, norm='l2', lowercase=False, vocabulary=vocab,
        smooth_idf=True, sublinear_tf=True,
        **({} if kind == 'word' else {'min_df': 0.1, 'max_df': 0.8}))
    # Preserve the source's dense training arithmetic and feature ordering.
    x = vectorizer.fit_transform(train).toarray()
    idx = np.argsort(vectorizer.idf_)[:int(len(vectorizer.idf_) * 0.5)]
    x = x[:, idx]
    stats['selected_features'] = int(x.shape[1])
    if not x.shape[1]:
        raise EmptyChannel('zero_selected_features')
    if not np.any(x):
        raise EmptyChannel('all_selected_features_zero')
    scaler = MaxAbsScaler()
    x = scaler.fit_transform(x)
    # Retain the previous adapter's bound on nonexistent SVD dimensions.
    svd = None
    if x.shape[1] > 1:
        svd = TruncatedSVD(n_components=min(63, x.shape[0], x.shape[1]),
                           algorithm='randomized', random_state=42)
        x = svd.fit_transform(x)
    stats['projected_features'] = int(x.shape[1])
    # A one-column full-rank SVD changes at most the sign. sklearn requires
    # two input columns, so keep that already one-dimensional representation.
    classifier, classifier_classes = fit_classifier(x, labels, folds)
    columns = [represented_positions[int(label)] for label in classifier_classes]
    full = np.zeros((len(queries), n_classes))
    for offset in range(0, len(queries), 32):
        # TF-IDF normalization still precedes selection, exactly as upstream.
        q = vectorizer.transform(queries[offset:offset + 32])[:, idx]
        q = scaler.transform(q)
        q = svd.transform(q) if svd is not None else q.toarray()
        full[offset:offset + len(q), columns] = classifier_votes(classifier, q, folds)
    stats['status'] = 'used'
    return full


def predict(data, diagnostics=None):
    if diagnostics is None:
        diagnostics = {}
    diagnostics.update({'version': 1, 'channels': [], 'branch_counts': {},
                        'query_count': len(data['queries'])})
    queries = [as_string(row) for row in data['queries']]
    if not queries:
        diagnostics['mode'] = 'empty_queries'
        return []
    # Preserve declared candidate order and within-author support order from
    # the previous adapter. Rejection is never a fitted author class.
    train, labels, represented_positions, represented_counts = [], [], [], []
    for index, label in enumerate(data['classes']):
        rows = [r for r in data['support'] if r['label'] == label and label != 0]
        if rows:
            represented_positions.append(index)
            represented_counts.append(len(rows))
            train.extend(as_string(r) for r in rows)
            labels.extend([len(represented_positions) - 1] * len(rows))
    diagnostics['represented_classes'] = [data['classes'][i] for i in represented_positions]
    diagnostics['support_counts'] = represented_counts
    diagnostics['missing_classes'] = [label for i, label in enumerate(data['classes'])
                                      if i not in represented_positions and label != 0]
    if not represented_positions:
        diagnostics['mode'] = 'no_support'
        diagnostics['rejected_queries'] = len(queries)
        return [{'id': r['id'], 'label': 0} for r in data['queries']]
    labels = np.asarray(labels)
    folds = min(3, min(represented_counts))
    mode = ('single_class' if len(represented_positions) == 1 else
            'margin' if folds == 1 else 'calibrated_cv%d' % folds)
    diagnostics['mode'] = mode
    diagnostics['calibration_folds'] = folds if mode.startswith('calibrated') else 0
    probas = []
    for kind, ngrams in CHANNELS:
        stats = {'channel': kind}
        diagnostics['channels'].append(stats)
        try:
            probas.append(channel_probabilities(
                train, labels, queries, kind, ngrams, folds,
                represented_positions, len(data['classes']), stats))
        except EmptyChannel as error:
            stats.update(status='skipped', reason=str(error))
    diagnostics['branch_counts'] = {mode: len(probas), 'empty_channel': 3 - len(probas)}
    if not probas:
        diagnostics['mode'] = 'no_usable_channels'
        diagnostics['rejected_queries'] = len(queries)
        return [{'id': r['id'], 'label': 0} for r in data['queries']]
    avg = np.average(probas, axis=0)
    predictions = []
    for row, probabilities in zip(data['queries'], avg):
        ordered = sorted(probabilities, reverse=True)
        label = data['classes'][int(np.argmax(probabilities))]
        second = ordered[1] if len(ordered) > 1 else 0.0
        if ordered[0] - second < 0.1 or ordered[0] < 0.25:
            label = 0
        predictions.append({'id': row['id'], 'label': label})
    diagnostics['rejected_queries'] = sum(row['label'] == 0 for row in predictions)
    return predictions


def main(data_dir, output_dir):
    diagnostics = {}
    predictions = predict(read(data_dir), diagnostics)
    write(output_dir, predictions)
    # The grader consumes predictions.json; this small text sidecar records
    # branch counts without requiring practice answers at inference time.
    (Path(output_dir) / 'diagnostics.json').write_text(json.dumps(diagnostics, indent=2) + '\n')


if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])