File size: 12,565 Bytes
a144c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
"""Real-data REGRESSION families — empirical conditional quantile targets.

Each row is a real record from a Kaggle tabular regression dataset
serialized WITHOUT its label (compact feature JSON). The regress target
is the empirical conditional distribution of the label given the record's
strongest covariates, estimated by grouped binning: the 19 quantiles at
taus .05-.95 come from the bin's own sample (linear interpolation). Bins
with < MIN_N members fall back along a coarsening chain — drop the weakest
conditioning feature, then the next, ending at the global marginal — so
targets are always honest empirical conditionals, never fabricated.

~30% of rows add a noul "is y above X?" with X a round number near the bin
median (target = exact P(y>X|bin) off the empirical CDF); ~20% add a
choice over value bands (target = empirical conditional over the bands).

CSV files are loaded once each and cached at module level (lazy on first
family call so `gen_all --list` stays cheap).
"""
import json
import random
from pathlib import Path

import numpy as np
import pandas as pd

from alea.genbase import (generate, emit, q_choice, q_noul, q_score,
                          q_regress, validate_row, write_jsonl)

rng = random.Random()

KAGGLE = Path(__file__).resolve().parents[1] / "data" / "kaggle"
TAUS = [0.05 * (i + 1) for i in range(19)]
MIN_N = 20      # smallest trusted bin; below -> coarser conditioning
P_NOUL = 0.30   # share of rows that also carry a threshold noul
P_BAND = 0.20   # share of rows that also carry a band choice


# ---------- empirical-conditional machinery ----------
def _build(df, bin_cols, y_col):
    """Return (keys, levels): keys[i] is the full bin tuple of row i;
    levels[L] maps a length-L key prefix to the sorted label sample of
    that bin. levels[0][()] is the global marginal."""
    y = df[y_col].to_numpy(dtype=float)
    keys = list(zip(*[df[c].tolist() for c in bin_cols]))
    levels = {0: {(): np.sort(y)}}
    for L in range(1, len(bin_cols) + 1):
        d = {}
        for k, v in zip(keys, y):
            d.setdefault(k[:L], []).append(v)
        levels[L] = {k: np.sort(np.asarray(v)) for k, v in d.items()}
    return keys, levels


def _sample(levels, key, min_n=MIN_N):
    """Sorted label sample of the finest trusted bin along key's prefix
    chain: full key -> drop weakest feature -> ... -> global marginal."""
    for L in range(len(key), 0, -1):
        arr = levels[L].get(tuple(key[:L]))
        if arr is not None and len(arr) >= min_n:
            return arr
    return levels[0][()]


def _q19(arr):
    """19 empirical quantiles at TAUS, linear interpolation, 3 decimals."""
    return [round(float(v), 3) for v in np.quantile(arr, TAUS)]


def _cdf_gt(arr, x):
    """Empirical P(y > x): one minus the sample fraction <= x."""
    return float(1.0 - np.searchsorted(arr, x, side="right") / len(arr))


def _band_probs(arr, edges):
    """Empirical P(y in band) over (-inf,e0),[e0,e1),...,[eK,+inf)."""
    c = [float(np.searchsorted(arr, e, side="right")) / len(arr)
         for e in edges]
    ps, prev = [], 0.0
    for x in c + [1.0]:
        ps.append(max(0.0, x - prev))
        prev = x
    s = sum(ps) or 1.0
    ps = [round(p / s, 4) for p in ps]
    ps[-1] = round(max(0.0, 1.0 - sum(ps[:-1])), 4)
    return ps


def _near(x, step):
    """Round number within about one step of x."""
    return int(round(x / step)) * step + rng.choice([-1, 0, 0, 0, 1]) * step


def _num(v, nd=1):
    """Compact float for state JSON: drop trailing .0, cap decimals."""
    f = round(float(v), nd)
    i = int(f)
    return i if f == i else f


# ---------- dataset loaders (module-level cache) ----------
_CACHE = {}


def _house_data():
    if "house" not in _CACHE:
        df = pd.read_csv(KAGGLE / "house" / "kc_house_data.csv")
        df["_sqft"] = pd.qcut(df["sqft_living"], 10, labels=False,
                              duplicates="drop")
        df["_grade"] = pd.cut(df["grade"], [0, 6, 8, 10, 13], labels=False)
        keys, lv = _build(df, ["_sqft", "_grade"], "price")
        _CACHE["house"] = (df, keys, lv)
    return _CACHE["house"]


