Datasets:
Download scripts/v1_1/baseline.py from finipher/finipher-us-tax-document-classifier: direct link, hf CLI and curl.
- Browser
- Download file 3.53 kB
-
https://huggingface.co/datasets/finipher/finipher-us-tax-document-classifier/resolve/main/scripts/v1_1/baseline.py
- Command line
-
hf download hf://datasets/finipher/finipher-us-tax-document-classifier/scripts/v1_1/baseline.py
-
curl -L -o baseline.py https://huggingface.co/datasets/finipher/finipher-us-tax-document-classifier/resolve/main/scripts/v1_1/baseline.py
3.53 kB
| """Character TF-IDF + logistic regression smoke baseline (train-only fit). | |
| Run from the dataset root: python scripts/v1_1/baseline.py | |
| Writes reports/baseline-metrics.json. No checkpoint is saved. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| import pandas as pd | |
| import sklearn | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| from sklearn.linear_model import LogisticRegression | |
| from sklearn.metrics import accuracy_score, classification_report, f1_score | |
| ROOT = Path(__file__).resolve().parents[2] | |
| ORIGIN_V11 = "synthetic_programmatic_template" | |
| def _load(config: str, split: str) -> pd.DataFrame: | |
| return pd.read_json(ROOT / f"data/{config}/{split}.jsonl", lines=True, dtype={"label": str}) | |
| def _score(y_true, y_pred) -> dict: | |
| return {"rows": int(len(y_true)), "accuracy": round(float(accuracy_score(y_true, y_pred)), 4), | |
| "macro_f1": round(float(f1_score(y_true, y_pred, average="macro", zero_division=0)), 4)} | |
| def main() -> None: | |
| out = {"purpose": "Synthetic classifier smoke benchmark; not real-document acceptance.", | |
| "estimator": "character TF-IDF ngrams 3..5 (sublinear tf) and balanced logistic regression C=2.0", | |
| "sklearn_version": sklearn.__version__, "train_only_fit": True, "model_checkpoint_saved": False, "tasks": {}} | |
| masked = pd.read_parquet(ROOT / "robustness_views/test_header_masked_v1_1.parquet") | |
| for task in ("document_type", "document_family"): | |
| train, val, test = (_load(task, s) for s in ("train", "validation", "test")) | |
| vec = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5), sublinear_tf=True, min_df=2, max_features=300000) | |
| x = vec.fit_transform(train["text"]) | |
| clf = LogisticRegression(C=2.0, class_weight="balanced", max_iter=3000) | |
| clf.fit(x, train["label"]) | |
| res = {} | |
| for name, frame in (("validation", val), ("test", test)): | |
| pred = clf.predict(vec.transform(frame["text"])) | |
| res[name] = _score(frame["label"], pred) | |
| for origin, tag in (("synthetic_AI_labeled", "v1_0_rows"), (ORIGIN_V11, "v1_1_rows")): | |
| m = (frame["origin"] == origin).to_numpy() | |
| res[name][tag] = _score(frame["label"][m], pred[m]) | |
| if name == "test": | |
| rep = classification_report(frame["label"], pred, output_dict=True, zero_division=0) | |
| res[name]["per_label"] = {k: {kk: round(vv, 4) for kk, vv in v.items()} for k, v in rep.items() | |
| if isinstance(v, dict) and k not in ("macro avg", "weighted avg")} | |
| errors = frame.assign(pred=pred).loc[lambda f: f["label"] != f["pred"]] | |
| res[name]["confusions"] = errors.groupby(["label", "pred"]).size().sort_values(ascending=False).head(25) \ | |
| .reset_index().rename(columns={0: "count"}).to_dict("records") | |
| target = masked["label"] if task == "document_type" else masked["family"] | |
| res["test_header_masked_v1_1"] = _score(target, clf.predict(vec.transform(masked["text"]))) | |
| out["tasks"][task] = res | |
| (ROOT / "reports/baseline-metrics.json").write_text(json.dumps(out, indent=2) + "\n") | |
| print(json.dumps({t: {k: {kk: vv for kk, vv in v.items() if kk not in ("per_label", "confusions")} | |
| for k, v in r.items()} for t, r in out["tasks"].items()}, indent=1)) | |
| print(json.dumps(out["tasks"]["document_type"]["test"]["confusions"][:15])) | |
| if __name__ == "__main__": | |
| main() | |