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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real Kaggle classification datasets -> decision-model rows.
|
| 2 |
+
|
| 3 |
+
Eight families, one per dataset (see data/kaggle/manifest.json). Files are
|
| 4 |
+
loaded lazily ONCE into a module-level cache (_load); subsampling and the
|
| 5 |
+
empirical bucket tables are also computed once at load time.
|
| 6 |
+
|
| 7 |
+
Row flavors (flagged in code):
|
| 8 |
+
DET - targets are the record's ground-truth label (0/1 or one-hot).
|
| 9 |
+
SOFT - targets are empirical P(label | bucket) computed over the FULL
|
| 10 |
+
dataset, bucketed by 1-2 strong features (+ Beta(1,1) smoothing).
|
| 11 |
+
|
| 12 |
+
Text families emit the text itself as state (optionally with a one-line task
|
| 13 |
+
prefix); tabular families serialize the record as a compact JSON dict.
|
| 14 |
+
"""
|
| 15 |
+
import json
|
| 16 |
+
import random
|
| 17 |
+
from collections import Counter
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import pandas as pd
|
| 21 |
+
|
| 22 |
+
from .genbase import (generate, emit, q_choice, q_noul, q_score, q_regress,
|
| 23 |
+
validate_row, write_jsonl)
|
| 24 |
+
|
| 25 |
+
rng = random.Random()
|
| 26 |
+
|
| 27 |
+
DATA = Path(__file__).resolve().parents[1] / "data" / "kaggle"
|
| 28 |
+
_CACHE = {}
|
| 29 |
+
|
| 30 |
+
CC_FEATS = ["Time"] + [f"V{i}" for i in range(1, 29)] + ["Amount"]
|
| 31 |
+
IRIS_FEATS = ["SepalLengthCm", "SepalWidthCm", "PetalLengthCm", "PetalWidthCm"]
|
| 32 |
+
IRIS_CLASSES = ["Iris-setosa", "Iris-versicolor", "Iris-virginica"]
|
| 33 |
+
|
| 34 |
+
# (instruction, polarity) pairs; polarity 1 means "yes" == positive label,
|
| 35 |
+
# 0 means the question is phrased on the negative class (target = 1 - p).
|
| 36 |
+
_SPAM_Q = [("Is this message spam?", 1),
|
| 37 |
+
("Is this SMS junk or spam?", 1),
|
| 38 |
+
("Should this text be filtered out as spam?", 1),
|
| 39 |
+
("Is this a normal personal message?", 0)]
|
| 40 |
+
_FAKE_Q = [("Is this article fake news?", 1),
|
| 41 |
+
("Is this news story fabricated?", 1),
|
| 42 |
+
("Was this article made up or intentionally false?", 1),
|
| 43 |
+
("Is this genuine, trustworthy reporting?", 0)]
|
| 44 |
+
_NEWS_Q = ["Which section does this article belong to?",
|
| 45 |
+
"Which news desk should handle this piece?",
|
| 46 |
+
"Pick the most appropriate category for this article.",
|
| 47 |
+
"Under which section should this article be filed?"]
|
| 48 |
+
_CHURN_Q = [("Will this customer churn?", 1),
|
| 49 |
+
("Is this customer likely to cancel their service?", 1),
|
| 50 |
+
("Will this account be lost to churn?", 1),
|
| 51 |
+
("Will this customer stay with the company?", 0)]
|
| 52 |
+
_HEART_Q = [("Does this patient have heart disease?", 1),
|
| 53 |
+
("Is heart disease present in this patient?", 1),
|
| 54 |
+
("Would a cardiologist flag this patient for heart disease?", 1),
|
| 55 |
+
("Is this patient's heart healthy?", 0)]
|
| 56 |
+
_MUSH_Q = [("Is this mushroom poisonous?", 1),
|
| 57 |
+
("Would eating this mushroom be dangerous?", 1),
|
| 58 |
+
("Is this mushroom toxic?", 1),
|
| 59 |
+
("Is this mushroom safe to eat?", 0)]
|
| 60 |
+
_FRAUD_Q = [("Is this transaction fraudulent?", 1),
|
| 61 |
+
("Should this transaction be flagged as fraud?", 1),
|
| 62 |
+
("Is this a fraudulent card transaction?", 1),
|
| 63 |
+
("Is this transaction legitimate?", 0)]
|
| 64 |
+
_IRIS_Q = ["Which iris species is this?",
|
| 65 |
+
"Identify the species of this iris specimen.",
|
| 66 |
+
"What species does this iris belong to?"]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ---------------------------------------------------------------------------
|
| 70 |
+
# helpers
|
| 71 |
+
# ---------------------------------------------------------------------------
|
| 72 |
+
|
| 73 |
+
def _trunc(s, n):
|
| 74 |
+
"""Collapse whitespace and keep the beginning of a long text."""
|
| 75 |
+
s = " ".join(str(s).split())
|
| 76 |
+
if len(s) <= n:
|
| 77 |
+
return s
|
| 78 |
+
return s[:n].rsplit(" ", 1)[0] + "..."
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _clean(v):
|
| 82 |
+
"""numpy scalar -> python; round floats; NaN -> None (for json.dumps)."""
|
| 83 |
+
if hasattr(v, "item"):
|
| 84 |
+
v = v.item()
|
| 85 |
+
if isinstance(v, float):
|
| 86 |
+
if v != v:
|
| 87 |
+
return None
|
| 88 |
+
return round(v, 4)
|
| 89 |
+
return v
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _emp_binary(df, keys, y):
|
| 93 |
+
"""{key-tuple: P(y==1 | bucket)} with Beta(1,1) smoothing, over full df."""
|
| 94 |
+
g = df.groupby(keys, observed=True)[y].agg(["sum", "count"])
|
| 95 |
+
out = {}
|
| 96 |
+
for k, r in g.iterrows():
|
| 97 |
+
kk = k if isinstance(k, tuple) else (k,)
|
| 98 |
+
out[tuple(str(x) for x in kk)] = float((r["sum"] + 1.0)
|
| 99 |
+
/ (r["count"] + 2.0))
|
| 100 |
+
return out
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _emp_multi(df, key, label, classes, prior=1.0):
|
| 104 |
+
"""{bucket: [P(label==c | bucket) for c in classes]} smoothed."""
|
| 105 |
+
ct = df.groupby(key, observed=True)[label].value_counts().unstack(
|
| 106 |
+
fill_value=0)
|
| 107 |
+
ct = ct.reindex(columns=classes, fill_value=0)
|
| 108 |
+
out = {}
|
| 109 |
+
for k, row in ct.iterrows():
|
| 110 |
+
tot = float(row.sum()) + prior * len(classes)
|
| 111 |
+
out[str(k)] = [float((row[c] + prior) / tot) for c in classes]
|
| 112 |
+
return out
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# ---------------------------------------------------------------------------
|
| 116 |
+
# lazy loaders — each file is read ONCE per process
|
| 117 |
+
# ---------------------------------------------------------------------------
|
| 118 |
+
|
| 119 |
+
def _load_sms():
|
| 120 |
+
df = pd.read_csv(DATA / "sms_spam" / "spam.csv", encoding="latin-1",
|
| 121 |
+
usecols=["v1", "v2"]).dropna(subset=["v2"])
|
| 122 |
+
return [(str(t), float(l == "spam"))
|
| 123 |
+
for l, t in zip(df["v1"], df["v2"])]
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _load_fakenews():
|
| 127 |
+
out = []
|
| 128 |
+
for fn, y in (("Fake.csv", 1.0), ("True.csv", 0.0)):
|
| 129 |
+
df = pd.read_csv(DATA / "fake_news" / fn)
|
| 130 |
+
# ~631 rows have empty body text — skip them
|
| 131 |
+
df = df[df["text"].astype(str).str.strip().str.len() > 0]
|
| 132 |
+
out += [(str(t), str(x), y)
|
| 133 |
+
for t, x in zip(df["title"], df["text"])]
|
| 134 |
+
return out
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _load_news():
|
| 138 |
+
r = random.Random(2024) # fixed subsample stream (load is once)
|
| 139 |
+
rows = []
|
| 140 |
+
with open(DATA / "news_cat" / "News_Category_Dataset_v3.json",
|
| 141 |
+
encoding="utf-8") as fh:
|
| 142 |
+
for line in fh:
|
| 143 |
+
if r.random() >= 0.13: # ~27k subsample of 209k
|
| 144 |
+
continue
|
| 145 |
+
d = json.loads(line)
|
| 146 |
+
h = (d.get("headline") or "").strip()
|
| 147 |
+
if not h:
|
| 148 |
+
continue
|
| 149 |
+
cat = d.get("category") or "OTHER"
|
| 150 |
+
if cat == "THE WORLDPOST": # normalize: merge into WORLDPOST
|
| 151 |
+
cat = "WORLDPOST"
|
| 152 |
+
rows.append((h, (d.get("short_description") or "").strip(), cat))
|
| 153 |
+
# cap the option list: 10 most frequent categories + OTHER bucket
|
| 154 |
+
top = [c for c, _ in Counter(x[2] for x in rows).most_common(10)]
|
| 155 |
+
rows = [(h, s, c if c in top else "OTHER") for h, s, c in rows]
|
| 156 |
+
return {"rows": rows, "options": top + ["OTHER"]}
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _load_telco():
|
| 160 |
+
df = pd.read_csv(DATA / "telco_churn"
|
| 161 |
+
/ "WA_Fn-UseC_-Telco-Customer-Churn.csv")
|
| 162 |
+
# ~11 blank TotalCharges, all tenure==0 new customers -> 0.0
|
| 163 |
+
df["TotalCharges"] = pd.to_numeric(df["TotalCharges"],
|
| 164 |
+
errors="coerce").fillna(0.0)
|
| 165 |
+
df["churn"] = (df["Churn"] == "Yes").astype(float)
|
| 166 |
+
df["ten_band"] = pd.cut(df["tenure"], [-1, 12, 36, 60, 73],
|
| 167 |
+
labels=["0-12", "13-36", "37-60", "61+"])
|
| 168 |
+
feats = [c for c in df.columns
|
| 169 |
+
if c not in ("customerID", "Churn", "churn", "ten_band")]
|
| 170 |
+
return {"rows": df.to_dict("records"), "feats": feats,
|
| 171 |
+
"probs": _emp_binary(df, ["Contract", "ten_band"], "churn"),
|
| 172 |
+
"global": float(df["churn"].mean())}
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _load_heart():
|
| 176 |
+
df = pd.read_csv(DATA / "heart" / "heart.csv")
|
| 177 |
+
df["age_band"] = pd.cut(df["Age"], [0, 45, 55, 65, 120],
|
| 178 |
+
labels=["<=45", "46-55", "56-65", "66+"])
|
| 179 |
+
feats = [c for c in df.columns
|
| 180 |
+
if c not in ("HeartDisease", "age_band")]
|
| 181 |
+
return {"rows": df.to_dict("records"), "feats": feats,
|
| 182 |
+
"probs": _emp_binary(df, ["ChestPainType", "age_band"],
|
| 183 |
+
"HeartDisease"),
|
| 184 |
+
"global": float(df["HeartDisease"].mean())}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _load_mushroom():
|
| 188 |
+
df = pd.read_csv(DATA / "mushroom" / "mushrooms.csv")
|
| 189 |
+
df["pois"] = (df["class"] == "p").astype(float)
|
| 190 |
+
# veil-type is constant -> drop; class/pois are labels, not features
|
| 191 |
+
feats = [c for c in df.columns
|
| 192 |
+
if c not in ("class", "veil-type", "pois")]
|
| 193 |
+
return {"rows": df.to_dict("records"), "feats": feats,
|
| 194 |
+
"probs": _emp_binary(df, ["gill-size", "gill-color"], "pois"),
|
| 195 |
+
"global": float(df["pois"].mean())}
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _load_cc():
|
| 199 |
+
df = pd.read_csv(DATA / "creditcard" / "creditcard.csv")
|
| 200 |
+
df["_amt"] = pd.cut(df["Amount"], [-1, 50, 200, 2000, float("inf")],
|
| 201 |
+
labels=["<=50", "51-200", "201-2000", "2000+"])
|
| 202 |
+
df["_v14"] = pd.cut(df["V14"], [-float("inf"), -4, -1, float("inf")],
|
| 203 |
+
labels=["<=-4", "-4..-1", ">-1"])
|
| 204 |
+
# SOFT targets must reflect the TRUE prevalence -> buckets over full df
|
| 205 |
+
probs = _emp_binary(df, ["_amt", "_v14"], "Class")
|
| 206 |
+
fraud = df[df["Class"] == 1].to_dict("records") # all 492
|
| 207 |
+
legit = df[df["Class"] == 0].sample(16000, random_state=7
|
| 208 |
+
).to_dict("records")
|
| 209 |
+
return {"fraud": fraud, "legit": legit, "probs": probs,
|
| 210 |
+
"global": float(df["Class"].mean())}
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _load_iris():
|
| 214 |
+
df = pd.read_csv(DATA / "iris" / "Iris.csv")
|
| 215 |
+
df["pet_band"] = pd.cut(df["PetalLengthCm"], [0, 2.5, 4.9, 7.0],
|
| 216 |
+
labels=["<=2.5", "2.5-4.9", ">4.9"])
|
| 217 |
+
return {"rows": df.to_dict("records"), "classes": IRIS_CLASSES,
|
| 218 |
+
"probs": _emp_multi(df, "pet_band", "Species", IRIS_CLASSES),
|
| 219 |
+
"uniform": [1.0 / 3.0] * 3}
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
_LOADERS = {"sms": _load_sms, "fakenews": _load_fakenews, "news": _load_news,
|
| 223 |
+
"telco": _load_telco, "heart": _load_heart,
|
| 224 |
+
"mushroom": _load_mushroom, "cc": _load_cc, "iris": _load_iris}
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def _load(name):
|
| 228 |
+
if name not in _CACHE:
|
| 229 |
+
_CACHE[name] = _LOADERS[name]()
|
| 230 |
+
return _CACHE[name]
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------------------
|
| 234 |
+
# text families
|
| 235 |
+
# ---------------------------------------------------------------------------
|
| 236 |
+
|
| 237 |
+
def gen_sms_spam():
|
| 238 |
+
rows = _load("sms")
|
| 239 |
+
text, y = rows[rng.randrange(len(rows))]
|
| 240 |
+
state = rng.choice([
|
| 241 |
+
"SMS message: {t}",
|
| 242 |
+
'Incoming text message: "{t}"',
|
| 243 |
+
"Message: {t}",
|
| 244 |
+
"Text received on this phone: {t}",
|
| 245 |
+
]).format(t=_trunc(text, 400))
|
| 246 |
+
instr, pol = rng.choice(_SPAM_Q)
|
| 247 |
+
qs = [q_noul("spam", instr, y if pol else 1.0 - y)] # DET
|
| 248 |
+
if rng.random() < 0.35:
|
| 249 |
+
qs.append(q_choice("cls", rng.choice([
|
| 250 |
+
"Classify this message.", "Spam or ham — which is it?"]),
|
| 251 |
+
["ham", "spam"], [1.0 - y, y])) # DET
|
| 252 |
+
return state, qs
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def gen_fake_news():
|
| 256 |
+
rows = _load("fakenews")
|
| 257 |
+
title, text, y = rows[rng.randrange(len(rows))]
|
| 258 |
+
state = rng.choice([
|
| 259 |
+
"Title: {h}\n{b}",
|
| 260 |
+
"News article — {h}\n{b}",
|
| 261 |
+
'Headline: "{h}"\nArticle body: {b}',
|
| 262 |
+
]).format(h=_trunc(title, 160), b=_trunc(text, 600))
|
| 263 |
+
instr, pol = rng.choice(_FAKE_Q)
|
| 264 |
+
qs = [q_noul("fake", instr, y if pol else 1.0 - y)] # DET
|
| 265 |
+
if rng.random() < 0.30:
|
| 266 |
+
qs.append(q_choice("cls", "Is this article real or fake?",
|
| 267 |
+
["real", "fake"], [1.0 - y, y])) # DET
|
| 268 |
+
return state, qs
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def gen_news_cat():
|
| 272 |
+
d = _load("news")
|
| 273 |
+
h, s, cat = d["rows"][rng.randrange(len(d["rows"]))]
|
| 274 |
+
opts = d["options"]
|
| 275 |
+
state = rng.choice([
|
| 276 |
+
"Headline: {h}\nSummary: {s}",
|
| 277 |
+
'Article: "{h}" — {s}',
|
| 278 |
+
"Headline: {h}\n{s}",
|
| 279 |
+
]).format(h=_trunc(h, 140), s=_trunc(s, 320) if s else "(no summary)")
|
| 280 |
+
t = [0.0] * len(opts) # DET one-hot
|
| 281 |
+
t[opts.index(cat)] = 1.0
|
| 282 |
+
qs = [q_choice("section", rng.choice(_NEWS_Q), opts, t)]
|
| 283 |
+
if rng.random() < 0.30: # DET probe
|
| 284 |
+
c = rng.choice(opts[:-1]) # real categories only (not OTHER)
|
| 285 |
+
qs.append(q_noul("is", f"Is this a {c} article?",
|
| 286 |
+
float(cat == c)))
|
| 287 |
+
return state, qs
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
# ---------------------------------------------------------------------------
|
| 291 |
+
# tabular families
|
| 292 |
+
# ---------------------------------------------------------------------------
|
| 293 |
+
|
| 294 |
+
def gen_telco():
|
| 295 |
+
d = _load("telco")
|
| 296 |
+
row = d["rows"][rng.randrange(len(d["rows"]))]
|
| 297 |
+
rec = {k: _clean(row[k]) for k in d["feats"]}
|
| 298 |
+
state = "Customer record: " + json.dumps(rec, ensure_ascii=False)
|
| 299 |
+
if rng.random() < 0.5:
|
| 300 |
+
p_churn = float(row["churn"]) # DET
|
| 301 |
+
else:
|
| 302 |
+
# SOFT: empirical P(churn | Contract x tenure-band), full dataset
|
| 303 |
+
p_churn = d["probs"].get(
|
| 304 |
+
(str(row["Contract"]), str(row["ten_band"])), d["global"])
|
| 305 |
+
instr, pol = rng.choice(_CHURN_Q)
|
| 306 |
+
qs = [q_noul("churn", instr, p_churn if pol else 1.0 - p_churn)]
|
| 307 |
+
if rng.random() < 0.4: # exact numeric threshold probe
|
| 308 |
+
if rng.random() < 0.5:
|
| 309 |
+
thr = rng.choice([30, 50, 70, 90])
|
| 310 |
+
qs.append(q_noul(
|
| 311 |
+
"mc", f"Is the monthly charge over ${thr}?",
|
| 312 |
+
float(row["MonthlyCharges"] > thr)))
|
| 313 |
+
else:
|
| 314 |
+
thr = rng.choice([12, 24, 48])
|
| 315 |
+
qs.append(q_noul(
|
| 316 |
+
"ten", f"Has this customer subscribed for over {thr} months?",
|
| 317 |
+
float(row["tenure"] > thr)))
|
| 318 |
+
if rng.random() < 0.2:
|
| 319 |
+
qs.append(q_choice("cls", "What will this customer do?",
|
| 320 |
+
["stay", "churn"],
|
| 321 |
+
[1.0 - p_churn, p_churn]))
|
| 322 |
+
return state, qs
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def gen_heart():
|
| 326 |
+
d = _load("heart")
|
| 327 |
+
row = d["rows"][rng.randrange(len(d["rows"]))]
|
| 328 |
+
rec = {k: _clean(row[k]) for k in d["feats"]}
|
| 329 |
+
state = "Patient record: " + json.dumps(rec, ensure_ascii=False)
|
| 330 |
+
if rng.random() < 0.5:
|
| 331 |
+
p_hd = float(row["HeartDisease"]) # DET
|
| 332 |
+
else:
|
| 333 |
+
# SOFT: empirical P(heart disease | ChestPainType x age-band)
|
| 334 |
+
p_hd = d["probs"].get(
|
| 335 |
+
(str(row["ChestPainType"]), str(row["age_band"])),
|
| 336 |
+
d["global"])
|
| 337 |
+
instr, pol = rng.choice(_HEART_Q)
|
| 338 |
+
qs = [q_noul("hd", instr, p_hd if pol else 1.0 - p_hd)]
|
| 339 |
+
if rng.random() < 0.4: # exact numeric threshold probe
|
| 340 |
+
probe = rng.random()
|
| 341 |
+
if probe < 0.34:
|
| 342 |
+
thr = rng.choice([130, 140, 160])
|
| 343 |
+
qs.append(q_noul(
|
| 344 |
+
"bp", f"Is resting blood pressure above {thr} mm Hg?",
|
| 345 |
+
float(row["RestingBP"] > thr)))
|
| 346 |
+
elif probe < 0.67:
|
| 347 |
+
thr = rng.choice([200, 240, 300])
|
| 348 |
+
qs.append(q_noul(
|
| 349 |
+
"chol", f"Is serum cholesterol over {thr} mg/dl?",
|
| 350 |
+
float(row["Cholesterol"] > thr)))
|
| 351 |
+
else:
|
| 352 |
+
thr = rng.choice([120, 140, 160])
|
| 353 |
+
qs.append(q_noul(
|
| 354 |
+
"hr", f"Is the maximum heart rate under {thr} bpm?",
|
| 355 |
+
float(row["MaxHR"] < thr)))
|
| 356 |
+
if rng.random() < 0.2:
|
| 357 |
+
qs.append(q_choice("cls", "What is the cardiac assessment?",
|
| 358 |
+
["no disease", "heart disease"],
|
| 359 |
+
[1.0 - p_hd, p_hd]))
|
| 360 |
+
return state, qs
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def gen_mushroom():
|
| 364 |
+
d = _load("mushroom")
|
| 365 |
+
row = d["rows"][rng.randrange(len(d["rows"]))]
|
| 366 |
+
rec = {k: _clean(row[k]) for k in d["feats"]}
|
| 367 |
+
state = ("Mushroom specimen (single-letter feature codes): "
|
| 368 |
+
+ json.dumps(rec, ensure_ascii=False))
|
| 369 |
+
if rng.random() < 0.5:
|
| 370 |
+
p_pois = float(row["pois"]) # DET
|
| 371 |
+
else:
|
| 372 |
+
# SOFT: empirical P(poisonous | gill-size x gill-color)
|
| 373 |
+
p_pois = d["probs"].get(
|
| 374 |
+
(str(row["gill-size"]), str(row["gill-color"])),
|
| 375 |
+
d["global"])
|
| 376 |
+
instr, pol = rng.choice(_MUSH_Q)
|
| 377 |
+
qs = [q_noul("pois", instr, p_pois if pol else 1.0 - p_pois)]
|
| 378 |
+
if rng.random() < 0.4: # exact feature-existence probe
|
| 379 |
+
probe = rng.random()
|
| 380 |
+
if probe < 0.34:
|
| 381 |
+
qs.append(q_noul(
|
| 382 |
+
"bruise", "Does this mushroom have bruises (code 't')?",
|
| 383 |
+
float(row["bruises"] == "t")))
|
| 384 |
+
elif probe < 0.67:
|
| 385 |
+
qs.append(q_noul(
|
| 386 |
+
"odor", "Is this mushroom odorless (odor code 'n')?",
|
| 387 |
+
float(row["odor"] == "n")))
|
| 388 |
+
else:
|
| 389 |
+
qs.append(q_noul(
|
| 390 |
+
"gill", "Is the gill size broad (code 'b')?",
|
| 391 |
+
float(row["gill-size"] == "b")))
|
| 392 |
+
if rng.random() < 0.2:
|
| 393 |
+
qs.append(q_choice("cls", "Classify this mushroom.",
|
| 394 |
+
["edible", "poisonous"],
|
| 395 |
+
[1.0 - p_pois, p_pois]))
|
| 396 |
+
return state, qs
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def gen_creditcard():
|
| 400 |
+
d = _load("cc")
|
| 401 |
+
# oversample fraud so generated rows keep ~10-30% positives
|
| 402 |
+
pool = d["fraud"] if rng.random() < rng.uniform(0.10, 0.30) else d["legit"]
|
| 403 |
+
row = pool[rng.randrange(len(pool))]
|
| 404 |
+
rec = {k: _clean(row[k]) for k in CC_FEATS}
|
| 405 |
+
state = ("Card transaction (PCA-anonymized features V1-V28): "
|
| 406 |
+
+ json.dumps(rec, ensure_ascii=False))
|
| 407 |
+
if rng.random() < 0.5:
|
| 408 |
+
p_fraud = float(row["Class"]) # DET
|
| 409 |
+
else:
|
| 410 |
+
# SOFT: empirical P(fraud | Amount-band x V14-band), full dataset
|
| 411 |
+
p_fraud = d["probs"].get(
|
| 412 |
+
(str(row["_amt"]), str(row["_v14"])), d["global"])
|
| 413 |
+
instr, pol = rng.choice(_FRAUD_Q)
|
| 414 |
+
qs = [q_noul("fraud", instr, p_fraud if pol else 1.0 - p_fraud)]
|
| 415 |
+
if rng.random() < 0.4: # exact numeric threshold probe
|
| 416 |
+
thr = rng.choice([50, 100, 500, 1000])
|
| 417 |
+
qs.append(q_noul(
|
| 418 |
+
"amt", f"Is the transaction amount over ${thr}?",
|
| 419 |
+
float(row["Amount"] > thr)))
|
| 420 |
+
if rng.random() < 0.15: # feature probe on top predictor
|
| 421 |
+
qs.append(q_noul(
|
| 422 |
+
"v14", "Is V14 below -1 (anomalous component)?",
|
| 423 |
+
float(row["V14"] < -1)))
|
| 424 |
+
if rng.random() < 0.2:
|
| 425 |
+
qs.append(q_choice("cls", "How should this transaction be classified?",
|
| 426 |
+
["legitimate", "fraud"],
|
| 427 |
+
[1.0 - p_fraud, p_fraud]))
|
| 428 |
+
return state, qs
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
def gen_iris():
|
| 432 |
+
d = _load("iris")
|
| 433 |
+
row = d["rows"][rng.randrange(len(d["rows"]))]
|
| 434 |
+
rec = {k: _clean(row[k]) for k in IRIS_FEATS}
|
| 435 |
+
state = ("Iris specimen measurements (cm): "
|
| 436 |
+
+ json.dumps(rec, ensure_ascii=False))
|
| 437 |
+
species = row["Species"]
|
| 438 |
+
classes = d["classes"]
|
| 439 |
+
if rng.random() < 0.5:
|
| 440 |
+
t = [1.0 if c == species else 0.0 for c in classes] # DET one-hot
|
| 441 |
+
else:
|
| 442 |
+
# SOFT: empirical P(species | petal-length band)
|
| 443 |
+
t = d["probs"].get(str(row["pet_band"]), d["uniform"])
|
| 444 |
+
qs = [q_choice("species", rng.choice(_IRIS_Q), classes, t)]
|
| 445 |
+
if rng.random() < 0.4:
|
| 446 |
+
if rng.random() < 0.5: # exact numeric threshold probe
|
| 447 |
+
thr = rng.choice([3.0, 4.5, 5.0])
|
| 448 |
+
qs.append(q_noul(
|
| 449 |
+
"pl", f"Is the petal longer than {thr} cm?",
|
| 450 |
+
float(row["PetalLengthCm"] > thr)))
|
| 451 |
+
else: # DET species probe
|
| 452 |
+
c = rng.choice(classes)
|
| 453 |
+
qs.append(q_noul("issp", f"Is this specimen {c}?",
|
| 454 |
+
float(species == c)))
|
| 455 |
+
return state, qs
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
FAMILIES = {"sms_spam": gen_sms_spam, "fake_news": gen_fake_news,
|
| 459 |
+
"news_cat": gen_news_cat, "telco_churn": gen_telco,
|
| 460 |
+
"heart": gen_heart, "mushroom": gen_mushroom,
|
| 461 |
+
"creditcard": gen_creditcard, "iris": gen_iris}
|
| 462 |
+
WEIGHTS = {"sms_spam": 0.15, "fake_news": 0.13, "news_cat": 0.14,
|
| 463 |
+
"telco_churn": 0.15, "heart": 0.12, "mushroom": 0.12,
|
| 464 |
+
"creditcard": 0.14, "iris": 0.05}
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def make_rows(n, seed):
|
| 468 |
+
return generate(FAMILIES, WEIGHTS, n, seed, rng)
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
if __name__ == "__main__":
|
| 472 |
+
rows = make_rows(10, 0)
|
| 473 |
+
for r in rows[:3]:
|
| 474 |
+
validate_row(r)
|
| 475 |
+
print(r["id"], "|", r["state"][:90])
|
| 476 |
+
print(f"{len(rows)} rows OK")
|