def _ins_data():
    if "ins" not in _CACHE:
        df = pd.read_csv(KAGGLE / "insurance" / "insurance.csv")
        df["_bmi"] = pd.cut(df["bmi"], [0, 25, 30, np.inf], labels=False)
        df["_age"] = pd.cut(df["age"], [0, 30, 45, np.inf], labels=False)
        keys, lv = _build(df, ["smoker", "_bmi", "_age"], "charges")
        _CACHE["ins"] = (df, keys, lv)
    return _CACHE["ins"]


def _housing_data():
    if "housing" not in _CACHE:
        df = pd.read_csv(KAGGLE / "housing" / "Housing.csv")
        df["_area"] = pd.qcut(df["area"], 5, labels=False,
                              duplicates="drop")
        keys, lv = _build(df, ["_area", "furnishingstatus"], "price")
        _CACHE["housing"] = (df, keys, lv)
    return _CACHE["housing"]


LIFE_FEATS = ["Adult Mortality", "infant deaths", "Alcohol", "BMI",
              "under-five deaths", "Polio", "Diphtheria", "HIV/AIDS", "GDP",
              "Income composition of resources", "Schooling"]


def _life_data():
    if "life" not in _CACHE:
        df = pd.read_csv(KAGGLE / "life_exp" / "Life Expectancy Data.csv")
        df.columns = [c.strip() for c in df.columns]  # stray spaces
        df = df.dropna(subset=["Life expectancy"]).reset_index(drop=True)
        for c in LIFE_FEATS:
            df[c] = df[c].fillna(df[c].median())
        df["_am"] = pd.qcut(df["Adult Mortality"], 4, labels=False,
                            duplicates="drop")
        df["_sch"] = pd.qcut(df["Schooling"], 4, labels=False,
                             duplicates="drop")
        keys, lv = _build(df, ["Status", "_am", "_sch"], "Life expectancy")
        _CACHE["life"] = (df, keys, lv)
    return _CACHE["life"]


# ---------- families ----------
HOUSE_INSTR = [
    "Estimate the distribution of this home's sale price.",
    "What sale price will this King County property fetch?",
    "Predict the final selling price of this house.",
]
HOUSE_NOUL = ["Is the sale price above ${x:,}?",
              "Will the home sell for more than ${x:,}?"]


