Akahsizrr commited on
Commit
a144c8e
·
verified ·
1 Parent(s): 2bea5bf

Upload alea/gen_kaggle_reg.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. alea/gen_kaggle_reg.py +332 -0
alea/gen_kaggle_reg.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Real-data REGRESSION families — empirical conditional quantile targets.
2
+
3
+ Each row is a real record from a Kaggle tabular regression dataset
4
+ serialized WITHOUT its label (compact feature JSON). The regress target
5
+ is the empirical conditional distribution of the label given the record's
6
+ strongest covariates, estimated by grouped binning: the 19 quantiles at
7
+ taus .05-.95 come from the bin's own sample (linear interpolation). Bins
8
+ with < MIN_N members fall back along a coarsening chain — drop the weakest
9
+ conditioning feature, then the next, ending at the global marginal — so
10
+ targets are always honest empirical conditionals, never fabricated.
11
+
12
+ ~30% of rows add a noul "is y above X?" with X a round number near the bin
13
+ median (target = exact P(y>X|bin) off the empirical CDF); ~20% add a
14
+ choice over value bands (target = empirical conditional over the bands).
15
+
16
+ CSV files are loaded once each and cached at module level (lazy on first
17
+ family call so `gen_all --list` stays cheap).
18
+ """
19
+ import json
20
+ import random
21
+ from pathlib import Path
22
+
23
+ import numpy as np
24
+ import pandas as pd
25
+
26
+ from alea.genbase import (generate, emit, q_choice, q_noul, q_score,
27
+ q_regress, validate_row, write_jsonl)
28
+
29
+ rng = random.Random()
30
+
31
+ KAGGLE = Path(__file__).resolve().parents[1] / "data" / "kaggle"
32
+ TAUS = [0.05 * (i + 1) for i in range(19)]
33
+ MIN_N = 20 # smallest trusted bin; below -> coarser conditioning
34
+ P_NOUL = 0.30 # share of rows that also carry a threshold noul
35
+ P_BAND = 0.20 # share of rows that also carry a band choice
36
+
37
+
38
+ # ---------- empirical-conditional machinery ----------
39
+ def _build(df, bin_cols, y_col):
40
+ """Return (keys, levels): keys[i] is the full bin tuple of row i;
41
+ levels[L] maps a length-L key prefix to the sorted label sample of
42
+ that bin. levels[0][()] is the global marginal."""
43
+ y = df[y_col].to_numpy(dtype=float)
44
+ keys = list(zip(*[df[c].tolist() for c in bin_cols]))
45
+ levels = {0: {(): np.sort(y)}}
46
+ for L in range(1, len(bin_cols) + 1):
47
+ d = {}
48
+ for k, v in zip(keys, y):
49
+ d.setdefault(k[:L], []).append(v)
50
+ levels[L] = {k: np.sort(np.asarray(v)) for k, v in d.items()}
51
+ return keys, levels
52
+
53
+
54
+ def _sample(levels, key, min_n=MIN_N):
55
+ """Sorted label sample of the finest trusted bin along key's prefix
56
+ chain: full key -> drop weakest feature -> ... -> global marginal."""
57
+ for L in range(len(key), 0, -1):
58
+ arr = levels[L].get(tuple(key[:L]))
59
+ if arr is not None and len(arr) >= min_n:
60
+ return arr
61
+ return levels[0][()]
62
+
63
+
64
+ def _q19(arr):
65
+ """19 empirical quantiles at TAUS, linear interpolation, 3 decimals."""
66
+ return [round(float(v), 3) for v in np.quantile(arr, TAUS)]
67
+
68
+
69
+ def _cdf_gt(arr, x):
70
+ """Empirical P(y > x): one minus the sample fraction <= x."""
71
+ return float(1.0 - np.searchsorted(arr, x, side="right") / len(arr))
72
+
73
+
74
+ def _band_probs(arr, edges):
75
+ """Empirical P(y in band) over (-inf,e0),[e0,e1),...,[eK,+inf)."""
76
+ c = [float(np.searchsorted(arr, e, side="right")) / len(arr)
77
+ for e in edges]
78
+ ps, prev = [], 0.0
79
+ for x in c + [1.0]:
80
+ ps.append(max(0.0, x - prev))
81
+ prev = x
82
+ s = sum(ps) or 1.0
83
+ ps = [round(p / s, 4) for p in ps]
84
+ ps[-1] = round(max(0.0, 1.0 - sum(ps[:-1])), 4)
85
+ return ps
86
+
87
+
88
+ def _near(x, step):
89
+ """Round number within about one step of x."""
90
+ return int(round(x / step)) * step + rng.choice([-1, 0, 0, 0, 1]) * step
91
+
92
+
93
+ def _num(v, nd=1):
94
+ """Compact float for state JSON: drop trailing .0, cap decimals."""
95
+ f = round(float(v), nd)
96
+ i = int(f)
97
+ return i if f == i else f
98
+
99
+
100
+ # ---------- dataset loaders (module-level cache) ----------
101
+ _CACHE = {}
102
+
103
+
104
+ def _house_data():
105
+ if "house" not in _CACHE:
106
+ df = pd.read_csv(KAGGLE / "house" / "kc_house_data.csv")
107
+ df["_sqft"] = pd.qcut(df["sqft_living"], 10, labels=False,
108
+ duplicates="drop")
109
+ df["_grade"] = pd.cut(df["grade"], [0, 6, 8, 10, 13], labels=False)
110
+ keys, lv = _build(df, ["_sqft", "_grade"], "price")
111
+ _CACHE["house"] = (df, keys, lv)
112
+ return _CACHE["house"]
113
+
114
+
115
+ def _ins_data():
116
+ if "ins" not in _CACHE:
117
+ df = pd.read_csv(KAGGLE / "insurance" / "insurance.csv")
118
+ df["_bmi"] = pd.cut(df["bmi"], [0, 25, 30, np.inf], labels=False)
119
+ df["_age"] = pd.cut(df["age"], [0, 30, 45, np.inf], labels=False)
120
+ keys, lv = _build(df, ["smoker", "_bmi", "_age"], "charges")
121
+ _CACHE["ins"] = (df, keys, lv)
122
+ return _CACHE["ins"]
123
+
124
+
125
+ def _housing_data():
126
+ if "housing" not in _CACHE:
127
+ df = pd.read_csv(KAGGLE / "housing" / "Housing.csv")
128
+ df["_area"] = pd.qcut(df["area"], 5, labels=False,
129
+ duplicates="drop")
130
+ keys, lv = _build(df, ["_area", "furnishingstatus"], "price")
131
+ _CACHE["housing"] = (df, keys, lv)
132
+ return _CACHE["housing"]
133
+
134
+
135
+ LIFE_FEATS = ["Adult Mortality", "infant deaths", "Alcohol", "BMI",
136
+ "under-five deaths", "Polio", "Diphtheria", "HIV/AIDS", "GDP",
137
+ "Income composition of resources", "Schooling"]
138
+
139
+
140
+ def _life_data():
141
+ if "life" not in _CACHE:
142
+ df = pd.read_csv(KAGGLE / "life_exp" / "Life Expectancy Data.csv")
143
+ df.columns = [c.strip() for c in df.columns] # stray spaces
144
+ df = df.dropna(subset=["Life expectancy"]).reset_index(drop=True)
145
+ for c in LIFE_FEATS:
146
+ df[c] = df[c].fillna(df[c].median())
147
+ df["_am"] = pd.qcut(df["Adult Mortality"], 4, labels=False,
148
+ duplicates="drop")
149
+ df["_sch"] = pd.qcut(df["Schooling"], 4, labels=False,
150
+ duplicates="drop")
151
+ keys, lv = _build(df, ["Status", "_am", "_sch"], "Life expectancy")
152
+ _CACHE["life"] = (df, keys, lv)
153
+ return _CACHE["life"]
154
+
155
+
156
+ # ---------- families ----------
157
+ HOUSE_INSTR = [
158
+ "Estimate the distribution of this home's sale price.",
159
+ "What sale price will this King County property fetch?",
160
+ "Predict the final selling price of this house.",
161
+ ]
162
+ HOUSE_NOUL = ["Is the sale price above ${x:,}?",
163
+ "Will the home sell for more than ${x:,}?"]
164
+
165
+
166
+ def gen_kc_house_price():
167
+ df, keys, lv = _house_data()
168
+ i = rng.randrange(len(df))
169
+ r = df.iloc[i]
170
+ arr = _sample(lv, keys[i])
171
+ state = json.dumps({
172
+ "bedrooms": int(r["bedrooms"]),
173
+ "bathrooms": float(r["bathrooms"]),
174
+ "sqft_living": int(r["sqft_living"]),
175
+ "sqft_lot": int(r["sqft_lot"]),
176
+ "floors": float(r["floors"]),
177
+ "waterfront": int(r["waterfront"]),
178
+ "view": int(r["view"]),
179
+ "condition": int(r["condition"]),
180
+ "grade": int(r["grade"]),
181
+ "yr_built": int(r["yr_built"]),
182
+ "zipcode": str(r["zipcode"])}, separators=(",", ":"))
183
+ qs = [q_regress("price", rng.choice(HOUSE_INSTR), _q19(arr),
184
+ unit="dollars")]
185
+ if rng.random() < P_NOUL:
186
+ thr = _near(arr[len(arr) // 2], 50000)
187
+ qs.append(q_noul("above", rng.choice(HOUSE_NOUL).format(x=thr),
188
+ _cdf_gt(arr, thr)))
189
+ if rng.random() < P_BAND:
190
+ qs.append(q_choice(
191
+ "band", "Which band does the sale price fall in?",
192
+ ["under $200k", "$200k-$400k", "$400k-$800k", "over $800k"],
193
+ _band_probs(arr, [200000, 400000, 800000])))
194
+ return state, qs
195
+
196
+
197
+ INS_INSTR = [
198
+ "Estimate the distribution of annual medical charges for this person.",
199
+ "What will this policyholder's medical insurance charges be?",
200
+ "Predict the yearly insurance charges for this individual.",
201
+ ]
202
+ INS_NOUL = ["Are the charges above ${x:,}?",
203
+ "Will the medical charges exceed ${x:,}?"]
204
+
205
+
206
+ def gen_insurance_charges():
207
+ df, keys, lv = _ins_data()
208
+ i = rng.randrange(len(df))
209
+ r = df.iloc[i]
210
+ arr = _sample(lv, keys[i])
211
+ state = json.dumps({
212
+ "age": int(r["age"]), "sex": r["sex"], "bmi": _num(r["bmi"]),
213
+ "children": int(r["children"]), "smoker": r["smoker"],
214
+ "region": r["region"]}, separators=(",", ":"))
215
+ qs = [q_regress("charges", rng.choice(INS_INSTR), _q19(arr),
216
+ unit="dollars")]
217
+ if rng.random() < P_NOUL:
218
+ thr = _near(arr[len(arr) // 2], 5000)
219
+ qs.append(q_noul("above", rng.choice(INS_NOUL).format(x=thr),
220
+ _cdf_gt(arr, thr)))
221
+ if rng.random() < P_BAND:
222
+ qs.append(q_choice(
223
+ "band", "Which band do the annual charges fall in?",
224
+ ["under $5k", "$5k-$15k", "$15k-$30k", "over $30k"],
225
+ _band_probs(arr, [5000, 15000, 30000])))
226
+ return state, qs
227
+
228
+
229
+ HOUSING_INSTR = [
230
+ "Estimate the distribution of this home's asking price.",
231
+ "What price will this house sell for?",
232
+ "Predict the sale price of this property.",
233
+ ]
234
+ HOUSING_NOUL = ["Is the asking price above ${x:,}?",
235
+ "Will the price exceed ${x:,}?"]
236
+
237
+
238
+ def gen_housing_price():
239
+ df, keys, lv = _housing_data()
240
+ i = rng.randrange(len(df))
241
+ r = df.iloc[i]
242
+ arr = _sample(lv, keys[i])
243
+ state = json.dumps({
244
+ "area": int(r["area"]), "bedrooms": int(r["bedrooms"]),
245
+ "bathrooms": int(r["bathrooms"]), "stories": int(r["stories"]),
246
+ "mainroad": r["mainroad"], "guestroom": r["guestroom"],
247
+ "basement": r["basement"],
248
+ "hotwaterheating": r["hotwaterheating"],
249
+ "airconditioning": r["airconditioning"],
250
+ "parking": int(r["parking"]), "prefarea": r["prefarea"],
251
+ "furnishingstatus": r["furnishingstatus"]},
252
+ separators=(",", ":"))
253
+ qs = [q_regress("price", rng.choice(HOUSING_INSTR), _q19(arr),
254
+ unit="dollars")]
255
+ if rng.random() < P_NOUL:
256
+ thr = _near(arr[len(arr) // 2], 500000)
257
+ qs.append(q_noul("above", rng.choice(HOUSING_NOUL).format(x=thr),
258
+ _cdf_gt(arr, thr)))
259
+ if rng.random() < P_BAND:
260
+ qs.append(q_choice(
261
+ "band", "Which price band does this home fall in?",
262
+ ["under $3.5M", "$3.5M-$5M", "$5M-$7M", "over $7M"],
263
+ _band_probs(arr, [3500000, 5000000, 7000000])))
264
+ return state, qs
265
+
266
+
267
+ LIFE_INSTR = [
268
+ "Estimate the distribution of life expectancy for this country-year.",
269
+ "What life expectancy at birth would you predict under these "
270
+ "conditions?",
271
+ "Predict the life expectancy for this country and year.",
272
+ ]
273
+ LIFE_NOUL = ["Is life expectancy above {x} years?",
274
+ "Will life expectancy exceed {x} years?"]
275
+
276
+
277
+ def gen_life_expectancy():
278
+ df, keys, lv = _life_data()
279
+ i = rng.randrange(len(df))
280
+ r = df.iloc[i]
281
+ arr = _sample(lv, keys[i])
282
+ state = json.dumps({
283
+ "Country": r["Country"], "Year": int(r["Year"]),
284
+ "Status": r["Status"],
285
+ "Adult Mortality": _num(r["Adult Mortality"], 0),
286
+ "infant deaths": _num(r["infant deaths"], 0),
287
+ "Alcohol": _num(r["Alcohol"], 2),
288
+ "BMI": _num(r["BMI"]),
289
+ "under-five deaths": _num(r["under-five deaths"], 0),
290
+ "Polio": _num(r["Polio"]),
291
+ "Diphtheria": _num(r["Diphtheria"]),
292
+ "HIV/AIDS": _num(r["HIV/AIDS"]),
293
+ "GDP": _num(r["GDP"], 0),
294
+ "Income composition": _num(r["Income composition of resources"], 2),
295
+ "Schooling": _num(r["Schooling"])}, separators=(",", ":"))
296
+ qs = [q_regress("lifexp", rng.choice(LIFE_INSTR), _q19(arr),
297
+ unit="years")]
298
+ if rng.random() < P_NOUL:
299
+ thr = _near(arr[len(arr) // 2], 5)
300
+ qs.append(q_noul("above", rng.choice(LIFE_NOUL).format(x=thr),
301
+ _cdf_gt(arr, thr)))
302
+ if rng.random() < P_BAND:
303
+ qs.append(q_choice(
304
+ "band", "Which life-expectancy band applies?",
305
+ ["under 60 years", "60-70 years", "70-77 years",
306
+ "over 77 years"],
307
+ _band_probs(arr, [60, 70, 77])))
308
+ return state, qs
309
+
310
+
311
+ FAMILIES = {"kc_house_price": gen_kc_house_price,
312
+ "insurance_charges": gen_insurance_charges,
313
+ "housing_price": gen_housing_price,
314
+ "life_expectancy": gen_life_expectancy}
315
+ WEIGHTS = {"kc_house_price": 0.30, "insurance_charges": 0.25,
316
+ "housing_price": 0.15, "life_expectancy": 0.30}
317
+
318
+
319
+ def make_rows(n, seed):
320
+ return generate(FAMILIES, WEIGHTS, n, seed, rng)
321
+
322
+
323
+ if __name__ == "__main__":
324
+ rows = make_rows(10, 0)
325
+ for r in rows:
326
+ validate_row(r)
327
+ for r in rows[:3]:
328
+ print(r["id"], "|", r["state"][:120])
329
+ for qid, t in r["targets"].items():
330
+ print(" ", qid, r["questions"][qid]["type"],
331
+ t[:6] if isinstance(t, list) else t)
332
+ print(f"{len(rows)} rows OK")