File size: 4,853 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
"""Fit only the shared training data; no external assets or practice labels."""

import argparse
import csv
import hashlib
import json
from pathlib import Path
import platform
import resource
import time
import warnings

import numpy as np
import scipy
import sklearn
from sklearn.feature_extraction.text import TfidfVectorizer

from text_features import paper_text
from vendor.scirepeval_regression import fit_regression


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--core", type=Path, required=True)
    parser.add_argument("--model", type=Path, default=Path(__file__).resolve().parent)
    args = parser.parse_args()
    start = time.monotonic()
    documents_path = args.core / "interface/train.jsonl"
    labels_path = args.core / "interface/train.csv"
    with documents_path.open(encoding="utf-8") as stream:
        documents_list = [json.loads(line) for line in stream if line.strip()]
    documents = {row["doc_id"]: row for row in documents_list}
    with labels_path.open(encoding="utf-8", newline="") as stream:
        rows = list(csv.DictReader(stream))
    identifiers = [row["paper_id"] for row in rows]
    if len(documents) != len(documents_list) or len(set(identifiers)) != len(rows):
        raise ValueError("Duplicate shared-training identifiers")
    if set(identifiers) != set(documents):
        raise ValueError("The shared-training document and label IDs differ")
    labels = np.asarray([float(row["label"]) for row in rows], dtype=np.float64)
    if not np.isfinite(labels).all():
        raise ValueError("Nonfinite training labels")

    # All parameters are the documented scikit-learn 1.5.2 defaults.
    vectorizer = TfidfVectorizer()
    features = vectorizer.fit_transform([paper_text(documents[key]) for key in identifiers])
    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always")
        search = fit_regression(features, labels)
    estimator = search.best_estimator_

    args.model.mkdir(parents=True, exist_ok=True)
    vocabulary = {word: int(index) for word, index in vectorizer.vocabulary_.items()}
    (args.model / "vocabulary.json").write_text(
        json.dumps(vocabulary, ensure_ascii=False, sort_keys=True) + "\n", encoding="utf-8")
    np.savez_compressed(args.model / "weights.npz", idf=vectorizer.idf_,
                        coef=estimator.coef_, intercept=estimator.intercept_)

    # Validate the portable inference state against the fitted estimator.
    with np.load(args.model / "weights.npz", allow_pickle=False) as state:
        restored = TfidfVectorizer(vocabulary=vocabulary)
        restored.idf_ = state["idf"]
        sample = restored.transform([paper_text(documents[key]) for key in identifiers[:16]])
        restored_predictions = np.asarray(sample @ state["coef"]).ravel() + state["intercept"][0]
    np.testing.assert_allclose(restored_predictions, estimator.predict(features[:16]),
                               rtol=1e-12, atol=1e-12)

    record = {
        "method": "TF-IDF + SciRepEval LinearSVR (standard text-regression fallback)",
        "source_commit": "e04594e6401cb68fb4ddf6daa801fb219cccc0bb",
        "rows": len(rows), "features": features.shape[1], "nonzero_features": features.nnz,
        "label_min": float(labels.min()), "label_max": float(labels.max()),
        "training_order": "train.csv row order, joined on paper_id/doc_id",
        "training_sha256": {path.name: hashlib.sha256(path.read_bytes()).hexdigest()
                            for path in (documents_path, labels_path)},
        "selected_C": float(search.best_params_["C"]),
        "cv": 3, "cv_shuffle": False, "cv_selection_score": "R2", "seed": 42,
        "cv_results": [{"C": float(c), "mean_R2": float(mean), "std_R2": float(std)}
                       for c, mean, std in zip(search.cv_results_["param_C"],
                                               search.cv_results_["mean_test_score"],
                                               search.cv_results_["std_test_score"])],
        "estimator_parameters": estimator.get_params(),
        "selected_estimator_iterations": int(estimator.n_iter_),
        "warnings": [{"category": warning.category.__name__, "message": str(warning.message)}
                     for warning in caught],
        "portable_state_check": "passed: fitted-estimator equivalence on 16 training rows",
        "versions": {"python": platform.python_version(), "numpy": np.__version__,
                     "scipy": scipy.__version__, "scikit-learn": sklearn.__version__},
        "elapsed_seconds": time.monotonic() - start,
        "peak_rss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
    }
    (args.model / "training.json").write_text(json.dumps(record, indent=2) + "\n")
    print(json.dumps(record, indent=2))


if __name__ == "__main__":
    main()