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