alea-runs / alea /gen_kaggle_cls.py
Akahsizrr's picture
Upload alea/gen_kaggle_cls.py with huggingface_hub
59f32ca verified
Raw History Blame
19.7 kB
"""Real Kaggle classification datasets -> decision-model rows.
Eight families, one per dataset (see data/kaggle/manifest.json). Files are
loaded lazily ONCE into a module-level cache (_load); subsampling and the
empirical bucket tables are also computed once at load time.
Row flavors (flagged in code):
DET - targets are the record's ground-truth label (0/1 or one-hot).
SOFT - targets are empirical P(label | bucket) computed over the FULL
dataset, bucketed by 1-2 strong features (+ Beta(1,1) smoothing).
Text families emit the text itself as state (optionally with a one-line task
prefix); tabular families serialize the record as a compact JSON dict.
"""
import json
import random
from collections import Counter
from pathlib import Path
import pandas as pd
from .genbase import (generate, emit, q_choice, q_noul, q_score, q_regress,
validate_row, write_jsonl)
rng = random.Random()
DATA = Path(__file__).resolve().parents[1] / "data" / "kaggle"
_CACHE = {}
CC_FEATS = ["Time"] + [f"V{i}" for i in range(1, 29)] + ["Amount"]
IRIS_FEATS = ["SepalLengthCm", "SepalWidthCm", "PetalLengthCm", "PetalWidthCm"]
IRIS_CLASSES = ["Iris-setosa", "Iris-versicolor", "Iris-virginica"]
# (instruction, polarity) pairs; polarity 1 means "yes" == positive label,
# 0 means the question is phrased on the negative class (target = 1 - p).
_SPAM_Q = [("Is this message spam?", 1),
("Is this SMS junk or spam?", 1),
("Should this text be filtered out as spam?", 1),
("Is this a normal personal message?", 0)]
_FAKE_Q = [("Is this article fake news?", 1),
("Is this news story fabricated?", 1),
("Was this article made up or intentionally false?", 1),
("Is this genuine, trustworthy reporting?", 0)]
_NEWS_Q = ["Which section does this article belong to?",
"Which news desk should handle this piece?",
"Pick the most appropriate category for this article.",
"Under which section should this article be filed?"]
_CHURN_Q = [("Will this customer churn?", 1),
("Is this customer likely to cancel their service?", 1),
("Will this account be lost to churn?", 1),
("Will this customer stay with the company?", 0)]
_HEART_Q = [("Does this patient have heart disease?", 1),
("Is heart disease present in this patient?", 1),
("Would a cardiologist flag this patient for heart disease?", 1),
("Is this patient's heart healthy?", 0)]
_MUSH_Q = [("Is this mushroom poisonous?", 1),
("Would eating this mushroom be dangerous?", 1),
("Is this mushroom toxic?", 1),
("Is this mushroom safe to eat?", 0)]
_FRAUD_Q = [("Is this transaction fraudulent?", 1),
("Should this transaction be flagged as fraud?", 1),
("Is this a fraudulent card transaction?", 1),
("Is this transaction legitimate?", 0)]
_IRIS_Q = ["Which iris species is this?",
"Identify the species of this iris specimen.",
"What species does this iris belong to?"]
# ---------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------
def _trunc(s, n):
"""Collapse whitespace and keep the beginning of a long text."""
s = " ".join(str(s).split())
if len(s) <= n:
return s
return s[:n].rsplit(" ", 1)[0] + "..."
def _clean(v):
"""numpy scalar -> python; round floats; NaN -> None (for json.dumps)."""
if hasattr(v, "item"):
v = v.item()
if isinstance(v, float):
if v != v:
return None
return round(v, 4)
return v
def _emp_binary(df, keys, y):
"""{key-tuple: P(y==1 | bucket)} with Beta(1,1) smoothing, over full df."""
g = df.groupby(keys, observed=True)[y].agg(["sum", "count"])
out = {}
for k, r in g.iterrows():
kk = k if isinstance(k, tuple) else (k,)
out[tuple(str(x) for x in kk)] = float((r["sum"] + 1.0)
/ (r["count"] + 2.0))
return out
def _emp_multi(df, key, label, classes, prior=1.0):
"""{bucket: [P(label==c | bucket) for c in classes]} smoothed."""
ct = df.groupby(key, observed=True)[label].value_counts().unstack(
fill_value=0)
ct = ct.reindex(columns=classes, fill_value=0)
out = {}
for k, row in ct.iterrows():
tot = float(row.sum()) + prior * len(classes)
out[str(k)] = [float((row[c] + prior) / tot) for c in classes]
return out
# ---------------------------------------------------------------------------
# lazy loaders — each file is read ONCE per process
# ---------------------------------------------------------------------------
def _load_sms():
df = pd.read_csv(DATA / "sms_spam" / "spam.csv", encoding="latin-1",
usecols=["v1", "v2"]).dropna(subset=["v2"])
return [(str(t), float(l == "spam"))
for l, t in zip(df["v1"], df["v2"])]
def _load_fakenews():
out = []
for fn, y in (("Fake.csv", 1.0), ("True.csv", 0.0)):
df = pd.read_csv(DATA / "fake_news" / fn)
# ~631 rows have empty body text — skip them
df = df[df["text"].astype(str).str.strip().str.len() > 0]
out += [(str(t), str(x), y)
for t, x in zip(df["title"], df["text"])]
return out
def _load_news():
r = random.Random(2024) # fixed subsample stream (load is once)
rows = []
with open(DATA / "news_cat" / "News_Category_Dataset_v3.json",
encoding="utf-8") as fh:
for line in fh:
if r.random() >= 0.13: # ~27k subsample of 209k
continue
d = json.loads(line)
h = (d.get("headline") or "").strip()
if not h:
continue
cat = d.get("category") or "OTHER"
if cat == "THE WORLDPOST": # normalize: merge into WORLDPOST
cat = "WORLDPOST"
rows.append((h, (d.get("short_description") or "").strip(), cat))
# cap the option list: 10 most frequent categories + OTHER bucket
top = [c for c, _ in Counter(x[2] for x in rows).most_common(10)]
rows = [(h, s, c if c in top else "OTHER") for h, s, c in rows]
return {"rows": rows, "options": top + ["OTHER"]}
def _load_telco():
df = pd.read_csv(DATA / "telco_churn"
/ "WA_Fn-UseC_-Telco-Customer-Churn.csv")
# ~11 blank TotalCharges, all tenure==0 new customers -> 0.0
df["TotalCharges"] = pd.to_numeric(df["TotalCharges"],
errors="coerce").fillna(0.0)
df["churn"] = (df["Churn"] == "Yes").astype(float)
df["ten_band"] = pd.cut(df["tenure"], [-1, 12, 36, 60, 73],
labels=["0-12", "13-36", "37-60", "61+"])
feats = [c for c in df.columns
if c not in ("customerID", "Churn", "churn", "ten_band")]
return {"rows": df.to_dict("records"), "feats": feats,
"probs": _emp_binary(df, ["Contract", "ten_band"], "churn"),
"global": float(df["churn"].mean())}
def _load_heart():
df = pd.read_csv(DATA / "heart" / "heart.csv")
df["age_band"] = pd.cut(df["Age"], [0, 45, 55, 65, 120],
labels=["<=45", "46-55", "56-65", "66+"])
feats = [c for c in df.columns
if c not in ("HeartDisease", "age_band")]
return {"rows": df.to_dict("records"), "feats": feats,
"probs": _emp_binary(df, ["ChestPainType", "age_band"],
"HeartDisease"),
"global": float(df["HeartDisease"].mean())}
def _load_mushroom():
df = pd.read_csv(DATA / "mushroom" / "mushrooms.csv")
df["pois"] = (df["class"] == "p").astype(float)
# veil-type is constant -> drop; class/pois are labels, not features
feats = [c for c in df.columns
if c not in ("class", "veil-type", "pois")]
return {"rows": df.to_dict("records"), "feats": feats,
"probs": _emp_binary(df, ["gill-size", "gill-color"], "pois"),
"global": float(df["pois"].mean())}
def _load_cc():
df = pd.read_csv(DATA / "creditcard" / "creditcard.csv")
df["_amt"] = pd.cut(df["Amount"], [-1, 50, 200, 2000, float("inf")],
labels=["<=50", "51-200", "201-2000", "2000+"])
df["_v14"] = pd.cut(df["V14"], [-float("inf"), -4, -1, float("inf")],
labels=["<=-4", "-4..-1", ">-1"])
# SOFT targets must reflect the TRUE prevalence -> buckets over full df
probs = _emp_binary(df, ["_amt", "_v14"], "Class")
fraud = df[df["Class"] == 1].to_dict("records") # all 492
legit = df[df["Class"] == 0].sample(16000, random_state=7
).to_dict("records")
return {"fraud": fraud, "legit": legit, "probs": probs,
"global": float(df["Class"].mean())}
def _load_iris():
df = pd.read_csv(DATA / "iris" / "Iris.csv")
df["pet_band"] = pd.cut(df["PetalLengthCm"], [0, 2.5, 4.9, 7.0],
labels=["<=2.5", "2.5-4.9", ">4.9"])
return {"rows": df.to_dict("records"), "classes": IRIS_CLASSES,
"probs": _emp_multi(df, "pet_band", "Species", IRIS_CLASSES),
"uniform": [1.0 / 3.0] * 3}
_LOADERS = {"sms": _load_sms, "fakenews": _load_fakenews, "news": _load_news,
"telco": _load_telco, "heart": _load_heart,
"mushroom": _load_mushroom, "cc": _load_cc, "iris": _load_iris}
def _load(name):
if name not in _CACHE:
_CACHE[name] = _LOADERS[name]()
return _CACHE[name]
# ---------------------------------------------------------------------------
# text families
# ---------------------------------------------------------------------------
def gen_sms_spam():
rows = _load("sms")
text, y = rows[rng.randrange(len(rows))]
state = rng.choice([
"SMS message: {t}",
'Incoming text message: "{t}"',
"Message: {t}",
"Text received on this phone: {t}",
]).format(t=_trunc(text, 400))
instr, pol = rng.choice(_SPAM_Q)
qs = [q_noul("spam", instr, y if pol else 1.0 - y)] # DET
if rng.random() < 0.35:
qs.append(q_choice("cls", rng.choice([
"Classify this message.", "Spam or ham — which is it?"]),
["ham", "spam"], [1.0 - y, y])) # DET
return state, qs
def gen_fake_news():
rows = _load("fakenews")
title, text, y = rows[rng.randrange(len(rows))]
state = rng.choice([
"Title: {h}\n{b}",
"News article — {h}\n{b}",
'Headline: "{h}"\nArticle body: {b}',
]).format(h=_trunc(title, 160), b=_trunc(text, 600))
instr, pol = rng.choice(_FAKE_Q)
qs = [q_noul("fake", instr, y if pol else 1.0 - y)] # DET
if rng.random() < 0.30:
qs.append(q_choice("cls", "Is this article real or fake?",
["real", "fake"], [1.0 - y, y])) # DET
return state, qs
def gen_news_cat():
d = _load("news")
h, s, cat = d["rows"][rng.randrange(len(d["rows"]))]
opts = d["options"]
state = rng.choice([
"Headline: {h}\nSummary: {s}",
'Article: "{h}" — {s}',
"Headline: {h}\n{s}",
]).format(h=_trunc(h, 140), s=_trunc(s, 320) if s else "(no summary)")
t = [0.0] * len(opts) # DET one-hot
t[opts.index(cat)] = 1.0
qs = [q_choice("section", rng.choice(_NEWS_Q), opts, t)]
if rng.random() < 0.30: # DET probe
c = rng.choice(opts[:-1]) # real categories only (not OTHER)
qs.append(q_noul("is", f"Is this a {c} article?",
float(cat == c)))
return state, qs
# ---------------------------------------------------------------------------
# tabular families
# ---------------------------------------------------------------------------
def gen_telco():
d = _load("telco")
row = d["rows"][rng.randrange(len(d["rows"]))]
rec = {k: _clean(row[k]) for k in d["feats"]}
state = "Customer record: " + json.dumps(rec, ensure_ascii=False)
if rng.random() < 0.5:
p_churn = float(row["churn"]) # DET
else:
# SOFT: empirical P(churn | Contract x tenure-band), full dataset
p_churn = d["probs"].get(
(str(row["Contract"]), str(row["ten_band"])), d["global"])
instr, pol = rng.choice(_CHURN_Q)
qs = [q_noul("churn", instr, p_churn if pol else 1.0 - p_churn)]
if rng.random() < 0.4: # exact numeric threshold probe
if rng.random() < 0.5:
thr = rng.choice([30, 50, 70, 90])
qs.append(q_noul(
"mc", f"Is the monthly charge over ${thr}?",
float(row["MonthlyCharges"] > thr)))
else:
thr = rng.choice([12, 24, 48])
qs.append(q_noul(
"ten", f"Has this customer subscribed for over {thr} months?",
float(row["tenure"] > thr)))
if rng.random() < 0.2:
qs.append(q_choice("cls", "What will this customer do?",
["stay", "churn"],
[1.0 - p_churn, p_churn]))
return state, qs
def gen_heart():
d = _load("heart")
row = d["rows"][rng.randrange(len(d["rows"]))]
rec = {k: _clean(row[k]) for k in d["feats"]}
state = "Patient record: " + json.dumps(rec, ensure_ascii=False)
if rng.random() < 0.5:
p_hd = float(row["HeartDisease"]) # DET
else:
# SOFT: empirical P(heart disease | ChestPainType x age-band)
p_hd = d["probs"].get(
(str(row["ChestPainType"]), str(row["age_band"])),
d["global"])
instr, pol = rng.choice(_HEART_Q)
qs = [q_noul("hd", instr, p_hd if pol else 1.0 - p_hd)]
if rng.random() < 0.4: # exact numeric threshold probe
probe = rng.random()
if probe < 0.34:
thr = rng.choice([130, 140, 160])
qs.append(q_noul(
"bp", f"Is resting blood pressure above {thr} mm Hg?",
float(row["RestingBP"] > thr)))
elif probe < 0.67:
thr = rng.choice([200, 240, 300])
qs.append(q_noul(
"chol", f"Is serum cholesterol over {thr} mg/dl?",
float(row["Cholesterol"] > thr)))
else:
thr = rng.choice([120, 140, 160])
qs.append(q_noul(
"hr", f"Is the maximum heart rate under {thr} bpm?",
float(row["MaxHR"] < thr)))
if rng.random() < 0.2:
qs.append(q_choice("cls", "What is the cardiac assessment?",
["no disease", "heart disease"],
[1.0 - p_hd, p_hd]))
return state, qs
def gen_mushroom():
d = _load("mushroom")
row = d["rows"][rng.randrange(len(d["rows"]))]
rec = {k: _clean(row[k]) for k in d["feats"]}
state = ("Mushroom specimen (single-letter feature codes): "
+ json.dumps(rec, ensure_ascii=False))
if rng.random() < 0.5:
p_pois = float(row["pois"]) # DET
else:
# SOFT: empirical P(poisonous | gill-size x gill-color)
p_pois = d["probs"].get(
(str(row["gill-size"]), str(row["gill-color"])),
d["global"])
instr, pol = rng.choice(_MUSH_Q)
qs = [q_noul("pois", instr, p_pois if pol else 1.0 - p_pois)]
if rng.random() < 0.4: # exact feature-existence probe
probe = rng.random()
if probe < 0.34:
qs.append(q_noul(
"bruise", "Does this mushroom have bruises (code 't')?",
float(row["bruises"] == "t")))
elif probe < 0.67:
qs.append(q_noul(
"odor", "Is this mushroom odorless (odor code 'n')?",
float(row["odor"] == "n")))
else:
qs.append(q_noul(
"gill", "Is the gill size broad (code 'b')?",
float(row["gill-size"] == "b")))
if rng.random() < 0.2:
qs.append(q_choice("cls", "Classify this mushroom.",
["edible", "poisonous"],
[1.0 - p_pois, p_pois]))
return state, qs
def gen_creditcard():
d = _load("cc")
# oversample fraud so generated rows keep ~10-30% positives
pool = d["fraud"] if rng.random() < rng.uniform(0.10, 0.30) else d["legit"]
row = pool[rng.randrange(len(pool))]
rec = {k: _clean(row[k]) for k in CC_FEATS}
state = ("Card transaction (PCA-anonymized features V1-V28): "
+ json.dumps(rec, ensure_ascii=False))
if rng.random() < 0.5:
p_fraud = float(row["Class"]) # DET
else:
# SOFT: empirical P(fraud | Amount-band x V14-band), full dataset
p_fraud = d["probs"].get(
(str(row["_amt"]), str(row["_v14"])), d["global"])
instr, pol = rng.choice(_FRAUD_Q)
qs = [q_noul("fraud", instr, p_fraud if pol else 1.0 - p_fraud)]
if rng.random() < 0.4: # exact numeric threshold probe
thr = rng.choice([50, 100, 500, 1000])
qs.append(q_noul(
"amt", f"Is the transaction amount over ${thr}?",
float(row["Amount"] > thr)))
if rng.random() < 0.15: # feature probe on top predictor
qs.append(q_noul(
"v14", "Is V14 below -1 (anomalous component)?",
float(row["V14"] < -1)))
if rng.random() < 0.2:
qs.append(q_choice("cls", "How should this transaction be classified?",
["legitimate", "fraud"],
[1.0 - p_fraud, p_fraud]))
return state, qs
def gen_iris():
d = _load("iris")
row = d["rows"][rng.randrange(len(d["rows"]))]
rec = {k: _clean(row[k]) for k in IRIS_FEATS}
state = ("Iris specimen measurements (cm): "
+ json.dumps(rec, ensure_ascii=False))
species = row["Species"]
classes = d["classes"]
if rng.random() < 0.5:
t = [1.0 if c == species else 0.0 for c in classes] # DET one-hot
else:
# SOFT: empirical P(species | petal-length band)
t = d["probs"].get(str(row["pet_band"]), d["uniform"])
qs = [q_choice("species", rng.choice(_IRIS_Q), classes, t)]
if rng.random() < 0.4:
if rng.random() < 0.5: # exact numeric threshold probe
thr = rng.choice([3.0, 4.5, 5.0])
qs.append(q_noul(
"pl", f"Is the petal longer than {thr} cm?",
float(row["PetalLengthCm"] > thr)))
else: # DET species probe
c = rng.choice(classes)
qs.append(q_noul("issp", f"Is this specimen {c}?",
float(species == c)))
return state, qs
FAMILIES = {"sms_spam": gen_sms_spam, "fake_news": gen_fake_news,
"news_cat": gen_news_cat, "telco_churn": gen_telco,
"heart": gen_heart, "mushroom": gen_mushroom,
"creditcard": gen_creditcard, "iris": gen_iris}
WEIGHTS = {"sms_spam": 0.15, "fake_news": 0.13, "news_cat": 0.14,
"telco_churn": 0.15, "heart": 0.12, "mushroom": 0.12,
"creditcard": 0.14, "iris": 0.05}
def make_rows(n, seed):
return generate(FAMILIES, WEIGHTS, n, seed, rng)
if __name__ == "__main__":
rows = make_rows(10, 0)
for r in rows[:3]:
validate_row(r)
print(r["id"], "|", r["state"][:90])
print(f"{len(rows)} rows OK")