Download tasks/authorship_lab/solution/reference/main.py from Tokenwave-AI/REE: direct link, hf CLI and curl.
- Browser
- Download file 7.97 kB
-
https://huggingface.co/datasets/Tokenwave-AI/REE/resolve/main/tasks/authorship_lab/solution/reference/main.py
- Command line
-
hf download hf://datasets/Tokenwave-AI/REE/tasks/authorship_lab/solution/reference/main.py
-
curl -L -o main.py https://huggingface.co/datasets/Tokenwave-AI/REE/resolve/main/tasks/authorship_lab/solution/reference/main.py
7.97 kB
| """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]) | |