edgepoint-booster 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- edgepoint_booster/__init__.py +18 -0
- edgepoint_booster/combo_bin_rules.py +75 -0
- edgepoint_booster/core_validations.py +225 -0
- edgepoint_booster/edge_points.py +316 -0
- edgepoint_booster/main.py +281 -0
- edgepoint_booster/others.py +54 -0
- edgepoint_booster/utils.py +155 -0
- edgepoint_booster-1.0.0.dist-info/METADATA +10 -0
- edgepoint_booster-1.0.0.dist-info/RECORD +11 -0
- edgepoint_booster-1.0.0.dist-info/WHEEL +5 -0
- edgepoint_booster-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""edgepoint_booster: Short one-line description of what the module does.
|
|
2
|
+
|
|
3
|
+
Usage:
|
|
4
|
+
from edgepoint_booster import train
|
|
5
|
+
|
|
6
|
+
result = train(df)
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
10
|
+
|
|
11
|
+
from .main import train
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
__version__ = version("edgepoint-booster") # same name as `name` in pyproject.toml
|
|
15
|
+
except PackageNotFoundError: # running from source, not pip-installed
|
|
16
|
+
__version__ = "0.0.0"
|
|
17
|
+
|
|
18
|
+
__all__ = ["train", "__version__"]
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
from itertools import combinations
|
|
2
|
+
from itertools import product
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def all_combinations(items, df_len):
|
|
6
|
+
"""
|
|
7
|
+
Return every unique subset of `items`, from single items up to a cap
|
|
8
|
+
worked out from the number of rows.
|
|
9
|
+
Order doesn't matter: ['age', 'sex'] == ['sex', 'age'].
|
|
10
|
+
|
|
11
|
+
items: list of choices
|
|
12
|
+
df_len: number of rows in the df
|
|
13
|
+
|
|
14
|
+
Cap by rows: under 150 -> 2, 150 to 399 -> 3, 400 to 1,999 -> 4,
|
|
15
|
+
2,000+ -> 5. The cap is also limited to len(items).
|
|
16
|
+
"""
|
|
17
|
+
if df_len < 150:
|
|
18
|
+
cap = 2
|
|
19
|
+
elif df_len < 400:
|
|
20
|
+
cap = 3
|
|
21
|
+
elif df_len < 2000:
|
|
22
|
+
cap = 4
|
|
23
|
+
else:
|
|
24
|
+
cap = 5
|
|
25
|
+
|
|
26
|
+
cap = min(cap, len(items))
|
|
27
|
+
|
|
28
|
+
return [list(c) for r in range(1, cap + 1)
|
|
29
|
+
for c in combinations(items, r)]
|
|
30
|
+
|
|
31
|
+
def combo_bin_rules(df, rules, display=True):
|
|
32
|
+
"""
|
|
33
|
+
Build combinations of columns from the flat rules, then attach each
|
|
34
|
+
column's rule to it. The cap on combination size comes from the
|
|
35
|
+
number of rows in df.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
df: DataFrame the rules will be used on (only its length is used).
|
|
39
|
+
rules: flat list of rule strings, '<column> <condition>', e.g.
|
|
40
|
+
["age 26 to 50", "score >= 3", "income <= 500"]
|
|
41
|
+
display: If True, print the combinations.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
list of {column: rule} dicts, smallest combinations first, e.g.
|
|
45
|
+
[{"age": "26 to 50"},
|
|
46
|
+
{"age": "26 to 50", "score": ">= 3"}, ...]
|
|
47
|
+
"""
|
|
48
|
+
if not isinstance(rules, list):
|
|
49
|
+
raise TypeError(f"rules must be a flat list of strings, got {type(rules).__name__}.")
|
|
50
|
+
|
|
51
|
+
# Group flat rules by column (keeps first-seen column order)
|
|
52
|
+
grouped = {}
|
|
53
|
+
for rule in rules:
|
|
54
|
+
col, cond = rule.strip().split(' ', 1)
|
|
55
|
+
grouped.setdefault(col, []).append(cond.strip())
|
|
56
|
+
|
|
57
|
+
df_len = len(df)
|
|
58
|
+
columns = list(grouped)
|
|
59
|
+
|
|
60
|
+
combos = []
|
|
61
|
+
for cols in all_combinations(columns, df_len):
|
|
62
|
+
# one rule per column; if a column holds several rules,
|
|
63
|
+
# every pairing is produced
|
|
64
|
+
for chosen in product(*(grouped[c] for c in cols)):
|
|
65
|
+
combos.append(dict(zip(cols, chosen)))
|
|
66
|
+
|
|
67
|
+
if display:
|
|
68
|
+
header = f"RULE COMBINATIONS ({len(combos):,})."
|
|
69
|
+
print(f"\n\033[1m{header}\033[0m")
|
|
70
|
+
print("-" * len(header))
|
|
71
|
+
print()
|
|
72
|
+
for i, combo in enumerate(combos, 1):
|
|
73
|
+
print(f"{i:>4}. " + " AND ".join(f"{c} {r}" for c, r in combo.items()))
|
|
74
|
+
|
|
75
|
+
return combos
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import numbers
|
|
5
|
+
|
|
6
|
+
def datetime_reason(s, name):
|
|
7
|
+
"""Return why a column looks like a date/time, or None if it doesn't."""
|
|
8
|
+
if pd.api.types.is_datetime64_any_dtype(s):
|
|
9
|
+
return "datetime dtype"
|
|
10
|
+
if pd.api.types.is_timedelta64_dtype(s):
|
|
11
|
+
return "timedelta dtype"
|
|
12
|
+
|
|
13
|
+
# name hint: whole words only, so "extra_time_goals" is not caught
|
|
14
|
+
if any(t in ("date", "datetime", "timestamp") for t in name.lower().split("_")):
|
|
15
|
+
return "name looks like a date"
|
|
16
|
+
|
|
17
|
+
if not pd.api.types.is_numeric_dtype(s) or pd.api.types.is_bool_dtype(s):
|
|
18
|
+
return None
|
|
19
|
+
|
|
20
|
+
v = s.dropna()
|
|
21
|
+
if v.empty or not (v == v.round()).all():
|
|
22
|
+
return None
|
|
23
|
+
lo, hi = v.min(), v.max()
|
|
24
|
+
|
|
25
|
+
# YYYYMMDD stored as a number, e.g. 20261123
|
|
26
|
+
if 19000101 <= lo and hi <= 21001231:
|
|
27
|
+
parsed = pd.to_datetime(v.astype("int64").astype(str), format="%Y%m%d", errors="coerce")
|
|
28
|
+
if parsed.notna().all():
|
|
29
|
+
return "YYYYMMDD number"
|
|
30
|
+
|
|
31
|
+
# unix epoch, seconds (2000 to 2100) or milliseconds
|
|
32
|
+
if 9.5e8 <= lo and hi <= 4.2e9:
|
|
33
|
+
return "epoch seconds"
|
|
34
|
+
if 9.5e11 <= lo and hi <= 4.2e12:
|
|
35
|
+
return "epoch milliseconds"
|
|
36
|
+
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
def low_variance_reason(s, max_top_share=0.99):
|
|
40
|
+
"""Return why a numeric column has too little variance, or None if it's fine."""
|
|
41
|
+
v = s.dropna()
|
|
42
|
+
if v.empty:
|
|
43
|
+
return "all missing"
|
|
44
|
+
if v.nunique() <= 1:
|
|
45
|
+
return "constant"
|
|
46
|
+
top_share = v.value_counts(normalize=True).iloc[0]
|
|
47
|
+
if top_share >= max_top_share:
|
|
48
|
+
return f"{top_share:.1%} one value"
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
def validate(df, directions, min_coverage, shrinkage_n, display=True):
|
|
52
|
+
"""
|
|
53
|
+
Validate inputs and clean the DataFrame before binning.
|
|
54
|
+
|
|
55
|
+
Checks performed:
|
|
56
|
+
✔ min_coverage is a finite number (not bool)
|
|
57
|
+
✔ min_coverage is between 1 and 100
|
|
58
|
+
✔ shrinkage_n is a whole number (not bool)
|
|
59
|
+
✔ shrinkage_n is at least 3
|
|
60
|
+
✔ "hit" column exists in df
|
|
61
|
+
✔ "hit" contains only 0/1 or True/False
|
|
62
|
+
✔ no column name starts or ends with "." (both edges are reserved:
|
|
63
|
+
validate() adds the trailing "." to every feature column below,
|
|
64
|
+
and the app adds a leading "." later)
|
|
65
|
+
✔ datetime-like columns are dropped (datetime/timedelta dtype,
|
|
66
|
+
date-like names, YYYYMMDD numbers, epoch seconds/milliseconds)
|
|
67
|
+
✔ non-numeric columns are dropped
|
|
68
|
+
✔ low-variance columns are dropped (all missing, constant, or
|
|
69
|
+
one value making up 99%+ of rows)
|
|
70
|
+
✔ directions is a string, or a dict of column -> string
|
|
71
|
+
✔ each direction is one of "all", "left", "right", "range"
|
|
72
|
+
✔ dict keys exist in the cleaned df (plain names, without the dot)
|
|
73
|
+
✔ every feature column is renamed with a trailing "." ("age" becomes
|
|
74
|
+
"age."); "hit" keeps its name
|
|
75
|
+
✔ summary of checks, dropped columns and directions is printed
|
|
76
|
+
when display is True
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
df: DataFrame with a "hit" column and feature columns.
|
|
80
|
+
directions: String applied to all columns, or dict mapping
|
|
81
|
+
column names to a direction (others default to "all").
|
|
82
|
+
min_coverage: Minimum coverage percentage per bin (1 to 100).
|
|
83
|
+
shrinkage_n: Minimum observations per bin (>= 3).
|
|
84
|
+
display: If True, print the summary of checks, dropped columns
|
|
85
|
+
and directions. If False, run silently. Default True.
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
DataFrame with "hit" and numeric, non-datetime, non-degenerate
|
|
89
|
+
columns only. Every feature column name ends with "." (e.g. "age."),
|
|
90
|
+
"hit" is unchanged.
|
|
91
|
+
|
|
92
|
+
Raises:
|
|
93
|
+
TypeError: Wrong type for min_coverage, shrinkage_n or a direction.
|
|
94
|
+
ValueError: Out-of-range value, invalid "hit" values, a column name
|
|
95
|
+
that starts or ends with ".", bad direction or dict keys not in df
|
|
96
|
+
(including dropped columns).
|
|
97
|
+
KeyError: "hit" column is missing.
|
|
98
|
+
"""
|
|
99
|
+
# parameters
|
|
100
|
+
if isinstance(min_coverage, bool) or not isinstance(min_coverage, numbers.Real) or not math.isfinite(min_coverage):
|
|
101
|
+
raise TypeError(f"min_coverage must be a number, got {min_coverage!r}")
|
|
102
|
+
if not 1 <= min_coverage <= 100:
|
|
103
|
+
raise ValueError(f"min_coverage must be between 1 and 100, got {min_coverage}")
|
|
104
|
+
|
|
105
|
+
if isinstance(shrinkage_n, bool) or not isinstance(shrinkage_n, numbers.Integral):
|
|
106
|
+
raise TypeError(f"shrinkage_n must be a whole number, got {shrinkage_n!r}")
|
|
107
|
+
if shrinkage_n < 3:
|
|
108
|
+
raise ValueError(f"shrinkage_n must be at least 3, got {shrinkage_n}")
|
|
109
|
+
|
|
110
|
+
# hit column
|
|
111
|
+
if "hit" not in df.columns:
|
|
112
|
+
raise KeyError("column 'hit' not found in df")
|
|
113
|
+
|
|
114
|
+
bad = ~df["hit"].isin([0, 1])
|
|
115
|
+
if bad.any():
|
|
116
|
+
raise ValueError(
|
|
117
|
+
f"'hit' must contain only 0/1 or True/False, found {bad.sum()} invalid value(s) "
|
|
118
|
+
f"(e.g. {df.loc[bad, 'hit'].unique()[:5].tolist()})"
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
# no column name may start or end with "."; both edges are reserved:
|
|
122
|
+
# validate() adds the trailing "." to every feature column (see the rename
|
|
123
|
+
# below) and the app adds its own leading "." later, so a name that already
|
|
124
|
+
# has a dot at either edge is rejected up front
|
|
125
|
+
dotted = [c for c in df.columns if str(c).startswith(".") or str(c).endswith(".")]
|
|
126
|
+
if dotted:
|
|
127
|
+
raise ValueError(
|
|
128
|
+
f"column names must not start or end with '.', found {dotted}. "
|
|
129
|
+
"Rename them (e.g. df.rename(columns=lambda c: str(c).strip('.')))."
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
# drop datetime-like columns, even the ones that pass as numeric
|
|
133
|
+
date_cols = {}
|
|
134
|
+
for c in df.columns:
|
|
135
|
+
if c == "hit":
|
|
136
|
+
continue
|
|
137
|
+
reason = datetime_reason(df[c], str(c))
|
|
138
|
+
if reason:
|
|
139
|
+
date_cols[c] = reason
|
|
140
|
+
df = df.drop(columns=list(date_cols))
|
|
141
|
+
|
|
142
|
+
# drop non-numeric columns
|
|
143
|
+
keep = [c for c in df.columns if c == "hit" or pd.api.types.is_numeric_dtype(df[c])]
|
|
144
|
+
dropped = [c for c in df.columns if c not in keep]
|
|
145
|
+
df = df[keep]
|
|
146
|
+
|
|
147
|
+
# drop low-variance columns
|
|
148
|
+
low_var_cols = {}
|
|
149
|
+
for c in df.columns:
|
|
150
|
+
if c == "hit":
|
|
151
|
+
continue
|
|
152
|
+
reason = low_variance_reason(df[c])
|
|
153
|
+
if reason:
|
|
154
|
+
low_var_cols[c] = reason
|
|
155
|
+
df = df.drop(columns=list(low_var_cols))
|
|
156
|
+
|
|
157
|
+
# directions
|
|
158
|
+
valid = ("all", "left", "right", "range")
|
|
159
|
+
|
|
160
|
+
def norm(d, label):
|
|
161
|
+
if not isinstance(d, str):
|
|
162
|
+
raise TypeError(f"direction for {label} must be a string, got {type(d).__name__}")
|
|
163
|
+
d = d.strip().lower()
|
|
164
|
+
if d not in valid:
|
|
165
|
+
raise ValueError(f"direction for {label} must be one of {valid}, got {d!r}")
|
|
166
|
+
return d
|
|
167
|
+
|
|
168
|
+
if isinstance(directions, dict):
|
|
169
|
+
missing = [c for c in directions if c not in df.columns]
|
|
170
|
+
if missing:
|
|
171
|
+
raise ValueError(f"direction columns not in df: {missing}")
|
|
172
|
+
# users type plain names; the map uses the dotted names the df will have
|
|
173
|
+
direction_map = {f"{c}.": norm(d, repr(c)) for c, d in directions.items()}
|
|
174
|
+
default_direction = "all"
|
|
175
|
+
else:
|
|
176
|
+
direction_map = {}
|
|
177
|
+
default_direction = norm(directions, "directions")
|
|
178
|
+
|
|
179
|
+
# sanitize: add a trailing "." to every feature column ("age" -> "age.")
|
|
180
|
+
# so a df column can never clash with the internal tables/variables.
|
|
181
|
+
# "hit" keeps its name because the rest of the code looks it up by name.
|
|
182
|
+
df = df.rename(columns={c: f"{c}." for c in df.columns if c != "hit"})
|
|
183
|
+
|
|
184
|
+
# summary
|
|
185
|
+
def section(name, rows):
|
|
186
|
+
# rows: list of (left, right) pairs, left column padded to the same width
|
|
187
|
+
w = max(len(str(l)) for l, _ in rows)
|
|
188
|
+
if name:
|
|
189
|
+
print(name)
|
|
190
|
+
for l, r in rows:
|
|
191
|
+
print(f" {str(l).ljust(w)} {r}")
|
|
192
|
+
print()
|
|
193
|
+
|
|
194
|
+
def fmt(cols):
|
|
195
|
+
return ", ".join(f"{c} ({r})" for c, r in cols.items()) if cols else "none"
|
|
196
|
+
|
|
197
|
+
if display:
|
|
198
|
+
title = "Sanity and validations Checks"
|
|
199
|
+
print(f"\033[1m{title}\033[0m")
|
|
200
|
+
print("-" * len(title))
|
|
201
|
+
print()
|
|
202
|
+
|
|
203
|
+
section(None, [
|
|
204
|
+
("✔ min_coverage", min_coverage),
|
|
205
|
+
("✔ shrinkage_n", shrinkage_n),
|
|
206
|
+
("✔ hit", "binary 0/1"),
|
|
207
|
+
("✔ column names", "sanitized"),
|
|
208
|
+
])
|
|
209
|
+
|
|
210
|
+
section("Dropped", [
|
|
211
|
+
("datetime", fmt(date_cols)),
|
|
212
|
+
("non-numeric", ", ".join(map(str, dropped)) if dropped else "none"),
|
|
213
|
+
("low variance", fmt(low_var_cols)),
|
|
214
|
+
])
|
|
215
|
+
|
|
216
|
+
if isinstance(directions, dict):
|
|
217
|
+
rows = [(c.removesuffix("."), d) for c, d in direction_map.items()] + [("all others", default_direction)]
|
|
218
|
+
else:
|
|
219
|
+
rows = [("all columns", default_direction)]
|
|
220
|
+
section("Directions", rows)
|
|
221
|
+
|
|
222
|
+
# reset the index to start from 0
|
|
223
|
+
df = df.reset_index(drop=True)
|
|
224
|
+
|
|
225
|
+
return df
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import operator
|
|
3
|
+
import pandas as pd
|
|
4
|
+
import math
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
_RANGE = re.compile(r'^(-?\d+(?:\.\d+)?)\s+to\s+(-?\d+(?:\.\d+)?)$')
|
|
8
|
+
_COMPARE = re.compile(r'^(>=|<=|==|=|>|<)\s*(-?\d+(?:\.\d+)?)$')
|
|
9
|
+
_OPS = {'>=': operator.ge, '<=': operator.le, '>': operator.gt,
|
|
10
|
+
'<': operator.lt, '=': operator.eq, '==': operator.eq}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def rule_mask(df: pd.DataFrame, rule: str) -> pd.Series:
|
|
14
|
+
"""'home_attack_rating 0 to 2' -> boolean Series (True where the row matches)."""
|
|
15
|
+
if not isinstance(rule, str) or ' ' not in rule.strip():
|
|
16
|
+
raise ValueError(f"Bad rule format: {rule!r} (expected '<column> <condition>').")
|
|
17
|
+
|
|
18
|
+
col, cond = rule.strip().split(' ', 1)
|
|
19
|
+
cond = cond.strip()
|
|
20
|
+
|
|
21
|
+
if col not in df.columns:
|
|
22
|
+
raise KeyError(f"Column '{col}' from rule {rule!r} not found in df.")
|
|
23
|
+
|
|
24
|
+
s = df[col]
|
|
25
|
+
|
|
26
|
+
m = _RANGE.match(cond)
|
|
27
|
+
if m:
|
|
28
|
+
lo, hi = float(m.group(1)), float(m.group(2))
|
|
29
|
+
return s.between(lo, hi) # inclusive on both ends
|
|
30
|
+
|
|
31
|
+
m = _COMPARE.match(cond)
|
|
32
|
+
if m:
|
|
33
|
+
return _OPS[m.group(1)](s, float(m.group(2)))
|
|
34
|
+
|
|
35
|
+
raise ValueError(f"Cannot parse condition {cond!r} in rule {rule!r}.")
|
|
36
|
+
|
|
37
|
+
def flatten_rules(rules) -> list[str]:
|
|
38
|
+
"""
|
|
39
|
+
Accepts:
|
|
40
|
+
- list[str] -> already flat, returned as is (after validation)
|
|
41
|
+
- dict[str, list[str]] -> converted to ['col rule', ...]
|
|
42
|
+
Raises TypeError / ValueError for anything else.
|
|
43
|
+
"""
|
|
44
|
+
if rules is None:
|
|
45
|
+
raise ValueError("flatten_rules received None (expected dict[str, list[str]] or list[str]).")
|
|
46
|
+
|
|
47
|
+
# Already flat -> validate and return
|
|
48
|
+
if isinstance(rules, list):
|
|
49
|
+
for r in rules:
|
|
50
|
+
if not isinstance(r, str) or not r.strip():
|
|
51
|
+
raise TypeError(f"Flat rules must be non-empty strings, got {r!r}.")
|
|
52
|
+
return rules
|
|
53
|
+
|
|
54
|
+
# Dict -> convert
|
|
55
|
+
if isinstance(rules, dict):
|
|
56
|
+
flat = []
|
|
57
|
+
for col, rule_list in rules.items():
|
|
58
|
+
if not isinstance(col, str) or not col.strip():
|
|
59
|
+
raise TypeError(f"Column name must be a non-empty string, got {col!r}.")
|
|
60
|
+
if not isinstance(rule_list, (list, tuple)):
|
|
61
|
+
raise TypeError(
|
|
62
|
+
f"Rules for '{col}' must be a list of strings, got {type(rule_list).__name__}."
|
|
63
|
+
)
|
|
64
|
+
for rule in rule_list:
|
|
65
|
+
if not isinstance(rule, str) or not rule.strip():
|
|
66
|
+
raise TypeError(f"Rule for '{col}' must be a non-empty string, got {rule!r}.")
|
|
67
|
+
flat.append(f"{col} {rule.strip()}")
|
|
68
|
+
return flat
|
|
69
|
+
|
|
70
|
+
raise TypeError(
|
|
71
|
+
f"Expected dict[str, list[str]] or list[str], got {type(rules).__name__}."
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def wilson_lower(hits: int, n: int, z: float = 1.96) -> float:
|
|
75
|
+
"""Lower bound of the Wilson score interval for a proportion (0-1)."""
|
|
76
|
+
if n == 0:
|
|
77
|
+
return 0.0
|
|
78
|
+
p = hits / n
|
|
79
|
+
denom = 1 + z**2 / n
|
|
80
|
+
centre = p + z**2 / (2 * n)
|
|
81
|
+
margin = z * math.sqrt((p * (1 - p) + z**2 / (4 * n)) / n)
|
|
82
|
+
return (centre - margin) / denom
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def edge_points(df: pd.DataFrame, rules, outcome_col: str = 'hit',
|
|
86
|
+
min_coverage: float = 20, shrinkage_n: int = 30,
|
|
87
|
+
top_n: int | None = None,
|
|
88
|
+
z: float = 1.96, display: bool = True,
|
|
89
|
+
title: str = 'Train', drop_duplicate: bool = True,
|
|
90
|
+
wilson_rate: float | None = None,
|
|
91
|
+
min_lift: float | None = None,
|
|
92
|
+
lift_baseline: float | None = None) -> list:
|
|
93
|
+
"""
|
|
94
|
+
rules : list of items to test. Each item is either
|
|
95
|
+
- a single rule string 'home_attack_rating >= 3'
|
|
96
|
+
- an AND combination dict {'home_attack_rating': '>= 3',
|
|
97
|
+
'away_defense_rating': '0 to 2'}
|
|
98
|
+
(the output of combo_bin_rules). A dict of column -> list[str]
|
|
99
|
+
is also accepted and flattened into single rules.
|
|
100
|
+
outcome_col : column that marks a hit (1/True = hit), default 'hit'
|
|
101
|
+
min_coverage : minimum % of total df rows an item must match (0-100), default 20
|
|
102
|
+
shrinkage_n : minimum number of rows (count) an item needs, default 30
|
|
103
|
+
top_n : None (off) or a positive integer. After all checks, keep only the
|
|
104
|
+
first n items (best Wilson first) and return them.
|
|
105
|
+
z : 1.96 = 95% confidence (1.645 = 90%, 2.576 = 99%)
|
|
106
|
+
display : print the title, funnel block and table of qualified items
|
|
107
|
+
title : heading printed above the block, default 'Train'
|
|
108
|
+
drop_duplicate : default True. Items that use the same column(s) compete, and only the
|
|
109
|
+
one with the top Wilson is kept.
|
|
110
|
+
wilson_rate : None (off) or a number between 0 and 100 (in percent, same scale as
|
|
111
|
+
the 'wilson' column). Items whose Wilson is less than this value are
|
|
112
|
+
removed. An item exactly equal to wilson_rate is kept. Default None.
|
|
113
|
+
min_lift : None (off) or a number (percentage points, same scale as the 'lift'
|
|
114
|
+
column = hit_rate - base_rate). When given, it REPLACES the baseline
|
|
115
|
+
check: items whose lift is less than this value are removed (an item
|
|
116
|
+
exactly equal to min_lift is kept). When None, the baseline check
|
|
117
|
+
(wilson > baseline) is used instead. Default None.
|
|
118
|
+
lift_baseline : None or a number between 0 and 100 (percent). The hit rate that lift
|
|
119
|
+
is measured against: lift = hit_rate - lift_baseline. When None, the
|
|
120
|
+
hit rate of df itself is used. Only the 'lift' column and the
|
|
121
|
+
min_lift check use it; the baseline check (wilson > baseline) still
|
|
122
|
+
uses the hit rate of df. Default None.
|
|
123
|
+
|
|
124
|
+
Checks enforced, in order (each item is charged to the FIRST one it fails):
|
|
125
|
+
shrinkage_n -> min_coverage -> full coverage (<100) -> baseline (wilson > baseline)
|
|
126
|
+
OR min_lift (when passed) -> wilson_rate -> drop_duplicate -> top_n
|
|
127
|
+
|
|
128
|
+
Returns : list of items that passed ALL checks, sorted by Wilson (descending),
|
|
129
|
+
in the same form they were given (strings stay strings, dicts stay dicts).
|
|
130
|
+
"""
|
|
131
|
+
if not isinstance(df, pd.DataFrame):
|
|
132
|
+
raise TypeError(f"df must be a pandas DataFrame, got {type(df).__name__}.")
|
|
133
|
+
if outcome_col not in df.columns:
|
|
134
|
+
raise KeyError(f"Outcome column '{outcome_col}' not found in df.")
|
|
135
|
+
if not isinstance(min_coverage, (int, float)) or not 0 <= min_coverage <= 100:
|
|
136
|
+
raise ValueError(f"min_coverage must be a number between 0 and 100, got {min_coverage!r}.")
|
|
137
|
+
if not isinstance(shrinkage_n, int) or isinstance(shrinkage_n, bool) or shrinkage_n < 0:
|
|
138
|
+
raise ValueError(f"shrinkage_n must be a non-negative integer, got {shrinkage_n!r}.")
|
|
139
|
+
if top_n is not None and (
|
|
140
|
+
isinstance(top_n, bool) or not isinstance(top_n, int) or top_n < 1):
|
|
141
|
+
raise ValueError(f"top_n must be None or a positive integer, got {top_n!r}.")
|
|
142
|
+
if not isinstance(drop_duplicate, bool):
|
|
143
|
+
raise TypeError(f"drop_duplicate must be a bool, got {type(drop_duplicate).__name__}.")
|
|
144
|
+
if wilson_rate is not None and (
|
|
145
|
+
isinstance(wilson_rate, bool)
|
|
146
|
+
or not isinstance(wilson_rate, (int, float))
|
|
147
|
+
or not 0 <= wilson_rate <= 100):
|
|
148
|
+
raise ValueError(f"wilson_rate must be None or a number between 0 and 100, got {wilson_rate!r}.")
|
|
149
|
+
if min_lift is not None and (
|
|
150
|
+
isinstance(min_lift, bool)
|
|
151
|
+
or not isinstance(min_lift, (int, float))
|
|
152
|
+
or not -100 <= min_lift <= 100):
|
|
153
|
+
raise ValueError(f"min_lift must be None or a number between -100 and 100, got {min_lift!r}.")
|
|
154
|
+
if lift_baseline is not None and (
|
|
155
|
+
isinstance(lift_baseline, bool)
|
|
156
|
+
or not isinstance(lift_baseline, (int, float))
|
|
157
|
+
or not 0 <= lift_baseline <= 100):
|
|
158
|
+
raise ValueError(f"lift_baseline must be None or a number between 0 and 100, got {lift_baseline!r}.")
|
|
159
|
+
|
|
160
|
+
# a single combo dict {col: 'rule'} is one item; a dict of column -> list[str] is flattened
|
|
161
|
+
if isinstance(rules, dict):
|
|
162
|
+
if rules and all(isinstance(v, str) for v in rules.values()):
|
|
163
|
+
items = [rules]
|
|
164
|
+
else:
|
|
165
|
+
items = flatten_rules(rules)
|
|
166
|
+
else:
|
|
167
|
+
items = rules
|
|
168
|
+
if not isinstance(items, list):
|
|
169
|
+
raise TypeError(f"rules must be a list of rule strings / combo dicts, got {type(items).__name__}.")
|
|
170
|
+
|
|
171
|
+
def _parts(item):
|
|
172
|
+
"""item -> list of 'column condition' strings that are ANDed together."""
|
|
173
|
+
if isinstance(item, str):
|
|
174
|
+
return [item.strip()]
|
|
175
|
+
if isinstance(item, dict) and item:
|
|
176
|
+
return [f"{c} {r}".strip() for c, r in item.items()]
|
|
177
|
+
raise TypeError(f"Each item must be a rule string or a non-empty {{column: rule}} dict, got {item!r}.")
|
|
178
|
+
|
|
179
|
+
total = len(df)
|
|
180
|
+
base_rate = df[outcome_col].astype(bool).mean() if total else float('nan')
|
|
181
|
+
base_pct = base_rate * 100
|
|
182
|
+
lift_ref = base_rate if lift_baseline is None else lift_baseline / 100 # what lift is measured against
|
|
183
|
+
outcome = df[outcome_col].astype(bool)
|
|
184
|
+
|
|
185
|
+
# ---- score every item ----
|
|
186
|
+
rows = []
|
|
187
|
+
for item in items:
|
|
188
|
+
parts = _parts(item)
|
|
189
|
+
|
|
190
|
+
mask = rule_mask(df, parts[0])
|
|
191
|
+
for p in parts[1:]:
|
|
192
|
+
mask = mask & rule_mask(df, p) # AND
|
|
193
|
+
|
|
194
|
+
n = int(mask.sum())
|
|
195
|
+
coverage = (n / total * 100) if total else 0.0
|
|
196
|
+
hits = int(outcome[mask].sum())
|
|
197
|
+
hit_rate = hits / n if n else 0.0
|
|
198
|
+
cols_used = sorted(p.split(' ', 1)[0] for p in parts)
|
|
199
|
+
|
|
200
|
+
rows.append({
|
|
201
|
+
'rule': ' AND '.join(parts),
|
|
202
|
+
'column': ' + '.join(cols_used), # key for drop_duplicate
|
|
203
|
+
'item': item, # original form, returned at the end
|
|
204
|
+
'count': n,
|
|
205
|
+
'hits': hits,
|
|
206
|
+
'hit_rate': round(hit_rate * 100, 2),
|
|
207
|
+
'wilson': round(wilson_lower(hits, n, z) * 100, 2),
|
|
208
|
+
'coverage': round(coverage, 2),
|
|
209
|
+
# hit rate minus the lift baseline, in percentage points
|
|
210
|
+
'lift': round((hit_rate - lift_ref) * 100, 2),
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
cols = ['rule', 'column', 'item', 'count', 'hits', 'hit_rate', 'wilson', 'coverage', 'lift']
|
|
214
|
+
result = pd.DataFrame(rows, columns=cols)
|
|
215
|
+
n_total = len(result)
|
|
216
|
+
|
|
217
|
+
# ---- enforce checks: charge each item to the FIRST criterion it fails ----
|
|
218
|
+
fail_n = result['count'] < max(shrinkage_n, 1) # also catches count == 0
|
|
219
|
+
fail_cov = ~fail_n & (result['coverage'] < min_coverage)
|
|
220
|
+
fail_full = ~fail_n & ~fail_cov & (result['coverage'] >= 100)
|
|
221
|
+
if min_lift is None:
|
|
222
|
+
# lift judge not passed -> use the baseline check
|
|
223
|
+
fail_base = ~fail_n & ~fail_cov & ~fail_full & ~(result['wilson'] > base_pct)
|
|
224
|
+
fail_lift = pd.Series(False, index=result.index)
|
|
225
|
+
else:
|
|
226
|
+
# lift judge passed -> it replaces the baseline check
|
|
227
|
+
fail_base = pd.Series(False, index=result.index)
|
|
228
|
+
fail_lift = ~fail_n & ~fail_cov & ~fail_full & (result['lift'] < min_lift)
|
|
229
|
+
if wilson_rate is None:
|
|
230
|
+
fail_wilson = pd.Series(False, index=result.index) # check is off
|
|
231
|
+
else:
|
|
232
|
+
fail_wilson = (~fail_n & ~fail_cov & ~fail_full & ~fail_base & ~fail_lift
|
|
233
|
+
& (result['wilson'] < wilson_rate))
|
|
234
|
+
|
|
235
|
+
removed = {
|
|
236
|
+
'shrinkage_n': int(fail_n.sum()),
|
|
237
|
+
'min_coverage': int(fail_cov.sum()),
|
|
238
|
+
'full coverage': int(fail_full.sum()),
|
|
239
|
+
'baseline': int(fail_base.sum()),
|
|
240
|
+
'min_lift': int(fail_lift.sum()),
|
|
241
|
+
'wilson_rate': int(fail_wilson.sum()),
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
result = (result[~(fail_n | fail_cov | fail_full | fail_base | fail_lift | fail_wilson)]
|
|
245
|
+
.sort_values('wilson', ascending=False))
|
|
246
|
+
|
|
247
|
+
# Drop duplicates: best Wilson item per column (or column set for combinations)
|
|
248
|
+
before = len(result)
|
|
249
|
+
if drop_duplicate:
|
|
250
|
+
result = result.drop_duplicates(subset='column', keep='first')
|
|
251
|
+
removed['drop_duplicate'] = before - len(result)
|
|
252
|
+
|
|
253
|
+
# top_n: after all checks, keep only the first n (best Wilson)
|
|
254
|
+
before = len(result)
|
|
255
|
+
if top_n is not None:
|
|
256
|
+
result = result.head(top_n)
|
|
257
|
+
removed['top_n'] = before - len(result)
|
|
258
|
+
|
|
259
|
+
result = result.reset_index(drop=True)
|
|
260
|
+
|
|
261
|
+
# ---- display ----
|
|
262
|
+
if display:
|
|
263
|
+
BOLD, RESET = '\033[1m', '\033[0m'
|
|
264
|
+
print(f"\n{BOLD}{title}{RESET}")
|
|
265
|
+
print('-' * len(title))
|
|
266
|
+
|
|
267
|
+
enforced = [
|
|
268
|
+
('shrinkage_n', str(shrinkage_n), removed['shrinkage_n']),
|
|
269
|
+
('min_coverage', str(min_coverage), removed['min_coverage']),
|
|
270
|
+
('full coverage', '<100', removed['full coverage']),
|
|
271
|
+
('baseline', f"{base_pct:.2f}%", removed['baseline']),
|
|
272
|
+
('min_lift', f"{min_lift}", removed['min_lift']),
|
|
273
|
+
('wilson_rate', f"{wilson_rate}%", removed['wilson_rate']),
|
|
274
|
+
('drop_duplicate', '', removed['drop_duplicate']),
|
|
275
|
+
('top_n', str(top_n), removed['top_n']),
|
|
276
|
+
]
|
|
277
|
+
|
|
278
|
+
# symbols in one place, so all lines use the same kind of glyph
|
|
279
|
+
SYM_TOTAL = '✦' # try also: '◆' (solid diamond), '●', '■'
|
|
280
|
+
SYM_OK = '✔'
|
|
281
|
+
SYM_FAIL = '✘'
|
|
282
|
+
|
|
283
|
+
W_NAME, W_VAL = 15, 8
|
|
284
|
+
|
|
285
|
+
def _line(sym, name, val, rm=None):
|
|
286
|
+
base = f" {sym} {name:<{W_NAME}}{val:<{W_VAL}}"
|
|
287
|
+
return base if rm is None else f"{base}{SYM_FAIL} {rm}"
|
|
288
|
+
|
|
289
|
+
print(_line(SYM_TOTAL, 'total', n_total))
|
|
290
|
+
for name, val, rm in enforced:
|
|
291
|
+
if name == 'baseline' and min_lift is not None:
|
|
292
|
+
continue
|
|
293
|
+
if name == 'min_lift' and min_lift is None:
|
|
294
|
+
continue
|
|
295
|
+
if name == 'wilson_rate' and wilson_rate is None:
|
|
296
|
+
continue
|
|
297
|
+
if name == 'drop_duplicate' and not drop_duplicate:
|
|
298
|
+
continue
|
|
299
|
+
if name == 'top_n' and top_n is None:
|
|
300
|
+
continue
|
|
301
|
+
print(_line(SYM_OK, name, val, rm))
|
|
302
|
+
print(_line(SYM_TOTAL, 'passed', len(result)))
|
|
303
|
+
print()
|
|
304
|
+
|
|
305
|
+
if result.empty:
|
|
306
|
+
print("No rules met all criteria.")
|
|
307
|
+
else:
|
|
308
|
+
shown = result.drop(columns=['column', 'item'])
|
|
309
|
+
# display only: drop the one internal trailing "." (a user's own dot stays)
|
|
310
|
+
shown['rule'] = shown['rule'].str.replace(r'(?<=\S)\.(?= )', '', regex=True)
|
|
311
|
+
shown.index = range(1, len(shown) + 1) # 1-based, last index = n qualified
|
|
312
|
+
with pd.option_context('display.max_rows', None, 'display.max_colwidth', None,
|
|
313
|
+
'display.width', 200):
|
|
314
|
+
print(shown.to_string(formatters={'lift': lambda v: f"{v:+.2f}%"}))
|
|
315
|
+
|
|
316
|
+
return result['item'].tolist()
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
from math import isfinite
|
|
2
|
+
from numbers import Real
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
from quantile_edges import bin_rules
|
|
6
|
+
from sparpartner import stratifier
|
|
7
|
+
|
|
8
|
+
from .edge_points import edge_points
|
|
9
|
+
from .combo_bin_rules import combo_bin_rules
|
|
10
|
+
from .core_validations import validate
|
|
11
|
+
from .others import show_info
|
|
12
|
+
from .utils import _plain, _check_footprint, avg_wilson_rate, _print_footprint_check
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
MODULE_NAME = "[Edgepoint Booster.]\n" # put your module name here; printed first when display=True (empty = nothing printed)
|
|
16
|
+
TOP_COMBOS = 2 # Test keeps only its top 2 combinations (by Wilson rate)
|
|
17
|
+
LOOKALIKE_MAX_N = 385 # bin_rules sees only the last 385 rows of Test (bigger index = older)
|
|
18
|
+
TEST_SPLIT = "Test" # the one split name this file relies on
|
|
19
|
+
PRE_TEST_SPLIT = "Pre_test_2"
|
|
20
|
+
# names the stratifier may use for a split (lower case, spaces/hyphens as "_") -> our name.
|
|
21
|
+
# Add an alias here if a stratifier update renames the Test split.
|
|
22
|
+
SPLIT_ALIASES = {"test": TEST_SPLIT}
|
|
23
|
+
MIN_PRE_TEST_N = 1000 # Test is split only if at least this many rows remain besides the last LOOKALIKE_MAX_N
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _normalize_splits(chunks):
|
|
27
|
+
"""
|
|
28
|
+
Copy of the stratifier's splits with our own names, in the same order.
|
|
29
|
+
Names found in SPLIT_ALIASES are renamed (e.g. " TEST" -> "Test"); any other
|
|
30
|
+
name is kept as it is. Raises if there is no Test split or two splits end up
|
|
31
|
+
with the same name.
|
|
32
|
+
"""
|
|
33
|
+
out = {}
|
|
34
|
+
for name, part in chunks.items():
|
|
35
|
+
key = str(name).strip().lower().replace("-", "_").replace(" ", "_")
|
|
36
|
+
new = SPLIT_ALIASES.get(key, name)
|
|
37
|
+
if new in out:
|
|
38
|
+
raise ValueError(f"stratifier returned two splits named {new!r}: {list(chunks)}.")
|
|
39
|
+
out[new] = part
|
|
40
|
+
if TEST_SPLIT not in out:
|
|
41
|
+
raise ValueError(
|
|
42
|
+
f"stratifier returned no Test split, got {list(chunks)}. "
|
|
43
|
+
"Add its name to SPLIT_ALIASES."
|
|
44
|
+
)
|
|
45
|
+
return out
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _print_closest_lookalike(chunks, full_df):
|
|
49
|
+
"""
|
|
50
|
+
Print the Closest lookalike section: what was done to the Test split and
|
|
51
|
+
the number of hits and the hit rate (in percent) in the last
|
|
52
|
+
LOOKALIKE_MAX_N rows of full_df, the rows the edges are built from.
|
|
53
|
+
Prints only when Test was split in two (Pre_test_2 exists); otherwise it
|
|
54
|
+
prints nothing.
|
|
55
|
+
"""
|
|
56
|
+
if PRE_TEST_SPLIT not in chunks:
|
|
57
|
+
return
|
|
58
|
+
|
|
59
|
+
title = "Closest lookalike"
|
|
60
|
+
print(f"\n\033[1m{title}\033[0m")
|
|
61
|
+
print("-" * len(title))
|
|
62
|
+
print()
|
|
63
|
+
|
|
64
|
+
window = full_df.iloc[-LOOKALIKE_MAX_N:]
|
|
65
|
+
n = len(window)
|
|
66
|
+
hits = int(window["hit"].astype(bool).sum())
|
|
67
|
+
hit_rate = hits / n * 100 if n else 0
|
|
68
|
+
|
|
69
|
+
rows = [(f"{PRE_TEST_SPLIT}_len", f"{len(chunks[PRE_TEST_SPLIT]):,}")]
|
|
70
|
+
rows.append(("Lookalike_len", f"{n:,}"))
|
|
71
|
+
rows.append(("Lookalike_hits", f"{hits:,}"))
|
|
72
|
+
rows.append(("Lookalike_hit_rate", f"{hit_rate:.2f}%"))
|
|
73
|
+
|
|
74
|
+
w = max(len(label) for label, _ in rows)
|
|
75
|
+
for label, value in rows:
|
|
76
|
+
print(f"{label.ljust(w)} : {value}")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def train(
|
|
80
|
+
df,
|
|
81
|
+
min_coverage=20,
|
|
82
|
+
shrinkage_n=30,
|
|
83
|
+
directions="all",
|
|
84
|
+
display=True,
|
|
85
|
+
footprint=None,
|
|
86
|
+
wilson_rate=None,
|
|
87
|
+
):
|
|
88
|
+
"""
|
|
89
|
+
Build edges on the Test split, narrow them split by split, then do the
|
|
90
|
+
same for combinations of the surviving columns. The Test split keeps only
|
|
91
|
+
its top 2 combinations (TOP_COMBOS) by Wilson rate.
|
|
92
|
+
|
|
93
|
+
Each split is compared with its own baseline: the hit rate (in percent)
|
|
94
|
+
of that split, calculated from the "hit" column.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
df: DataFrame with the feature columns and the "hit" column.
|
|
98
|
+
min_coverage: Minimum coverage in percent. Smaller is disqualified.
|
|
99
|
+
shrinkage_n: Minimum rows per bin and per combination.
|
|
100
|
+
directions: "all", "left", "right", "range", or a dict of
|
|
101
|
+
column -> direction.
|
|
102
|
+
display: If True, print the split info, the Closest lookalike
|
|
103
|
+
section, the Edge point table and the Combos table (Test split
|
|
104
|
+
only), the combo summary, and the footprint check.
|
|
105
|
+
footprint: Optional {column: number} dict, e.g. {"age": 35, "score": 4}.
|
|
106
|
+
Every value used by a surviving combination must be an int or
|
|
107
|
+
float. After the last split it is checked against the surviving
|
|
108
|
+
combinations.
|
|
109
|
+
wilson_rate: Optional number from 0 to 100 (percent, same scale as
|
|
110
|
+
the Wilson column). Default None (off). If given, the Test split
|
|
111
|
+
of the combinations removes every combination whose Wilson is
|
|
112
|
+
below it. The other splits do not use it.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
Column names in everything returned and printed by the footprint check
|
|
116
|
+
are the plain names the user passed in (the internal trailing "." is
|
|
117
|
+
removed).
|
|
118
|
+
|
|
119
|
+
Without footprint: list of {column: rule} dicts that survived every split.
|
|
120
|
+
With footprint: (avg_wilson, status, matched), where avg_wilson is the
|
|
121
|
+
average Wilson rate in percent on the Test split of the combinations
|
|
122
|
+
that passed (0 when nothing passed), status is the number of
|
|
123
|
+
surviving top combinations the footprint passed, and matched is the
|
|
124
|
+
list of combinations that passed.
|
|
125
|
+
When only 1 combination passed, avg_wilson is multiplied by
|
|
126
|
+
SINGLE_DISCOUNT (0.9). Status colors:
|
|
127
|
+
2 -> 🟢 green (passed both)
|
|
128
|
+
1 -> 🟡 yellow (also when only 1 combination survived and passed)
|
|
129
|
+
0 -> 🔴 red (failed all, or nothing survived; matched is empty)
|
|
130
|
+
Status 0 is falsy, so `if status:` still works as a pass/fail test.
|
|
131
|
+
|
|
132
|
+
Raises:
|
|
133
|
+
ValueError: If wilson_rate is not None or a number from 0 to 100,
|
|
134
|
+
footprint is not a non-empty {column: number} dict
|
|
135
|
+
with string keys, a column of footprint that is used in a
|
|
136
|
+
surviving combination holds a value that is not an int or float
|
|
137
|
+
(bool, NaN and infinity are rejected), or a split is empty.
|
|
138
|
+
"""
|
|
139
|
+
if wilson_rate is not None and (
|
|
140
|
+
isinstance(wilson_rate, bool)
|
|
141
|
+
or not isinstance(wilson_rate, Real)
|
|
142
|
+
or not 0 <= wilson_rate <= 100
|
|
143
|
+
):
|
|
144
|
+
raise ValueError("wilson_rate must be None or a number from 0 to 100.")
|
|
145
|
+
|
|
146
|
+
if footprint is not None and (
|
|
147
|
+
not isinstance(footprint, dict)
|
|
148
|
+
or not footprint
|
|
149
|
+
or not all(isinstance(c, str) for c in footprint)
|
|
150
|
+
):
|
|
151
|
+
raise ValueError("footprint must be a non-empty {column: number} dict.")
|
|
152
|
+
|
|
153
|
+
# validate() adds a trailing "." to every feature column, so the footprint
|
|
154
|
+
# (typed with plain names) gets the same dot
|
|
155
|
+
if footprint is not None:
|
|
156
|
+
footprint = {f"{c}.": v for c, v in footprint.items()}
|
|
157
|
+
|
|
158
|
+
def finish(combos):
|
|
159
|
+
if footprint is None:
|
|
160
|
+
return [_plain(c) for c in combos]
|
|
161
|
+
|
|
162
|
+
combos = combos[:TOP_COMBOS] # never score more than the top 2
|
|
163
|
+
|
|
164
|
+
# a footprint value must be numeric wherever a combination uses its column
|
|
165
|
+
used = {c for combo in combos for c in combo}
|
|
166
|
+
for col in used & set(footprint):
|
|
167
|
+
v = footprint[col]
|
|
168
|
+
if isinstance(v, bool) or not isinstance(v, Real) or not isfinite(v):
|
|
169
|
+
raise ValueError(
|
|
170
|
+
f"footprint[{col.removesuffix('.')!r}] must be an int or float, got {v!r}."
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
score, matched, details = _check_footprint(footprint, combos)
|
|
174
|
+
status, matched, avg_wilson = avg_wilson_rate(chunks[TEST_SPLIT], matched)
|
|
175
|
+
|
|
176
|
+
if display:
|
|
177
|
+
_print_footprint_check(footprint, len(combos), score, details, avg_wilson)
|
|
178
|
+
|
|
179
|
+
if avg_wilson is None:
|
|
180
|
+
avg_wilson = 0
|
|
181
|
+
|
|
182
|
+
return avg_wilson, status, [_plain(c) for c in matched]
|
|
183
|
+
|
|
184
|
+
if display and MODULE_NAME:
|
|
185
|
+
print(f"\033[1m{MODULE_NAME}\033[0m\n")
|
|
186
|
+
|
|
187
|
+
full_df = validate(df, directions, min_coverage, shrinkage_n, display=display)
|
|
188
|
+
|
|
189
|
+
# the df columns now end with "."; a directions dict gets the same dot
|
|
190
|
+
if isinstance(directions, dict):
|
|
191
|
+
directions = {f"{c}.": d for c, d in directions.items()}
|
|
192
|
+
|
|
193
|
+
# stratify first so we go with good sampling
|
|
194
|
+
chunks, info = stratifier(full_df)
|
|
195
|
+
chunks = _normalize_splits(chunks) # our own split names, whatever the API calls them
|
|
196
|
+
|
|
197
|
+
if display:
|
|
198
|
+
show_info(info)
|
|
199
|
+
|
|
200
|
+
# a long Test is split in two: its last LOOKALIKE_MAX_N rows (bigger index = older)
|
|
201
|
+
# become the new "Test", the rows before them become "Pre_test_2".
|
|
202
|
+
# New order: the other splits, then Pre_test_2, then Test.
|
|
203
|
+
if len(chunks[TEST_SPLIT]) >= MIN_PRE_TEST_N + LOOKALIKE_MAX_N:
|
|
204
|
+
test_df = chunks[TEST_SPLIT]
|
|
205
|
+
chunks = {name: part for name, part in chunks.items() if name != TEST_SPLIT}
|
|
206
|
+
chunks[PRE_TEST_SPLIT] = test_df.iloc[:-LOOKALIKE_MAX_N]
|
|
207
|
+
chunks[TEST_SPLIT] = test_df.iloc[-LOOKALIKE_MAX_N:]
|
|
208
|
+
|
|
209
|
+
if display:
|
|
210
|
+
_print_closest_lookalike(chunks, full_df)
|
|
211
|
+
|
|
212
|
+
# Lookalike_hit_rate (percent): hit rate of the last LOOKALIKE_MAX_N rows of full_df,
|
|
213
|
+
# the same number the Closest lookalike section prints. It is the lift baseline.
|
|
214
|
+
lookalike_window = full_df.iloc[-LOOKALIKE_MAX_N:]
|
|
215
|
+
lookalike_hit_rate = (
|
|
216
|
+
lookalike_window["hit"].astype(bool).sum() / len(lookalike_window) * 100
|
|
217
|
+
if len(lookalike_window) else 0
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
# edges are built only from the last LOOKALIKE_MAX_N rows of full_df (bigger index = older)
|
|
221
|
+
columns_bins = bin_rules(
|
|
222
|
+
full_df.iloc[-LOOKALIKE_MAX_N:],
|
|
223
|
+
bin_pct=min_coverage,
|
|
224
|
+
min_bin_n=shrinkage_n,
|
|
225
|
+
directions=directions,
|
|
226
|
+
display=False, # check_hit_rate does the printing
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
# 1. single edges: each split's survivors go to the next split,
|
|
230
|
+
# and each split is compared with its own hit rate
|
|
231
|
+
qualified_rules = columns_bins
|
|
232
|
+
|
|
233
|
+
for split_name, split_df in chunks.items():
|
|
234
|
+
is_test = split_name == TEST_SPLIT
|
|
235
|
+
|
|
236
|
+
qualified_rules = edge_points(
|
|
237
|
+
split_df,
|
|
238
|
+
qualified_rules,
|
|
239
|
+
min_coverage=min_coverage,
|
|
240
|
+
shrinkage_n=shrinkage_n,
|
|
241
|
+
title="Edge points." if is_test else split_name,
|
|
242
|
+
drop_duplicate=is_test, # only Test drops duplicates
|
|
243
|
+
display=is_test and display, # only Test prints
|
|
244
|
+
lift_baseline=lookalike_hit_rate, # lift is measured against the lookalike hit rate
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
if not qualified_rules:
|
|
248
|
+
if display:
|
|
249
|
+
print(f"No rules survived {split_name}; stopping.")
|
|
250
|
+
return finish([])
|
|
251
|
+
|
|
252
|
+
# 2. combinations of the surviving columns, chained the same way
|
|
253
|
+
qualified_combos = combo_bin_rules(chunks[TEST_SPLIT], qualified_rules, display=False)
|
|
254
|
+
n_combos_total = len(qualified_combos)
|
|
255
|
+
|
|
256
|
+
for split_name, split_df in chunks.items():
|
|
257
|
+
is_test = split_name == TEST_SPLIT
|
|
258
|
+
|
|
259
|
+
qualified_combos = edge_points(
|
|
260
|
+
split_df,
|
|
261
|
+
qualified_combos,
|
|
262
|
+
min_coverage=min_coverage,
|
|
263
|
+
shrinkage_n=shrinkage_n,
|
|
264
|
+
top_n=TOP_COMBOS if is_test else None, # only Test cuts to the top 2
|
|
265
|
+
wilson_rate=wilson_rate if is_test else None, # only Test applies it
|
|
266
|
+
title="Combos." if is_test else split_name,
|
|
267
|
+
drop_duplicate=False,
|
|
268
|
+
display=is_test and display, # only Test prints
|
|
269
|
+
lift_baseline=lookalike_hit_rate, # lift is measured against the lookalike hit rate
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
if not qualified_combos:
|
|
273
|
+
if display:
|
|
274
|
+
print(f"No combinations survived {split_name}; stopping.")
|
|
275
|
+
break
|
|
276
|
+
|
|
277
|
+
if display:
|
|
278
|
+
print(f"\nCombos summary: {n_combos_total} generated in total, "
|
|
279
|
+
f"{len(qualified_combos)} survived all splits.")
|
|
280
|
+
|
|
281
|
+
return finish(qualified_combos)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
|
|
3
|
+
def show_info(info, title="Stratified Sample Info."):
|
|
4
|
+
lines = []
|
|
5
|
+
|
|
6
|
+
def fmt(v):
|
|
7
|
+
if isinstance(v, bool):
|
|
8
|
+
return str(v)
|
|
9
|
+
if isinstance(v, int):
|
|
10
|
+
return f"{v:,}"
|
|
11
|
+
if isinstance(v, float):
|
|
12
|
+
return f"{v:,.4f}".rstrip("0").rstrip(".")
|
|
13
|
+
return str(v)
|
|
14
|
+
|
|
15
|
+
def is_container(v):
|
|
16
|
+
return isinstance(v, (dict, list, tuple, pd.DataFrame, pd.Series))
|
|
17
|
+
|
|
18
|
+
def walk(obj, indent=0):
|
|
19
|
+
pad = " " * indent
|
|
20
|
+
|
|
21
|
+
if isinstance(obj, dict):
|
|
22
|
+
if not obj:
|
|
23
|
+
lines.append(f"{pad}(empty)")
|
|
24
|
+
return
|
|
25
|
+
width = max(len(str(k)) for k in obj)
|
|
26
|
+
for k, v in obj.items():
|
|
27
|
+
if is_container(v):
|
|
28
|
+
lines.append(f"{pad}{k}")
|
|
29
|
+
walk(v, indent + 1)
|
|
30
|
+
else:
|
|
31
|
+
lines.append(f"{pad}{str(k).ljust(width)} : {fmt(v)}")
|
|
32
|
+
|
|
33
|
+
elif isinstance(obj, (list, tuple)):
|
|
34
|
+
if not obj:
|
|
35
|
+
lines.append(f"{pad}(empty)")
|
|
36
|
+
elif not any(is_container(i) for i in obj):
|
|
37
|
+
lines.append(f"{pad}{', '.join(fmt(i) for i in obj)}")
|
|
38
|
+
else:
|
|
39
|
+
for i, item in enumerate(obj):
|
|
40
|
+
lines.append(f"{pad}[{i}]")
|
|
41
|
+
walk(item, indent + 1)
|
|
42
|
+
|
|
43
|
+
elif isinstance(obj, (pd.DataFrame, pd.Series)):
|
|
44
|
+
lines.extend(pad + l for l in obj.to_string().splitlines())
|
|
45
|
+
|
|
46
|
+
else:
|
|
47
|
+
lines.append(f"{pad}{fmt(obj)}")
|
|
48
|
+
|
|
49
|
+
walk(info)
|
|
50
|
+
|
|
51
|
+
print(f"\033[1m{title}\033[0m")
|
|
52
|
+
print("-" * len(title))
|
|
53
|
+
print()
|
|
54
|
+
print("\n".join(lines))
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
from math import sqrt
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
SINGLE_DISCOUNT = 0.9 # avg Wilson is multiplied by this when only 1 combo passed
|
|
7
|
+
|
|
8
|
+
# score = how many of the top combos the footprint passed
|
|
9
|
+
SCORE_MARKS = {
|
|
10
|
+
2: "🟢 GREEN",
|
|
11
|
+
1: "🟡 YELLOW",
|
|
12
|
+
0: "🔴 RED",
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _plain(combo):
|
|
17
|
+
"""Combination with the internal trailing "." removed from its column names."""
|
|
18
|
+
return {col.removesuffix("."): rule for col, rule in combo.items()}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _rule_holds(value, rule):
|
|
22
|
+
"""True if a single number satisfies a rule string."""
|
|
23
|
+
if rule.startswith(">= "):
|
|
24
|
+
return value >= float(rule[3:])
|
|
25
|
+
if rule.startswith("<= "):
|
|
26
|
+
return value <= float(rule[3:])
|
|
27
|
+
if rule.startswith("= "):
|
|
28
|
+
return value == float(rule[2:])
|
|
29
|
+
lo, hi = rule.split(" to ")
|
|
30
|
+
return float(lo) <= value <= float(hi)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _wilson_lower(hits, n, z=1.96):
|
|
34
|
+
"""Wilson lower bound of a hit rate, as a fraction (0 to 1)."""
|
|
35
|
+
if n == 0:
|
|
36
|
+
return 0.0
|
|
37
|
+
p = hits / n
|
|
38
|
+
centre = p + z * z / (2 * n)
|
|
39
|
+
margin = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n))
|
|
40
|
+
return (centre - margin) / (1 + z * z / n)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _combo_mask(df, combo):
|
|
44
|
+
"""Boolean mask of the rows that satisfy every rule of one combination."""
|
|
45
|
+
mask = pd.Series(True, index=df.index)
|
|
46
|
+
for col, rule in combo.items():
|
|
47
|
+
s = df[col]
|
|
48
|
+
if rule.startswith(">= "):
|
|
49
|
+
m = s >= float(rule[3:])
|
|
50
|
+
elif rule.startswith("<= "):
|
|
51
|
+
m = s <= float(rule[3:])
|
|
52
|
+
elif rule.startswith("= "):
|
|
53
|
+
m = s == float(rule[2:])
|
|
54
|
+
else:
|
|
55
|
+
lo, hi = rule.split(" to ")
|
|
56
|
+
m = (s >= float(lo)) & (s <= float(hi))
|
|
57
|
+
mask &= m
|
|
58
|
+
return mask
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def avg_wilson_rate(df, matched, outcome_col="hit", z=1.96,
|
|
62
|
+
single_discount=SINGLE_DISCOUNT):
|
|
63
|
+
"""
|
|
64
|
+
Average Wilson rate (in percent) of the combinations that passed,
|
|
65
|
+
measured on df (the Test split).
|
|
66
|
+
|
|
67
|
+
A lone combination is only one reading, so its average is multiplied by
|
|
68
|
+
single_discount. Two agreeing combinations are not discounted.
|
|
69
|
+
|
|
70
|
+
Returns (status, combos, avg_wilson):
|
|
71
|
+
status : number of combinations that passed (2, 1 or 0)
|
|
72
|
+
combos : the combinations that passed
|
|
73
|
+
avg_wilson : average Wilson in percent, rounded to 2 decimals;
|
|
74
|
+
None when nothing passed
|
|
75
|
+
"""
|
|
76
|
+
matched = list(matched)
|
|
77
|
+
status = len(matched)
|
|
78
|
+
if status == 0:
|
|
79
|
+
return 0, [], None
|
|
80
|
+
|
|
81
|
+
outcome = df[outcome_col].astype(bool)
|
|
82
|
+
wilsons = []
|
|
83
|
+
for combo in matched:
|
|
84
|
+
mask = _combo_mask(df, combo)
|
|
85
|
+
n = int(mask.sum())
|
|
86
|
+
hits = int(outcome[mask].sum())
|
|
87
|
+
wilsons.append(round(_wilson_lower(hits, n, z) * 100, 2))
|
|
88
|
+
|
|
89
|
+
avg = sum(wilsons) / status
|
|
90
|
+
if status == 1:
|
|
91
|
+
avg *= single_discount
|
|
92
|
+
|
|
93
|
+
return status, matched, round(avg, 2)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _fmt_value(v):
|
|
97
|
+
"""Short text for a footprint value: 35.0 -> 35, 3.14159 -> 3.1416."""
|
|
98
|
+
if float(v).is_integer():
|
|
99
|
+
return str(int(v))
|
|
100
|
+
return str(round(float(v), 4))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _check_footprint(footprint, combos):
|
|
104
|
+
"""
|
|
105
|
+
Test the footprint against every combination.
|
|
106
|
+
|
|
107
|
+
Returns (score, matched, details):
|
|
108
|
+
score : number of combinations that passed (0 to TOP_COMBOS)
|
|
109
|
+
matched : list of combinations that passed, in their original order
|
|
110
|
+
details : one entry per combination (original order) as
|
|
111
|
+
(combo, [(rule_text, value_text, ok), ...], passed)
|
|
112
|
+
"""
|
|
113
|
+
details = []
|
|
114
|
+
for combo in combos:
|
|
115
|
+
lines = []
|
|
116
|
+
for col, rule in combo.items():
|
|
117
|
+
if col in footprint:
|
|
118
|
+
val_txt = f"({_fmt_value(footprint[col])})"
|
|
119
|
+
ok = _rule_holds(footprint[col], rule)
|
|
120
|
+
else:
|
|
121
|
+
val_txt = "(missing)"
|
|
122
|
+
ok = False
|
|
123
|
+
lines.append((f"{col.removesuffix('.')} {rule}", val_txt, ok))
|
|
124
|
+
details.append((combo, lines, all(ok for _, _, ok in lines)))
|
|
125
|
+
|
|
126
|
+
matched = [combo for combo, _, passed in details if passed]
|
|
127
|
+
return len(matched), matched, details
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _print_footprint_check(footprint, total, score, details, avg_wilson=None):
|
|
131
|
+
"""Print the FOOTPRINT CHECK section: aligned rules, values and marks."""
|
|
132
|
+
title = "FOOTPRINT CHECK."
|
|
133
|
+
print(f"\n\033[1m{title}\033[0m")
|
|
134
|
+
print("-" * len(title))
|
|
135
|
+
print()
|
|
136
|
+
print(f"status : {SCORE_MARKS[score]} ({score})")
|
|
137
|
+
print(f"footprint : {len(footprint)} columns")
|
|
138
|
+
print(f"passed : {score} of {total} combos")
|
|
139
|
+
print(f"avg wilson: {'n/a' if avg_wilson is None else f'{avg_wilson}%'}")
|
|
140
|
+
|
|
141
|
+
if not details:
|
|
142
|
+
return
|
|
143
|
+
|
|
144
|
+
# fixed column widths so every mark lands in one straight vertical line
|
|
145
|
+
rule_w = max(len(txt) for _, lines, _ in details for txt, _, _ in lines)
|
|
146
|
+
val_w = max(len(val) for _, lines, _ in details for _, val, _ in lines)
|
|
147
|
+
num_w = len(str(len(details)))
|
|
148
|
+
indent = " " * (2 + num_w + 2) # continuation lines sit under the first rule
|
|
149
|
+
|
|
150
|
+
print()
|
|
151
|
+
for i, (_, lines, _) in enumerate(details, start=1):
|
|
152
|
+
for j, (txt, val, ok) in enumerate(lines):
|
|
153
|
+
prefix = f" {i:>{num_w}}. " if j == 0 else indent
|
|
154
|
+
print(f"{prefix}{txt:<{rule_w}} {val:<{val_w}} {'✔' if ok else '✘'}")
|
|
155
|
+
print()
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: edgepoint-booster
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Standalone extension for edgepoint (https://pypi.org/project/edgepoint/) that sharpens its general reads into specific positions by checking them against the closest lookalikes.
|
|
5
|
+
Author-email: Henry <osas2henry@gmail.com>
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Requires-Dist: pandas
|
|
9
|
+
Requires-Dist: quantile_edges
|
|
10
|
+
Requires-Dist: sparpartner
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
edgepoint_booster/__init__.py,sha256=UWvNa4uSxqgrzui2ny0tarTBgv7L5w93wz7p_hv0a9k,477
|
|
2
|
+
edgepoint_booster/combo_bin_rules.py,sha256=017BtXT9_WKwgg6V7EFNAe4ifl9DGvQ1FAnKf0ONZi4,2406
|
|
3
|
+
edgepoint_booster/core_validations.py,sha256=TnK8T5J6bYS9KJjthIGp0HMeTdReZEmnpODHMH_uzl4,8795
|
|
4
|
+
edgepoint_booster/edge_points.py,sha256=KDCgmKZDHyrLtGvSTkVXh37PneKcg-SX4MsrJAAuzZo,14866
|
|
5
|
+
edgepoint_booster/main.py,sha256=bjeTa5W5d6_GH1LnYiJICh4nd-UxuyfvcYrsiJ0EK9k,11678
|
|
6
|
+
edgepoint_booster/others.py,sha256=6nyc8uZc6P4imkcVLgTgGPp20LsX7A3JKtuVP1EH3r8,1637
|
|
7
|
+
edgepoint_booster/utils.py,sha256=HhMKLAunQPDYOFIOi_o6cO8XSiupDvA7fzQ7W2j0WR4,5227
|
|
8
|
+
edgepoint_booster-1.0.0.dist-info/METADATA,sha256=OIWyTi6lVfgwYJgGBTNefqBDT1qiQMHoimDLYiBSRPU,443
|
|
9
|
+
edgepoint_booster-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
edgepoint_booster-1.0.0.dist-info/top_level.txt,sha256=-WKzA0Y8OzZADMDr0PUTIsERf6oAWIcMlil08K-RstA,18
|
|
11
|
+
edgepoint_booster-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
edgepoint_booster
|