Download expansion_v2/experiments/contextual-discourse/source/legacy_transfer.py from Giuliocc/doxa-methods: direct link, hf CLI and curl.
- Browser
- Download file 4.41 kB
-
https://huggingface.co/datasets/Giuliocc/doxa-methods/resolve/main/expansion_v2/experiments/contextual-discourse/source/legacy_transfer.py
- Command line
-
hf download hf://datasets/Giuliocc/doxa-methods/expansion_v2/experiments/contextual-discourse/source/legacy_transfer.py
-
curl -L -o legacy_transfer.py https://huggingface.co/datasets/Giuliocc/doxa-methods/resolve/main/expansion_v2/experiments/contextual-discourse/source/legacy_transfer.py
4.41 kB
| """After selection: unchanged deployed-wording transfer on the new source. | |
| The old BABE task and BASIL lexical-span task are related, not identical. | |
| This is a lexical-only cross-dataset diagnostic, never an invented second | |
| informational-bias head or a substitute for the registered matched controls. | |
| """ | |
| import importlib.util | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| from sklearn.metrics import f1_score, precision_score, recall_score | |
| from data import ROOT, fingerprint, rows, write_json | |
| def positive_metrics(y, prediction): | |
| return {"rows": len(y), "positive_reference": int(y.sum()), "positive_predictions": int(prediction.sum()), | |
| "positive_f1": float(f1_score(y, prediction, zero_division=0)), | |
| "precision": float(precision_score(y, prediction, zero_division=0)), "recall": float(recall_score(y, prediction, zero_division=0))} | |
| def interval(y, candidate, legacy, groups): | |
| unique = sorted(set(groups)) | |
| groups = np.asarray(groups) | |
| matrices = [np.array([np.bincount(2*y[groups == group] + value[groups == group], minlength=4) for group in unique]) | |
| for value in (candidate, legacy)] | |
| random = np.random.default_rng(1729) | |
| differences = [] | |
| for _ in range(2000): | |
| weights = np.bincount(random.integers(0, len(unique), len(unique)), minlength=len(unique)) | |
| scores = [] | |
| for matrix in matrices: | |
| tn, fp, fn, tp = weights @ matrix | |
| scores.append(2*tp / max(1, 2*tp + fp + fn)) | |
| differences.append(scores[0] - scores[1]) | |
| return [float(value) for value in np.quantile(differences, [.025, .975])] | |
| def main(): | |
| local = ROOT / "local" | |
| if not (local / "EVALUATION.json").exists(): | |
| raise RuntimeError("Legacy transfer follows fixed candidate evaluation") | |
| previous = ROOT.parents[1] / "improvement_release/model/stage" | |
| spec = importlib.util.spec_from_file_location("doxa_previous_wording", previous / "inference.py") | |
| module = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(module) | |
| model = module.WordingModel(previous, threads=1) | |
| test = rows("test") | |
| truth = np.array([row["labels"]["lexical_bias"] for row in test]) | |
| results = [model.check(row["text"]) for row in test] | |
| prediction = np.array([int(row["model_score"] >= .5) if row["model_score"] is not None else 0 for row in results]) | |
| saved = [json.loads(line) for line in (local / "test_predictions.jsonl").read_text().splitlines()] | |
| selected = json.loads((local / "LOCKED_SELECTION.json").read_text())["selected_pipeline"] | |
| assert [row["id"] for row in test] == [row["id"] for row in saved] | |
| candidate = np.array([row["pipelines"][selected]["labels"][0] for row in saved]) | |
| metric = positive_metrics(truth, prediction) | |
| report = {"source_task": "BASIL_lexical_bias", "previous_model_task": "BABE expert-majority wording", | |
| "previous_manifest_sha256": fingerprint(previous / "runtime_manifest.json"), | |
| "previous_graph_sha256": fingerprint(previous / "onnx/model_quantized.onnx"), | |
| "previous_threshold": .5, "previous_threshold_retuned": False, "previous_model_retrained": False, | |
| "legacy_binary_before_abstention": metric, | |
| "legacy_original_resolved_coverage": float(np.mean([row["decision"] != "unresolved" for row in results])), | |
| "new_native_lexical": positive_metrics(truth, candidate), | |
| "new_native_lexical_gain": float(f1_score(truth, candidate) - metric["positive_f1"]), | |
| "new_native_gain_interval_95": interval(truth, candidate, prediction, [row["group_id"] for row in test]), | |
| "informational_task": "unsupported_by_previous_model_no_proxy_head_created", | |
| "used_for_training_selection_or_promotion_gate": False, | |
| "interpretation": "Related source-task cross-dataset transfer only; the two labeling operationalizations differ and this does not establish general superiority or political neutrality."} | |
| if "quantized" in saved[0]["pipelines"]: | |
| quantized = np.array([row["pipelines"]["quantized"]["labels"][0] for row in saved]) | |
| report["new_quantized_lexical"] = positive_metrics(truth, quantized) | |
| report["new_quantized_gain_interval_95"] = interval(truth, quantized, prediction, [row["group_id"] for row in test]) | |
| write_json(local / "LEGACY_TRANSFER.json", report) | |
| print(json.dumps(report, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |