enuf 0.2__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.
- enuf-0.2.dist-info/METADATA +122 -0
- enuf-0.2.dist-info/RECORD +6 -0
- enuf-0.2.dist-info/WHEEL +5 -0
- enuf-0.2.dist-info/licenses/LICENSE.md +20 -0
- enuf-0.2.dist-info/top_level.txt +1 -0
- enuf.py +379 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: enuf
|
|
3
|
+
Version: 0.2
|
|
4
|
+
Summary: Trees that are good enough: small, fast, close to LightGBM
|
|
5
|
+
Author-email: Tim Menzies <timm@ieee.org>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/timm/enuf
|
|
8
|
+
Project-URL: Documentation, https://timm.github.io/enuf/
|
|
9
|
+
Project-URL: Source, https://github.com/timm/enuf
|
|
10
|
+
Keywords: random forest,decision trees,classification,regression,optimization,tabular data
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE.md
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# enuf : trees that are good enough
|
|
22
|
+
|
|
23
|
+
Small enough, fast enough, close enough. Here, enough means
|
|
24
|
+
262 lines of Python that stay within two AUC points of LightGBM's
|
|
25
|
+
36,328 lines of C++ over 98 classification sets, win outright on the
|
|
26
|
+
61 software-engineering ones, and also do regression (MAE within a
|
|
27
|
+
point of LightGBM) and optimization (rank, label 5, keep the best).
|
|
28
|
+
In the box: csv reading, equal-frequency bins, deep random forests
|
|
29
|
+
that cut on small-integer labels, tie-aware AUC, distance-to-heaven
|
|
30
|
+
over many goals, and a seeded Park-Miller random so one seed gives
|
|
31
|
+
one answer on any interpreter.
|
|
32
|
+
|
|
33
|
+
The code, pretty-printed three-up: [docs/index.html][docs]. One file:
|
|
34
|
+
`enuf.py`. No dependencies. Run it with pypy3 for speed (the big
|
|
35
|
+
corpus runs use it), or any Python 3.11+.
|
|
36
|
+
|
|
37
|
+
[docs]: https://timm.github.io/enuf/
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
1. **a Python.** Best: `brew install pypy3` (or `apt install pypy3`).
|
|
42
|
+
Plain CPython 3.11+ works too, slower.
|
|
43
|
+
2. **enuf:** copy `enuf.py` next to your code -- that is the whole
|
|
44
|
+
install -- or `pip install -e .` from this repo for a module on
|
|
45
|
+
your path.
|
|
46
|
+
3. **data:** `git clone https://github.com/timm/moot ~/gits/moot`
|
|
47
|
+
-- hundreds of csvs in the format below.
|
|
48
|
+
|
|
49
|
+
## Input format
|
|
50
|
+
|
|
51
|
+
One csv, first row names the columns. The names are the schema:
|
|
52
|
+
|
|
53
|
+
| name looks like | meaning |
|
|
54
|
+
|---|---|
|
|
55
|
+
| starts uppercase (`Age`) | numeric column |
|
|
56
|
+
| starts lowercase (`sex`) | symbolic column |
|
|
57
|
+
| ends in `!` (`class!`) | the class to predict |
|
|
58
|
+
| ends in `+` / `-` | a goal to maximize / minimize |
|
|
59
|
+
| ends in `X` (`idX`) | ignored |
|
|
60
|
+
| cell holds `?` | unknown value |
|
|
61
|
+
|
|
62
|
+
E.g. `moot/classify/weather.csv` -- `Temp`, `Humid` numeric;
|
|
63
|
+
`outlook`, `windy` symbolic; `play!` the (symbolic) class
|
|
64
|
+
(cells may be padded for alignment; whitespace is trimmed):
|
|
65
|
+
|
|
66
|
+
```csv
|
|
67
|
+
outlook, Temp, Humid, windy, play!
|
|
68
|
+
sunny, 85, 85, FALSE, no
|
|
69
|
+
sunny, 80, 90, TRUE, no
|
|
70
|
+
overcast, 83, 86, FALSE, yes
|
|
71
|
+
rainy, 70, 96, FALSE, yes
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Use
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
import enuf as b
|
|
78
|
+
tb = b.Tbl(b.csv("~/gits/moot/classify/diabetes.csv"))
|
|
79
|
+
at = tb.cols.klass.at
|
|
80
|
+
y = lambda row: row.labels[at] # its class label
|
|
81
|
+
f = b.Forest(tb, tb.rows, y) # 30 trees
|
|
82
|
+
print(b.aucs(f.votes(tb.rows, y))) # 0..100
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Regression: pass the Num summary and read `predict` --
|
|
86
|
+
`f = b.Forest(tb, tb.rows, y, b.Col); f.predict(row)`.
|
|
87
|
+
Optimization: `tb.disty(row)` is a row's distance to heaven over
|
|
88
|
+
the `+`/`-` goals; regress on that, sort by the prediction.
|
|
89
|
+
|
|
90
|
+
Note every cell is labeled at load: `row.labels[col.at]` holds a
|
|
91
|
+
small int `0..n-1` (`?` becomes `-1`), and each column's legend maps
|
|
92
|
+
back (`tb.cols.klass.labels[i]` = label i's name). That is why one
|
|
93
|
+
seed gives one answer anywhere.
|
|
94
|
+
|
|
95
|
+
Knobs sit in `b.the` (defaults in parentheses): `trees` (30),
|
|
96
|
+
`bins` (16), `cap` (200 rows per class), `leaf` (2), `maxd` (30),
|
|
97
|
+
`rf` (True: sqrt(|x|) columns per cut for classification, |x|/3 for
|
|
98
|
+
regression), `seed`, and for the rig's stats `prudence` (0.01: mean
|
|
99
|
+
gaps smaller than this are never called different).
|
|
100
|
+
|
|
101
|
+
## Output format
|
|
102
|
+
|
|
103
|
+
The experiment rigs (in enuf-dev, not this repo) print one line per
|
|
104
|
+
cross-validation fold:
|
|
105
|
+
|
|
106
|
+
data|scores|secs|test row ids
|
|
107
|
+
|
|
108
|
+
one score and seconds per learner, and the 0-based csv row numbers of
|
|
109
|
+
that fold's test set -- so any other tool can replay the exact same
|
|
110
|
+
folds. That replay is how LightGBM and TabICL were scored against
|
|
111
|
+
enuf on identical splits.
|
|
112
|
+
|
|
113
|
+
## Hack
|
|
114
|
+
|
|
115
|
+
Edit `enuf.py`; there is no build step. Everything else --
|
|
116
|
+
experiment rigs, the Lisp twin, the retired Lua/Yue line (it lives
|
|
117
|
+
in the attic), LightGBM/TabICL hooks, all scores, charts, and the
|
|
118
|
+
Makefile that regenerates this repo's `docs/` -- is in
|
|
119
|
+
[enuf-dev](https://github.com/timm/enuf-dev); there, `make
|
|
120
|
+
package` refreshes this repo.
|
|
121
|
+
|
|
122
|
+
(c) 2026 Tim Menzies <timm@ieee.org>, MIT license.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
enuf.py,sha256=Tg9pqGILHrUSBN1haUmJgXQOt7TyeWW6C7UVSDxcwDk,12111
|
|
2
|
+
enuf-0.2.dist-info/licenses/LICENSE.md,sha256=vw0aZIoMsjOsmZepFYtYgbzKD366Q4_z-MCgLe8FS98,1060
|
|
3
|
+
enuf-0.2.dist-info/METADATA,sha256=ivLu3ett6WX58ZIyDsLYML9uZZ3glVFrnhzx8MHyd20,4658
|
|
4
|
+
enuf-0.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
enuf-0.2.dist-info/top_level.txt,sha256=BoI5IoGy_-r-pXnXEBJFHOw_8y1RBq170Q4vNglQ5As,5
|
|
6
|
+
enuf-0.2.dist-info/RECORD,,
|
enuf-0.2.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Copyright © 2025 Tim Menzies
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
4
|
+
a copy of this software and associated documentation files (the
|
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
8
|
+
permit persons to whom the Software is furnished to do so, subject
|
|
9
|
+
to the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be
|
|
12
|
+
included in all copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
17
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
|
|
18
|
+
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
|
|
19
|
+
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
enuf
|
enuf.py
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
# vim: set ts=2 sw=2 sts=2 et cc=75:
|
|
2
|
+
"""
|
|
3
|
+
enuf: lightweight ensemble trees for classification, regression
|
|
4
|
+
(c) 2026 Tim Menzies <timm@ieee.org>, MIT license
|
|
5
|
+
|
|
6
|
+
Options:
|
|
7
|
+
seed=1234567891 random number seed (Park-Miller)
|
|
8
|
+
prudence=0.01 mean gaps under this are never 'different'
|
|
9
|
+
bins=16 labels per numeric column (syms: commonest 15)
|
|
10
|
+
trees=30 trees per forest
|
|
11
|
+
cap=200 rows kept per class (classification)
|
|
12
|
+
rcap=1000 rows kept, total (regression)
|
|
13
|
+
leaf=2 no cut may leave fewer rows than this
|
|
14
|
+
maxd=30 max tree depth
|
|
15
|
+
rf=True cols per cut: sqrt(|x|); regression |x|/3
|
|
16
|
+
p=2 Minkowski exponent for x-distance
|
|
17
|
+
"""
|
|
18
|
+
import re
|
|
19
|
+
from bisect import bisect_left, bisect_right
|
|
20
|
+
from math import ceil, exp, floor, inf, log, nan, sqrt
|
|
21
|
+
from os.path import expanduser
|
|
22
|
+
|
|
23
|
+
isa = isinstance
|
|
24
|
+
|
|
25
|
+
# Root of all things ----------------------------------------------------
|
|
26
|
+
def say(x):
|
|
27
|
+
if isa(x, float): x = ("%.2f" % x).rstrip("0").rstrip(".")
|
|
28
|
+
elif isa(x, (list, tuple)): x = "[%s]" % ", ".join(map(say, x))
|
|
29
|
+
elif hasattr(x,"__slots__"): x = {k:getattr(x,k) for k in x.__slots__}
|
|
30
|
+
if isa(x, dict): x = "{%s}"%" ".join(f":{k} {say(x[k])}" for k in x)
|
|
31
|
+
return str(x)
|
|
32
|
+
|
|
33
|
+
class Box:
|
|
34
|
+
def __init__(i, **d) : i.__dict__.update(**d)
|
|
35
|
+
def __repr__(i) : return type(i).__name__ + say(vars(i))
|
|
36
|
+
|
|
37
|
+
# config ----------------------------------------------------------------
|
|
38
|
+
def thing(s):
|
|
39
|
+
for f in (int, float):
|
|
40
|
+
try: return f(s)
|
|
41
|
+
except ValueError: pass
|
|
42
|
+
return {"True": True, "False": False}.get(s, s.strip())
|
|
43
|
+
|
|
44
|
+
the = Box(**{k: thing(v) for k,v in re.findall(r"(\w+)=(\S+)",__doc__)})
|
|
45
|
+
|
|
46
|
+
# csv ------------------------------------------------------------------
|
|
47
|
+
# csV rows. Headers start uppercase for numbers. Suffixes !, +, -, and X
|
|
48
|
+
# mark the class, goals to maximize or minimize, and columns to skip.
|
|
49
|
+
class Row(list):
|
|
50
|
+
__slots__ = ("labels", "d2h")
|
|
51
|
+
|
|
52
|
+
def csv(file):
|
|
53
|
+
with open(expanduser(file), encoding="utf-8") as f:
|
|
54
|
+
return [Row(thing(v) for v in line.split(","))
|
|
55
|
+
for s in f if (line := s.replace("\r", "").strip())]
|
|
56
|
+
|
|
57
|
+
# Column ----------------------------------------------------------------
|
|
58
|
+
# column and target summaries. Known labels are 0..n-1; "?" is -1,
|
|
59
|
+
# so "unknown" is always label < 0.
|
|
60
|
+
class Column(Box):
|
|
61
|
+
def __init__(i, txt, at): i.txt, i.at, i.n = txt, at, 0
|
|
62
|
+
|
|
63
|
+
def add(i, v, inc=1):
|
|
64
|
+
if v != "?":
|
|
65
|
+
i.n += inc
|
|
66
|
+
i.add_known(v, inc)
|
|
67
|
+
|
|
68
|
+
def cuts(i, rows, targets, mk, leaf):
|
|
69
|
+
bins = [mk() for _ in range(len(i.labels) + 1)]
|
|
70
|
+
for row, y in zip(rows, targets):
|
|
71
|
+
b = row.labels[i.at]
|
|
72
|
+
if b >= 0: bins[b].add(y)
|
|
73
|
+
prefix, total, rest = mk(), mk(), mk()
|
|
74
|
+
for bin in bins: yfold(total, bin)
|
|
75
|
+
for b, bin in enumerate(bins[:-1]):
|
|
76
|
+
left, right = i.split_bin(bin, prefix, total, rest)
|
|
77
|
+
if min(left.n, right.n) >= leaf:
|
|
78
|
+
yield (i, b), xpect(left, right)
|
|
79
|
+
|
|
80
|
+
def Col(txt="N", at=0):
|
|
81
|
+
return (Num if "A" <= txt[:1] <= "Z" else Sym)(txt, at)
|
|
82
|
+
|
|
83
|
+
# Sym ----------------------------------------------------------------
|
|
84
|
+
class Sym(Column):
|
|
85
|
+
def __init__(i, txt, at):
|
|
86
|
+
super().__init__(txt, at)
|
|
87
|
+
i.has = {}
|
|
88
|
+
|
|
89
|
+
def add_known(i, v, inc):
|
|
90
|
+
i.has[v] = i.has.get(v, 0) + inc
|
|
91
|
+
if i.has[v] <= 0: del i.has[v] # drop emptied keys
|
|
92
|
+
|
|
93
|
+
def div(i):
|
|
94
|
+
return -sum((p := n/i.n)*log(p) for n in i.has.values() if n>0)/log(2)
|
|
95
|
+
|
|
96
|
+
def mid(i): return None
|
|
97
|
+
|
|
98
|
+
def labels_for(i, n, rows=None):
|
|
99
|
+
def key(v):
|
|
100
|
+
txt = format(v, ".14g") if isa(v, float) else str(v)
|
|
101
|
+
return -i.has[v], txt
|
|
102
|
+
ranked = sorted(i.has, key=key)
|
|
103
|
+
return ranked[:max(0, min(len(ranked), n - 1))]
|
|
104
|
+
|
|
105
|
+
def label(i, v):
|
|
106
|
+
try: return i.labels.index(v)
|
|
107
|
+
except ValueError: return len(i.labels) # the rare pool
|
|
108
|
+
|
|
109
|
+
def class_labels(i): return i.labels_for(inf)
|
|
110
|
+
|
|
111
|
+
def split_bin(i, bin, prefix, total, rest):
|
|
112
|
+
return bin, yfold(total, bin, -1, rest)
|
|
113
|
+
|
|
114
|
+
def matches(i, label, cut): return label == cut
|
|
115
|
+
|
|
116
|
+
# Num ----------------------------------------------------------------
|
|
117
|
+
def bisect(t, v, le=False):
|
|
118
|
+
return (bisect_right if le else bisect_left)(t, v)
|
|
119
|
+
|
|
120
|
+
class Num(Column):
|
|
121
|
+
def __init__(i, txt="N", at=0):
|
|
122
|
+
super().__init__(txt, at)
|
|
123
|
+
i.mu, i.m2, i.goal = 0, 0, int(not txt.endswith("-"))
|
|
124
|
+
|
|
125
|
+
def add_known(i, v, inc):
|
|
126
|
+
if i.n <= 0: i.n = i.mu = i.m2 = 0; return # removed the last row
|
|
127
|
+
d = v - i.mu
|
|
128
|
+
i.mu += inc * d / i.n
|
|
129
|
+
i.m2 = max(0, i.m2 + inc * d * (v - i.mu))
|
|
130
|
+
|
|
131
|
+
def div(i): return 0 if i.n < 2 else sqrt(i.m2 / (i.n - 1))
|
|
132
|
+
|
|
133
|
+
def mid(i): return i.mu
|
|
134
|
+
|
|
135
|
+
def fold(i, b, inc, u):
|
|
136
|
+
n = i.n + inc * b.n
|
|
137
|
+
if n <= 0:
|
|
138
|
+
u.n, u.mu, u.m2 = 0, 0, 0
|
|
139
|
+
return u
|
|
140
|
+
mu = i.mu + inc * b.n * (b.mu - i.mu) / n
|
|
141
|
+
gap = b.mu - (mu if n < i.n else i.mu)
|
|
142
|
+
between = min(n, i.n) * b.n * gap * gap / max(n, i.n)
|
|
143
|
+
u.m2 = max(0, i.m2 + inc * (b.m2 + between))
|
|
144
|
+
u.mu, u.n = mu, n
|
|
145
|
+
return u
|
|
146
|
+
|
|
147
|
+
def norm(i, v):
|
|
148
|
+
z = (v - i.mu) / (i.div() + 1e-32)
|
|
149
|
+
return 1 / (1 + exp(-1.7 * max(-3, min(3, z))))
|
|
150
|
+
|
|
151
|
+
def labels_for(i, n, rows):
|
|
152
|
+
values = sorted(row[i.at] for row in rows if row[i.at] != "?")
|
|
153
|
+
if not values: return []
|
|
154
|
+
m = len(values)
|
|
155
|
+
return list(dict.fromkeys(values[j * m // n] for j in range(n)))
|
|
156
|
+
|
|
157
|
+
def label(i, v): return max(0, bisect_right(i.labels, v) - 1)
|
|
158
|
+
|
|
159
|
+
def split_bin(i, bin, prefix, total, rest):
|
|
160
|
+
return yfold(prefix, bin), yfold(total, bin, -1)
|
|
161
|
+
|
|
162
|
+
def matches(i, label, cut): return label <= cut
|
|
163
|
+
|
|
164
|
+
# Targets -------------------------------------------------------------
|
|
165
|
+
class Ys(Box):
|
|
166
|
+
def __init__(i, nk): i.nk, i.n, i.has = nk, 0, [0] * nk
|
|
167
|
+
|
|
168
|
+
def add(i, v):
|
|
169
|
+
if v >= 0:
|
|
170
|
+
i.has[v] += 1
|
|
171
|
+
i.n += 1
|
|
172
|
+
|
|
173
|
+
def div(i):
|
|
174
|
+
if i.n < 2: return 0
|
|
175
|
+
e = sum(-c * log(c) for c in i.has if c > 0)
|
|
176
|
+
return (e / i.n + log(i.n)) / log(2)
|
|
177
|
+
|
|
178
|
+
def mid(i): return i.has.index(max(i.has)) if i.has else None
|
|
179
|
+
|
|
180
|
+
def fold(i, b, inc, u):
|
|
181
|
+
for j, c in enumerate(b.has):
|
|
182
|
+
u.has[j] = i.has[j] + inc * c
|
|
183
|
+
u.n = i.n + inc * b.n
|
|
184
|
+
return u
|
|
185
|
+
|
|
186
|
+
# Generics -------------------------------------------------------------
|
|
187
|
+
def adds(vs, col=None):
|
|
188
|
+
col = Num() if col is None else col
|
|
189
|
+
for v in vs: col.add(v)
|
|
190
|
+
return col
|
|
191
|
+
|
|
192
|
+
def yfold(ys, other, inc=1, u=None):
|
|
193
|
+
return ys.fold(other, inc, ys if u is None else u)
|
|
194
|
+
|
|
195
|
+
def tolabel(col, v): return -1 if v == "?" else col.label(v)
|
|
196
|
+
|
|
197
|
+
# Tables -------------------------------------------------------------
|
|
198
|
+
class Cols(Box):
|
|
199
|
+
def __init__(i, names):
|
|
200
|
+
i.names, i.x, i.y, i.klass = names, [], [], None
|
|
201
|
+
i.all = [Col(txt, j) for j, txt in enumerate(names)]
|
|
202
|
+
for col in i.all:
|
|
203
|
+
suffix = col.txt[-1:]
|
|
204
|
+
if suffix == "X": continue
|
|
205
|
+
(i.y if suffix in ("+", "-", "!") else i.x).append(col)
|
|
206
|
+
if suffix == "!": i.klass = col
|
|
207
|
+
|
|
208
|
+
def add(i, row):
|
|
209
|
+
row = row if isa(row, Row) else Row(row)
|
|
210
|
+
for col in i.all: col.add(row[col.at])
|
|
211
|
+
return row
|
|
212
|
+
|
|
213
|
+
class Tbl(Box):
|
|
214
|
+
def __init__(i, rows):
|
|
215
|
+
i.cols, i._mids = Cols(rows[0]), None
|
|
216
|
+
i.rows = [i.cols.add(row) for row in rows[1:]]
|
|
217
|
+
i.labelall()
|
|
218
|
+
|
|
219
|
+
def add(i, row, inc=1):
|
|
220
|
+
"Grow (inc=1) or shrink (inc=-1) by one row; returns the row."
|
|
221
|
+
i._mids = None
|
|
222
|
+
row = row if isa(row, Row) else Row(row)
|
|
223
|
+
(i.rows.append if inc > 0 else i.rows.remove)(row)
|
|
224
|
+
for col in i.cols.all:
|
|
225
|
+
if row[col.at] != "?": col.add(row[col.at], inc)
|
|
226
|
+
return row
|
|
227
|
+
|
|
228
|
+
def labelall(i):
|
|
229
|
+
cols, klass, i.nk = i.cols.x[:], i.cols.klass, 0
|
|
230
|
+
for col in cols: col.labels = col.labels_for(the.bins, i.rows)
|
|
231
|
+
if isa(klass, Sym):
|
|
232
|
+
klass.labels = klass.class_labels()
|
|
233
|
+
cols.append(klass)
|
|
234
|
+
i.nk = len(klass.labels)
|
|
235
|
+
for row in i.rows:
|
|
236
|
+
row.labels = [None] * len(row)
|
|
237
|
+
for col in cols: row.labels[col.at] = tolabel(col, row[col.at])
|
|
238
|
+
|
|
239
|
+
def disty(i, row):
|
|
240
|
+
d, n = 0, 0
|
|
241
|
+
for col in i.cols.y:
|
|
242
|
+
v = row[col.at]
|
|
243
|
+
if v != "?":
|
|
244
|
+
d += (col.norm(v) - col.goal) ** 2
|
|
245
|
+
n += 1
|
|
246
|
+
return sqrt(d / max(n, 1))
|
|
247
|
+
|
|
248
|
+
def mids(tb):
|
|
249
|
+
"Cached centroid: one mid per column; Tbl.add invalidates it."
|
|
250
|
+
tb._mids = tb._mids or [col.mid() for col in tb.cols.all]
|
|
251
|
+
return tb._mids
|
|
252
|
+
|
|
253
|
+
def gap(col, a, b):
|
|
254
|
+
"0..1 distance between two values of one column; ? is far."
|
|
255
|
+
if a == "?" and b == "?": return 1
|
|
256
|
+
if isa(col, Sym): return a != b
|
|
257
|
+
a = col.norm(a) if a != "?" else (1 if col.norm(b) < .5 else 0)
|
|
258
|
+
b = col.norm(b) if b != "?" else (1 if a < .5 else 0)
|
|
259
|
+
return abs(a - b)
|
|
260
|
+
|
|
261
|
+
def distx(tb, row, point):
|
|
262
|
+
"Minkowski x-distance from row to point, over tb's x columns."
|
|
263
|
+
d = n = 0
|
|
264
|
+
for col in tb.cols.x:
|
|
265
|
+
d += gap(col, row[col.at], point[col.at]) ** the.p; n += 1
|
|
266
|
+
return (d / max(n, 1)) ** (1 / the.p)
|
|
267
|
+
|
|
268
|
+
# Tree -------------------------------------------------------------
|
|
269
|
+
# split search and trees. Numeric cuts use a threshold, symbolic cuts
|
|
270
|
+
# use equality, and unknowns go left.
|
|
271
|
+
def xpect(left, right):
|
|
272
|
+
return ((left.n * left.div() + right.n * right.div())
|
|
273
|
+
/ (left.n + right.n + 1e-32))
|
|
274
|
+
|
|
275
|
+
def best_cut(xcols, rows, targets, mk, m, leaf):
|
|
276
|
+
cuts = (c for col in pick(xcols, m)
|
|
277
|
+
for c in col.cuts(rows, targets, mk, leaf))
|
|
278
|
+
return min(cuts, key=lambda c: c[1], default=(None, None))[0]
|
|
279
|
+
|
|
280
|
+
class Tree(Box):
|
|
281
|
+
def __init__(i, rows, y, xcols, mk, m, leaf, maxd, lvl=0):
|
|
282
|
+
targets = [y(row) for row in rows]
|
|
283
|
+
i.ys, i.n, i.yes = adds(targets, mk()), len(rows), None
|
|
284
|
+
if lvl < maxd:
|
|
285
|
+
if cut := best_cut(xcols, rows, targets, mk, m, leaf):
|
|
286
|
+
i.col, i.v = cut
|
|
287
|
+
yes, no = [], []
|
|
288
|
+
for row in rows:
|
|
289
|
+
(yes if i.goes_left(row) else no).append(row)
|
|
290
|
+
i.yes = Tree(yes, y, xcols, mk, m, leaf, maxd, lvl + 1)
|
|
291
|
+
i.no = Tree(no, y, xcols, mk, m, leaf, maxd, lvl + 1)
|
|
292
|
+
|
|
293
|
+
def goes_left(i, row):
|
|
294
|
+
label = row.labels[i.col.at]
|
|
295
|
+
return label < 0 or i.col.matches(label, i.v)
|
|
296
|
+
|
|
297
|
+
def leaf_of(i, row):
|
|
298
|
+
while i.yes: i = i.yes if i.goes_left(row) else i.no
|
|
299
|
+
return i
|
|
300
|
+
|
|
301
|
+
# Sampling -------------------------------------------------------------
|
|
302
|
+
_seed = the.seed
|
|
303
|
+
|
|
304
|
+
def srand(n):
|
|
305
|
+
global _seed
|
|
306
|
+
_seed = n
|
|
307
|
+
|
|
308
|
+
def rand(n=1):
|
|
309
|
+
global _seed
|
|
310
|
+
_seed = 16807 * _seed % 2147483647
|
|
311
|
+
return 1 + floor(n * _seed / 2147483647)
|
|
312
|
+
|
|
313
|
+
def shuffle(t):
|
|
314
|
+
u = t[:1]
|
|
315
|
+
for j in range(1, len(t)):
|
|
316
|
+
k = rand(j + 1) - 1
|
|
317
|
+
u.append(u[k] if k < j else t[j])
|
|
318
|
+
u[k] = t[j]
|
|
319
|
+
return u
|
|
320
|
+
|
|
321
|
+
def pick(t, n=None):
|
|
322
|
+
n = n or len(t)
|
|
323
|
+
return shuffle(t)[:ceil(n)] if n < len(t) else t[:]
|
|
324
|
+
|
|
325
|
+
def capped(rows, y, n, nk=None):
|
|
326
|
+
shuffled = shuffle(rows)
|
|
327
|
+
if nk is None or nk is False: return shuffled[:max(0, floor(n))]
|
|
328
|
+
counts, kept = {}, []
|
|
329
|
+
for row in shuffled:
|
|
330
|
+
label = y(row)
|
|
331
|
+
counts[label] = counts.get(label, 0) + 1
|
|
332
|
+
if counts[label] <= n: kept.append(row)
|
|
333
|
+
return kept
|
|
334
|
+
|
|
335
|
+
# Forests -------------------------------------------------------------
|
|
336
|
+
class Forest(list):
|
|
337
|
+
def __init__(i, tb, rows, y, mk=None):
|
|
338
|
+
if mk is None: mk = lambda: Ys(tb.nk)
|
|
339
|
+
nk = getattr(mk(), "nk", None)
|
|
340
|
+
xcols, m = tb.cols.x, None
|
|
341
|
+
if the.rf and nk is not None:
|
|
342
|
+
m = ceil(sqrt(len(xcols))) # regression: all columns
|
|
343
|
+
cap = the.cap if nk is not None else the.rcap
|
|
344
|
+
if cap: rows = capped(rows, y, cap, nk)
|
|
345
|
+
for _ in range(the.trees):
|
|
346
|
+
sample = rows if the.trees == 1 else pick(rows, len(rows) // 2)
|
|
347
|
+
i.append(Tree(sample, y, xcols, mk, m, the.leaf, the.maxd))
|
|
348
|
+
|
|
349
|
+
def vote(i, row):
|
|
350
|
+
nk, w = i[0].ys.nk, len(i)
|
|
351
|
+
h = [0] * nk
|
|
352
|
+
for node in i:
|
|
353
|
+
ys = node.leaf_of(row).ys
|
|
354
|
+
for j, c in enumerate(ys.has):
|
|
355
|
+
h[j] += c / ys.n / w if ys.n else nan
|
|
356
|
+
return h
|
|
357
|
+
|
|
358
|
+
def votes(i, rows, y): return [(y(row), i.vote(row)) for row in rows]
|
|
359
|
+
|
|
360
|
+
def predict(i, row):
|
|
361
|
+
if not i: return nan
|
|
362
|
+
return sum(node.leaf_of(row).ys.mid() for node in i) / len(i)
|
|
363
|
+
|
|
364
|
+
# Scoring -------------------------------------------------------------
|
|
365
|
+
def auc(pos, neg):
|
|
366
|
+
if not pos or not neg: return None
|
|
367
|
+
neg.sort()
|
|
368
|
+
s = sum((bisect_left(neg, p) + bisect_right(neg, p)) / 2 for p in pos)
|
|
369
|
+
return s / (len(pos) * len(neg))
|
|
370
|
+
|
|
371
|
+
def aucs(wps):
|
|
372
|
+
n, weighted = 0, 0
|
|
373
|
+
for j in range(len(wps[0][1])):
|
|
374
|
+
pos, neg = [], []
|
|
375
|
+
for y, scores in wps:
|
|
376
|
+
(pos if y == j else neg).append(scores[j])
|
|
377
|
+
a = auc(pos, neg)
|
|
378
|
+
if a is not None: n, weighted = n + len(pos), weighted + len(pos) * a
|
|
379
|
+
return 100 * weighted / max(n, 1)
|