def gen_kc_house_price():
    df, keys, lv = _house_data()
    i = rng.randrange(len(df))
    r = df.iloc[i]
    arr = _sample(lv, keys[i])
    state = json.dumps({
        "bedrooms": int(r["bedrooms"]),
        "bathrooms": float(r["bathrooms"]),
        "sqft_living": int(r["sqft_living"]),
        "sqft_lot": int(r["sqft_lot"]),
        "floors": float(r["floors"]),
        "waterfront": int(r["waterfront"]),
        "view": int(r["view"]),
        "condition": int(r["condition"]),
        "grade": int(r["grade"]),
        "yr_built": int(r["yr_built"]),
        "zipcode": str(r["zipcode"])}, separators=(",", ":"))
    qs = [q_regress("price", rng.choice(HOUSE_INSTR), _q19(arr),
                    unit="dollars")]
    if rng.random() < P_NOUL:
        thr = _near(arr[len(arr) // 2], 50000)
        qs.append(q_noul("above", rng.choice(HOUSE_NOUL).format(x=thr),
                         _cdf_gt(arr, thr)))
    if rng.random() < P_BAND:
        qs.append(q_choice(
            "band", "Which band does the sale price fall in?",
            ["under $200k", "$200k-$400k", "$400k-$800k", "over $800k"],
            _band_probs(arr, [200000, 400000, 800000])))
    return state, qs


INS_INSTR = [
    "Estimate the distribution of annual medical charges for this person.",
    "What will this policyholder's medical insurance charges be?",
    "Predict the yearly insurance charges for this individual.",
]
INS_NOUL = ["Are the charges above ${x:,}?",
            "Will the medical charges exceed ${x:,}?"]


def gen_insurance_charges():
    df, keys, lv = _ins_data()
    i = rng.randrange(len(df))
    r = df.iloc[i]
    arr = _sample(lv, keys[i])
    state = json.dumps({
        "age": int(r["age"]), "sex": r["sex"], "bmi": _num(r["bmi"]),
        "children": int(r["children"]), "smoker": r["smoker"],
        "region": r["region"]}, separators=(",", ":"))
    qs = [q_regress("charges", rng.choice(INS_INSTR), _q19(arr),
                    unit="dollars")]
    if rng.random() < P_NOUL:
        thr = _near(arr[len(arr) // 2], 5000)
        qs.append(q_noul("above", rng.choice(INS_NOUL).format(x=thr),
                         _cdf_gt(arr, thr)))
    if rng.random() < P_BAND:
        qs.append(q_choice(
            "band", "Which band do the annual charges fall in?",
            ["under $5k", "$5k-$15k", "$15k-$30k", "over $30k"],
            _band_probs(arr, [5000, 15000, 30000])))
    return state, qs


HOUSING_INSTR = [
    "Estimate the distribution of this home's asking price.",
    "What price will this house sell for?",
    "Predict the sale price of this property.",
]
HOUSING_NOUL = ["Is the asking price above ${x:,}?",
                "Will the price exceed ${x:,}?"]


def gen_housing_price():
    df, keys, lv = _housing_data()
    i = rng.randrange(len(df))
    r = df.iloc[i]
    arr = _sample(lv, keys[i])
    state = json.dumps({
        "area": int(r["area"]), "bedrooms": int(r["bedrooms"]),
        "bathrooms": int(r["bathrooms"]), "stories": int(r["stories"]),
        "mainroad": r["mainroad"], "guestroom": r["guestroom"],
        "basement": r["basement"],
        "hotwaterheating": r["hotwaterheating"],
        "airconditioning": r["airconditioning"],
        "parking": int(r["parking"]), "prefarea": r["prefarea"],
        "furnishingstatus": r["furnishingstatus"]},
        separators=(",", ":"))
    qs = [q_regress("price", rng.choice(HOUSING_INSTR), _q19(arr),
                    unit="dollars")]
    if rng.random() < P_NOUL:
        thr = _near(arr[len(arr) // 2], 500000)
        qs.append(q_noul("above", rng.choice(HOUSING_NOUL).format(x=thr),
                         _cdf_gt(arr, thr)))
    if rng.random() < P_BAND:
        qs.append(q_choice(
            "band", "Which price band does this home fall in?",
            ["under $3.5M", "$3.5M-$5M", "$5M-$7M", "over $7M"],
            _band_probs(arr, [3500000, 5000000, 7000000])))
    return state, qs


LIFE_INSTR = [
    "Estimate the distribution of life expectancy for this country-year.",
    "What life expectancy at birth would you predict under these "
    "conditions?",
    "Predict the life expectancy for this country and year.",
]
LIFE_NOUL = ["Is life expectancy above {x} years?",
             "Will life expectancy exceed {x} years?"]


def gen_life_expectancy():
    df, keys, lv = _life_data()
    i = rng.randrange(len(df))
    r = df.iloc[i]
    arr = _sample(lv, keys[i])
    state = json.dumps({
        "Country": r["Country"], "Year": int(r["Year"]),
        "Status": r["Status"],
        "Adult Mortality": _num(r["Adult Mortality"], 0),
        "infant deaths": _num(r["infant deaths"], 0),
        "Alcohol": _num(r["Alcohol"], 2),
        "BMI": _num(r["BMI"]),
        "under-five deaths": _num(r["under-five deaths"], 0),
        "Polio": _num(r["Polio"]),
        "Diphtheria": _num(r["Diphtheria"]),
        "HIV/AIDS": _num(r["HIV/AIDS"]),
        "GDP": _num(r["GDP"], 0),
        "Income composition": _num(r["Income composition of resources"], 2),
        "Schooling": _num(r["Schooling"])}, separators=(",", ":"))
    qs = [q_regress("lifexp", rng.choice(LIFE_INSTR), _q19(arr),
                    unit="years")]
    if rng.random() < P_NOUL:
        thr = _near(arr[len(arr) // 2], 5)
        qs.append(q_noul("above", rng.choice(LIFE_NOUL).format(x=thr),
                         _cdf_gt(arr, thr)))
    if rng.random() < P_BAND:
        qs.append(q_choice(
            "band", "Which life-expectancy band applies?",
            ["under 60 years", "60-70 years", "70-77 years",
             "over 77 years"],
            _band_probs(arr, [60, 70, 77])))
    return state, qs


FAMILIES = {"kc_house_price": gen_kc_house_price,
            "insurance_charges": gen_insurance_charges,
            "housing_price": gen_housing_price,
            "life_expectancy": gen_life_expectancy}
WEIGHTS = {"kc_house_price": 0.30, "insurance_charges": 0.25,
           "housing_price": 0.15, "life_expectancy": 0.30}


def make_rows(n, seed):
    return generate(FAMILIES, WEIGHTS, n, seed, rng)


if __name__ == "__main__":
    rows = make_rows(10, 0)
    for r in rows:
        validate_row(r)
    for r in rows[:3]:
        print(r["id"], "|", r["state"][:120])
        for qid, t in r["targets"].items():
            print("   ", qid, r["questions"][qid]["type"],
                  t[:6] if isinstance(t, list) else t)
    print(f"{len(rows)} rows OK")