Download tools/evidence_model.py from Giuliocc/doxa-methods: direct link, hf CLI and curl.
- Browser
- Download file 8.82 kB
-
https://huggingface.co/datasets/Giuliocc/doxa-methods/resolve/main/tools/evidence_model.py
- Command line
-
hf download hf://datasets/Giuliocc/doxa-methods/tools/evidence_model.py
-
curl -L -o evidence_model.py https://huggingface.co/datasets/Giuliocc/doxa-methods/resolve/main/tools/evidence_model.py
8.82 kB
| """Small portable development classifier and extractive evidence selector.""" | |
| import argparse | |
| from collections import Counter | |
| import json | |
| import math | |
| from pathlib import Path | |
| import re | |
| from methods import LABELS | |
| ROOT = Path(__file__).parent | |
| FEATURE = re.compile(r"\b[^\W_]+\b", re.UNICODE) | |
| SENTENCE = re.compile(r"\S.*?(?:[.!?](?=\s|$)|(?=\n)|$)", re.S) | |
| def features(text, channel): | |
| tokens = FEATURE.findall(text.casefold()) | |
| counts = Counter(f"{channel}:w:{value}" for value in tokens) | |
| counts.update(f"{channel}:b:{a} {b}" for a, b in zip(tokens, tokens[1:])) | |
| return counts | |
| def inputs(text, context, with_context): | |
| result = features(text, "p") | |
| if with_context: | |
| result.update(features(context, "c")) | |
| return result | |
| def candidates(text, context): | |
| for segment, value in (("passage",text),("context",context)): | |
| for match in SENTENCE.finditer(value): | |
| yield {"segment":segment,"start":match.start(),"end":match.end(),"quote":match.group()} | |
| def rank_features(candidate, label): | |
| return features(candidate["quote"], f'{label}:{candidate["segment"]}') | |
| def scores(head, feature_counts): | |
| vocabulary = head["vocabulary"] | |
| observed = [(vocabulary[key], value) for key,value in feature_counts.items() if key in vocabulary] | |
| if not observed: | |
| return None | |
| norm = math.sqrt(sum(value * value for _,value in observed)) | |
| raw = [intercept + sum(row[index] * value / norm for index,value in observed) | |
| for row,intercept in zip(head["weights"],head["intercepts"],strict=True)] | |
| terms = [math.exp(v - max(raw)) for v in raw] | |
| total = sum(terms) | |
| return {label: value / total for label,value in zip(head["classes"],terms,strict=True)} | |
| class PortableModel: | |
| max_chars = 6000 | |
| def __init__(self, artifact): | |
| self.model = json.loads(Path(artifact).read_text(encoding="utf-8")) | |
| self.revision = self.model["revision"] | |
| def predict(self, text, context="", kind="with_context"): | |
| if not isinstance(text,str) or not isinstance(context,str) or not text.strip(): | |
| raise ValueError("Passage must be non-empty text and context must be text") | |
| if max(len(text),len(context)) > self.max_chars: | |
| raise ValueError("Passage and context are limited to 6,000 Unicode characters each") | |
| result = {"model_revision":self.revision,"architecture":kind,"decision":None, | |
| "status":"abstained","scores":None,"evidence":None, | |
| "annotation_status":"experimental_synthetic_development"} | |
| probs = scores(self.model[kind],inputs(text,context,kind=="with_context")) | |
| if not probs: | |
| result["reason"]="no_known_features" | |
| return result | |
| winner = max(probs,key=probs.get) | |
| result["scores"]=probs | |
| if probs[winner] < self.model["decision_threshold"]: | |
| result["reason"]="low_uncalibrated_score" | |
| return result | |
| if winner == "insufficient_context": | |
| result["reason"]="insufficient_context" | |
| return result | |
| result.update(status="ok",decision=winner) | |
| chosen = None | |
| best = self.model["evidence_threshold"] | |
| for candidate in candidates(text,context if kind=="with_context" else ""): | |
| probability = scores(self.model["extractor"],rank_features(candidate,winner)) | |
| if probability and probability["eligible"] > best: | |
| chosen,best = candidate,probability["eligible"] | |
| if chosen: | |
| result["evidence"]=chosen | |
| return result | |
| def fit_head(samples, labels): | |
| from sklearn.feature_extraction import DictVectorizer | |
| from sklearn.linear_model import LogisticRegression | |
| from sklearn.preprocessing import normalize | |
| vectorizer=DictVectorizer() | |
| matrix=normalize(vectorizer.fit_transform(samples)) | |
| learner=LogisticRegression(C=8.0, max_iter=500,random_state=1729).fit(matrix,labels) | |
| coefficients=learner.coef_ | |
| intercepts=learner.intercept_ | |
| if len(learner.classes_) == 2: | |
| coefficients=[-coefficients[0]/2,coefficients[0]/2] | |
| intercepts=[-intercepts[0]/2,intercepts[0]/2] | |
| return {"vocabulary": vectorizer.vocabulary_, "classes":list(learner.classes_), | |
| "weights":[row.tolist() for row in coefficients], | |
| "intercepts":[float(value) for value in intercepts]} | |
| def overlap(candidate, reference): | |
| if not candidate or candidate["segment"] != reference["segment"]: | |
| return 0.0 | |
| shared = max(0,min(candidate["end"],reference["end"])-max(candidate["start"],reference["start"])) | |
| union = max(candidate["end"],reference["end"])-min(candidate["start"],reference["start"]) | |
| return shared/union | |
| def evaluate(model, rows, kind): | |
| from sklearn.metrics import f1_score | |
| by_event = {} | |
| labeled = [] | |
| for row in rows: | |
| result=model.predict(row["text"],row["context"],kind) | |
| # An explicit insufficient-context response is a meaningful predicted | |
| # class; a confidence or vocabulary abstention stays unclassified. | |
| decision=result["decision"] or ("insufficient_context" if result.get("reason")=="insufficient_context" else "abstained") | |
| score = overlap(result["evidence"],row["reference_span"]) | |
| labeled.append({"unit_id":row["unit_id"],"event_id":row["event_id"],"family":row["family"], | |
| "reference":row["label"],"decision":decision,"exact_span":score==1.0, | |
| "overlap":score,**{key:result[key] for key in ("status","evidence","scores")}}) | |
| if row["family"]=="context_flip": | |
| by_event.setdefault(row["event_id"],[]).append(decision==row["label"]) | |
| eligible_spans=[row for row in labeled if row["reference"]!="insufficient_context"] | |
| return { | |
| "rows":len(labeled),"events":len({row["event_id"] for row in rows}), | |
| "macro_f1":float(f1_score([row["reference"] for row in labeled], | |
| [row["decision"] for row in labeled],labels=list(LABELS),average="macro",zero_division=0)), | |
| "coverage":sum(row["decision"]!="abstained" for row in labeled)/len(labeled), | |
| "paired_context_switches":len(by_event), | |
| "paired_both_correct":sum(len(x)==2 and all(x) for x in by_event.values()), | |
| "correct_decision_exact_evidence":sum(row["exact_span"] and row["reference"]==row["decision"] for row in eligible_spans), | |
| "evidence_denominator":len(eligible_spans),"outputs":labeled, | |
| } | |
| def train(data, out): | |
| import pyarrow.parquet as pq | |
| from build_data import json_file | |
| from methods import canonical_sha | |
| tr=pq.read_table(data/"train.parquet").to_pylist() | |
| va=pq.read_table(data/"validation.parquet").to_pylist() | |
| te=pq.read_table(data/"development_test.parquet").to_pylist() | |
| parts=[{row["event_id"] for row in split} for split in (tr,va,te)] | |
| if any(parts[a] & parts[b] for a,b in ((0,1),(0,2),(1,2))): | |
| raise ValueError("Event leakage across splits") | |
| model={ | |
| "revision":"0.1.0","training_data_sha256":canonical_sha(tr), | |
| "decision_threshold":.45,"evidence_threshold":.50, | |
| "passage_only":fit_head([inputs(row["text"],"",False) for row in tr],[row["label"] for row in tr]), | |
| "with_context":fit_head([inputs(row["text"],row["context"],True) for row in tr],[row["label"] for row in tr]), | |
| } | |
| samples, labels = [],[] | |
| for row in tr: | |
| if row["label"]=="insufficient_context": | |
| continue | |
| for candidate in candidates(row["text"],row["context"]): | |
| samples.append(rank_features(candidate,row["label"])) | |
| labels.append("eligible" if overlap(candidate,row["reference_span"])>=.5 else "ineligible") | |
| model["extractor"]=fit_head(samples,labels) | |
| out.mkdir(parents=True,exist_ok=True) | |
| json_file(out/"model.json",model) | |
| portable=PortableModel(out/"model.json") | |
| report={split:{kind:evaluate(portable,rows,kind) for kind in ("passage_only","with_context")} | |
| for split,rows in (("validation",va),("development_test",te))} | |
| report["data_status"]="Fictional template families and AI-provisional decisions. Development results only." | |
| report["training_groups"]=[len(part) for part in parts] | |
| report["threshold_policy"]="Fixed during implementation at 0.45 for the classifier and 0.50 for the span selector. Scores are uncalibrated." | |
| json_file(out/"evaluation.json",report) | |
| for kind,metrics in report["development_test"].items(): | |
| print(kind,{k:v for k,v in metrics.items() if k!="outputs"}) | |
| if __name__=="__main__": | |
| parser=argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--data",type=Path,default=ROOT/"work") | |
| parser.add_argument("--out",type=Path,default=ROOT/"work") | |
| args=parser.parse_args() | |
| train(args.data,args.out) | |