adanesy 0.1.0__tar.gz

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.

Potentially problematic release.


This version of adanesy might be problematic. Click here for more details.

adanesy-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ahmed T. Hammad
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
adanesy-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,328 @@
1
+ Metadata-Version: 2.4
2
+ Name: adanesy
3
+ Version: 0.1.0
4
+ Summary: Adaptive neuro-symbolic learning: online rule weights, rule induction and abductive predicate learning
5
+ Author: Ahmed T. Hammad
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/athammad/adanesy
8
+ Keywords: neuro-symbolic,rule learning,online learning,abductive learning,interpretable
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: numpy>=1.24
16
+ Requires-Dist: torch>=2.0
17
+ Provides-Extra: viz
18
+ Requires-Dist: matplotlib>=3.7; extra == "viz"
19
+ Provides-Extra: rich
20
+ Requires-Dist: rich>=13; extra == "rich"
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest>=7; extra == "test"
23
+ Dynamic: license-file
24
+
25
+ <p align="center"><img src="https://raw.githubusercontent.com/athammad/adanesy/main/assets/logo.png" alt="adanesy logo" width="220"></p>
26
+
27
+ <p align="center"><a href="https://github.com/athammad/adanesy/actions/workflows/tests.yml"><img src="https://github.com/athammad/adanesy/actions/workflows/tests.yml/badge.svg" alt="tests"></a></p>
28
+
29
+ # adanesy
30
+
31
+ **Adaptive neuro-symbolic learning, one example at a time.** `adanesy` learns a small book of readable rules
32
+ (`IF x1 > 0.14 AND col == 'red' THEN 1`) from a stream of tabular examples. The rules learn their weights, the
33
+ thresholds inside them move, new rules are induced and useless ones deleted, all online, with no batch retraining.
34
+
35
+ It does classification (binary and multi-class) and regression, with numeric and categorical features.
36
+
37
+ ## What "adaptive neuro-symbolic" means here
38
+
39
+ Each numeric feature becomes a set of **predicates** ("x1 is low / mid / high"): the value is turned into its
40
+ past-only empirical CDF (the share of earlier values below it) and cut into `n_states` zones at **learned
41
+ thresholds**. Those thresholds are the neural part. Categorical features give fixed atoms (`col == 'red'`).
42
+ The symbolic part is a pool of **weighted rules** `head IF a1 AND ... AND aL`.
43
+
44
+ After every example (`predict_one`, then `learn_one(x, y, weight)`) three mechanisms run:
45
+
46
+ 1. **Rule-weight learning.** One gradient step on the rule weights (classification) or THEN values (regression)
47
+ and on the predicate thresholds.
48
+ 2. **Abductive feedback to the predicates.** If the crisp rules got the example wrong, the model looks for the
49
+ fewest zone changes (up to `max_len`) that would have made them right, and takes one step that moves the
50
+ predicates toward those pseudo-labels. Reasoning corrects perception.
51
+ 3. **Online rule induction and deletion.** A rule whose removal does not raise the loss on the last `window`
52
+ examples is deleted. Free slots are filled with the candidates that lower that loss the most: single conditions,
53
+ or a surviving rule extended by one condition on another feature.
54
+
55
+ How a class is scored (leaky noisy-or): every class has a learned base score, its **leak**, and every firing
56
+ rule of the class adds its weight, `score(class) = 1 - (1 - leak) * prod(1 - weight)`; the highest score wins. The
57
+ leak carries the base rate, so a rule survives only if it separates the classes. `leak=False` gives the plain
58
+ noisy-or (every class starts from 0). When the scores tie exactly, the prediction is the fallback class: the one
59
+ with the largest total example weight so far (an example with weight 0 adds nothing). In regression, the prediction is a base value plus the THEN
60
+ values of the firing rules.
61
+
62
+ ## Examples
63
+
64
+ Jupyter notebooks in [`notebooks/`](https://github.com/athammad/adanesy/tree/main/notebooks), executed with their outputs: classification with the rule
65
+ book, diffs and every plot; regression; and a concept drift with a wrong prior rule, where you can watch rules
66
+ die and new ones take over.
67
+
68
+ ## Install
69
+
70
+ ```bash
71
+ pip install adanesy # numpy + torch
72
+ pip install "adanesy[viz]" # + matplotlib, for the plots and the live figure
73
+ pip install "adanesy[rich]" # + rich, colour in the live terminal view (optional)
74
+ pip install "adanesy[test]" # + pytest
75
+ ```
76
+
77
+ From a source checkout without installing: `PYTHONPATH=src python ...`.
78
+
79
+ ## Quickstart: classification
80
+
81
+ ```python
82
+ import numpy as np
83
+ from adanesy import AdaptiveNeSy
84
+
85
+ rng = np.random.default_rng(0)
86
+ x = rng.standard_normal((3000, 2))
87
+ X = [{"x1": a, "x2": b} for a, b in x]
88
+ y = ((x[:, 0] > 0) & (x[:, 1] > 0)).astype(int)
89
+
90
+ m = AdaptiveNeSy(numeric=["x1", "x2"], classes=[0, 1], max_rules=8, max_len=2, window=100, lr=0.1)
91
+ pred = m.fit_stream(X, y) # prequential: predict each example, then learn from it
92
+ print((pred[2000:] == y[2000:]).mean()) # accuracy on the last third
93
+ print(m.describe()) # the rules, strongest first
94
+ ```
95
+
96
+ Example by example, the same thing is:
97
+
98
+ ```python
99
+ for xi, yi in zip(X, y):
100
+ p = m.predict_one(xi)
101
+ m.learn_one(xi, yi) # optional weight=...
102
+ ```
103
+
104
+ `predict_proba_one(x)` returns the per-class noisy-or scores. They are each in [0, 1] and are **not**
105
+ normalised to sum to 1.
106
+
107
+ ## Multi-class with categorical features
108
+
109
+ ```python
110
+ col = rng.choice(["red", "blue"], 3000)
111
+ X = [{"x1": a, "x2": b, "col": c} for (a, b), c in zip(x, col)]
112
+ y = np.where(col == "red", "r", np.where(x[:, 0] > 0, "bp", "bn"))
113
+
114
+ m = AdaptiveNeSy(numeric=["x1", "x2"], categorical={"col": ["red", "blue"]},
115
+ classes=["r", "bp", "bn"], max_rules=8, max_len=2, window=100, lr=0.1)
116
+ m.fit_stream(X, y)
117
+ ```
118
+
119
+ `fit_stream` also takes a pandas DataFrame or a 2-D array (columns in the order numeric + categorical).
120
+ A missing value (`None`, NaN, absent key) makes every condition on that feature false; nothing is imputed.
121
+
122
+ ## Regression
123
+
124
+ ```python
125
+ y = 3 * (x[:, 0] > 0) - 2 * (x[:, 1] < -0.5) + 0.1 * rng.standard_normal(3000)
126
+ m = AdaptiveNeSy(numeric=["x1", "x2"], task="regression", max_rules=8, max_len=2, window=100, lr=0.05)
127
+ m.fit_stream(X, y)
128
+ ```
129
+
130
+ Regression waits one full `window` before it starts learning, so the target scale is not estimated from two or
131
+ three values.
132
+
133
+ ## Prior rules
134
+
135
+ ```python
136
+ m = AdaptiveNeSy(numeric=["x1", "x2"], categorical={"col": ["red", "blue"]}, classes=[0, 1])
137
+ m.add_rule(1, [("x1", "high"), ("col", "red")], weight=0.5) # zones: 0..n_states-1, or 'low' / 'high' ('mid' if 3)
138
+ ```
139
+
140
+ A prior rule is an ordinary rule: it is re-weighted, extended or deleted like any other. A wrong prior is dropped
141
+ once the data contradicts it. Regression takes `head=None` and `weight` as the starting THEN value (std units).
142
+
143
+ ## Reading the rules
144
+
145
+ ```python
146
+ m.rules_() # strongest first: id, slot, head, weight, conditions, body, born, age, origin
147
+ m.describe() # one rule per line
148
+
149
+ # read-only views
150
+ m.thresholds # [n_numeric, n_states-1] cuts as CDF shares
151
+ m.raw_thresholds # the same cuts as raw values: v is above a cut exactly when v > t
152
+ m.target_scale # (mean, std) of the regression target
153
+ m.base # regression prediction when no rule fires
154
+ m.leak # per-class base score (leaky noisy-or)
155
+ m.fallback # class predicted when the scores tie exactly
156
+ m.atom_labels # every predicate as (feature, zone) or (feature, value)
157
+ m.add_listener(fn) # fn(event) on every rule birth / deletion (kind, step, id, slot, head, body, origin, ...)
158
+
159
+ from adanesy import RuleHistory, prequential, to_text, to_markdown, rule_diff, to_python, to_json
160
+ h = RuleHistory(m) # attach before the stream
161
+ out = prequential(m, X, y, history=h) # predictions, noisy-or scores, history recorded after every example
162
+ print(to_text(m)) # the rule book, grouped by class, with weights, ages and the ELSE line
163
+ print(to_markdown(m)) # the same as a Markdown table
164
+ print("\n".join(rule_diff(h, 0, -1))) # + born, - deleted, ~ re-weighted, > threshold moved
165
+ src = to_python(m) # a standalone `def predict(x: dict)`, no library needed
166
+ js = to_json(m) # the rule book as JSON
167
+ ```
168
+
169
+ Example rule book after 1500 examples of `y = 1 iff x1 > 0 and col == 'red'`:
170
+
171
+ ```
172
+ RULE BOOK classification, 8/8 rules, 1500 examples seen
173
+ class 0
174
+ IF col == 'blue' THEN 0 (weight 0.974, age 1499)
175
+ IF x1 <= -1.276 THEN 0 (weight 0.899, age 1497)
176
+ IF -1.276 < x1 <= -0.03965 THEN 0 (weight 0.845, age 1497)
177
+ ...
178
+ class 1
179
+ IF x1 > -0.03965 AND col == 'red' THEN 1 (weight 0.906, age 1212)
180
+ ELSE (no rule fires, or scores tie): 0 (largest total example weight so far)
181
+ score(class) = 1 - prod(1 - weight) over its firing rules; the highest score wins
182
+ ```
183
+
184
+ Every rule has a stable id, its birth step (examples fully learned before it appeared), its age and its origin
185
+ (`prior` from `add_rule`, `induced`). Thresholds everywhere (`rules_()`, the rule book, the exports) are exact:
186
+ `x1 > t` is precisely the zone test the model applies given the values it has seen. `RuleHistory` listens to the
187
+ model's birth / deletion events; several histories can watch one model.
188
+
189
+ ### Exports
190
+
191
+ `to_python(m)` reproduces `predict_one` of the model as it is at export time. For classification it computes the
192
+ noisy-or in float64 where the model uses float32, so two class scores closer than float32 rounding (~1e-7) could
193
+ break the other way; exact ties (no rule fires) give the fallback in both. Regression agrees to float32 precision.
194
+ The export is a snapshot: the live model keeps moving its thresholds as it sees more data.
195
+
196
+ ## Evaluation (prequential)
197
+
198
+ `adanesy.scoring`: `prequential`, `running_mean`, `windowed_mean`, `accuracy`, `balanced_accuracy`,
199
+ `confusion_matrix`, `log_loss` (of the noisy-or scores: per example the sum of per-class binary cross-entropies,
200
+ the loss the model trains on; not a softmax log-loss, since the scores are not normalised), `mse`, `mae`, `r2`,
201
+ and `rule_stats(history)`: pool size, cumulative births and deaths, churn per example, mean rule age, weight
202
+ quantiles, lifetimes of deleted rules.
203
+
204
+ ```python
205
+ from adanesy.scoring import running_mean, windowed_mean, rule_stats
206
+ ok = out["y"] == out["pred"]
207
+ acc_curve, acc_200 = running_mean(ok), windowed_mean(ok, 200)
208
+ stats = rule_stats(h)
209
+ ```
210
+
211
+ ## Watching the rules
212
+
213
+ **In the terminal** (plain text, the main view):
214
+
215
+ ```python
216
+ from adanesy import LiveRuleBook
217
+ view = LiveRuleBook(every=100, history=h) # redraw every 100 examples
218
+ prequential(m, X, y, history=h, view=view)
219
+ ```
220
+
221
+ Each frame: a header (examples seen, running and recent accuracy or MSE, rules in the pool, births / deletions),
222
+ the rule book, and the changes since the previous frame. On a terminal it redraws in place (ANSI, or `rich` with
223
+ colour if installed); into a file or a captured stream it appends frames.
224
+
225
+ **As a figure** (`adanesy[viz]`):
226
+
227
+ ```python
228
+ from adanesy import LiveRuleView
229
+ prequential(m, X, y, view=LiveRuleView(every=200)) # Jupyter (inline) or a script with a GUI backend
230
+ ```
231
+
232
+ **Plots of a run** (`adanesy.viz`): `plot_rule_timeline(h)` (each rule a bar from birth to death, coloured by
233
+ class, opacity by mean weight), `plot_weights(h)` (weight trajectories), `plot_thresholds(h)` (cuts per feature
234
+ over time, raw values or CDF shares), `plot_metrics({...})` (prequential curves). matplotlib is imported only
235
+ when one of these is called.
236
+
237
+ ## Constructor parameters
238
+
239
+ Every argument is validated when the model is built: integers must be integers, `lr` and `sharpness` finite
240
+ and positive, `init_weight` and prior classification weights strictly inside (0, 1); `learn_one` sample weights
241
+ must be finite and non-negative (weight 0 still updates the feature statistics, but teaches the rules nothing).
242
+
243
+ | parameter | default | meaning |
244
+ |---|---|---|
245
+ | `numeric` | `()` | names of numeric features (learned-threshold predicates) |
246
+ | `categorical` | `None` | `{feature: [values]}`, one fixed atom per value |
247
+ | `task` | `"classification"` | or `"regression"` |
248
+ | `classes` | `None` | class labels (classification, at least 2) |
249
+ | `max_rules` | 16 | rule slots in the pool |
250
+ | `max_len` | 2 | maximum conditions per rule; also the abduction search depth |
251
+ | `window` | 50 | recent examples that rule induction and deletion look at |
252
+ | `lr` | 0.05 | SGD learning rate of every online step |
253
+ | `n_states` | 3 | zones per numeric feature (>= 2) |
254
+ | `init_weight` | 0.1 | weight of a newly induced classification rule |
255
+ | `sharpness` | `4 * n_states` | slope of the surrogate membership used for gradients |
256
+ | `abduction` | `True` | run the abductive step |
257
+ | `leak` | `True` | classification: learned per-class base score (leaky noisy-or) |
258
+ | `scaling` | `"running"` | regression target scale: `"running"` (all targets so far), `"fixed"` (first `window` targets, then frozen) or `"none"` (raw units) |
259
+
260
+ ## Life of a rule
261
+
262
+ - **Born.** After each example, every single condition and every pool rule extended by one condition on a feature
263
+ it does not use yet is a candidate, for every head. The candidates with the best likelihood gain
264
+ (classification, at weight `init_weight`) or squared-error gain (regression, at its least-squares THEN value) on
265
+ the last `window` examples fill the free slots. Only a positive gain qualifies.
266
+ - **Extended.** An extension is a new rule (the parent stays until it stops paying for itself), so a rule grows
267
+ one condition at a time up to `max_len`.
268
+ - **Weighted.** Each example moves its weight by one clipped gradient step; the thresholds of its conditions move
269
+ with the predicate updates and the abductive step.
270
+ - **Deleted.** When removing it would not raise the loss on the last `window` examples.
271
+
272
+ ## Speed
273
+
274
+ Milliseconds per `learn_one` (CPU, one process, x86_64, torch 2.14 CPU), after the rule pool has filled
275
+ (`benchmarks/benchmark.py`, stream `y = (x1 > 0) AND (x2 > 0)`, numeric features):
276
+
277
+ | features | max_len | max_rules | ms / example | abduction off |
278
+ |---|---|---|---|---|
279
+ | 2 | 1 | 16 | 5.3 | 3.6 |
280
+ | 2 | 3 | 64 | 7.8 | 2.8 |
281
+ | 10 | 2 | 16 | 4.0 | 2.5 |
282
+ | 10 | 3 | 64 | 5.6 | 3.9 |
283
+ | 30 | 1 | 64 | 13.7 | 17.2 |
284
+ | 30 | 2 | 64 | 8.4 | 6.5 |
285
+ | 30 | 3 | 64 | 14.6 | 10.8 |
286
+
287
+ Roughly 3-15 ms per example in every setting tried (full grid: run the script), i.e. about 70-300 examples per
288
+ second.
289
+
290
+ ## Limitations
291
+
292
+ - **Tabular only.** Features are numbers or categories in a dict.
293
+ - **Short AND rules.** Bodies are conjunctions of at most `max_len` conditions, each on a different feature; no OR
294
+ inside a rule, no negation beyond the zones, no relations between features.
295
+ - **Needs real signal.** Rules are chosen by their gain on the last `window` examples; with weak or no signal
296
+ those gains are noise, and so is the rule book.
297
+ - **Learning speed.** It learns from one pass, slowly: a clean 2-condition rule needed about 250 examples with
298
+ tuned settings before it appeared.
299
+ - **Cost.** Abduction tries zone changes over the features used by rules, up to `max_len` at a time, so its
300
+ cost grows with both; measured (Speed, above) it stays small. `abduction=False` turns it off.
301
+
302
+ ## References
303
+
304
+ - Dai, W.-Z., Xu, Q., Yu, Y., & Zhou, Z.-H. (2019). Bridging machine learning and logical reasoning by abductive
305
+ learning. *Advances in Neural Information Processing Systems 32* (NeurIPS 2019), 2811–2822.
306
+ - Delfosse, Q., Shindo, H., Dhami, D., & Kersting, K. (2023). Interpretable and explainable logical policies via
307
+ neurally guided symbolic abstraction. *Advances in Neural Information Processing Systems 36* (NeurIPS 2023),
308
+ 50838–50858.
309
+ - Huang, Y.-X., Hu, W.-C., Gao, E.-H., & Jiang, Y. (2024). ABLkit: a Python toolkit for abductive learning.
310
+ *Frontiers of Computer Science*, 18(6), 186354. https://doi.org/10.1007/s11704-024-40085-7
311
+ - Li, Z., Huang, J., & Naik, M. (2023). Scallop: A language for neurosymbolic programming. *Proceedings of the ACM
312
+ on Programming Languages*, 7(PLDI), Article 166, 1463–1487. https://doi.org/10.1145/3591280
313
+ - Wang, Z., Zhang, W., Liu, N., & Wang, J. (2021). Scalable rule-based representation learning for interpretable
314
+ classification. *Advances in Neural Information Processing Systems 34* (NeurIPS 2021). arXiv:2109.15103
315
+
316
+ ## Contributing
317
+
318
+ Contributions are welcome, and I am actively looking for them. Feel free to help: open an issue to report a bug,
319
+ propose an idea or ask a question, or send a pull request with code, tests, documentation or new examples.
320
+ Run the test suite before submitting:
321
+
322
+ ```bash
323
+ PYTHONPATH=src python -m pytest -q tests
324
+ ```
325
+
326
+ ## License
327
+
328
+ MIT, Ahmed T. Hammad.
@@ -0,0 +1,304 @@
1
+ <p align="center"><img src="https://raw.githubusercontent.com/athammad/adanesy/main/assets/logo.png" alt="adanesy logo" width="220"></p>
2
+
3
+ <p align="center"><a href="https://github.com/athammad/adanesy/actions/workflows/tests.yml"><img src="https://github.com/athammad/adanesy/actions/workflows/tests.yml/badge.svg" alt="tests"></a></p>
4
+
5
+ # adanesy
6
+
7
+ **Adaptive neuro-symbolic learning, one example at a time.** `adanesy` learns a small book of readable rules
8
+ (`IF x1 > 0.14 AND col == 'red' THEN 1`) from a stream of tabular examples. The rules learn their weights, the
9
+ thresholds inside them move, new rules are induced and useless ones deleted, all online, with no batch retraining.
10
+
11
+ It does classification (binary and multi-class) and regression, with numeric and categorical features.
12
+
13
+ ## What "adaptive neuro-symbolic" means here
14
+
15
+ Each numeric feature becomes a set of **predicates** ("x1 is low / mid / high"): the value is turned into its
16
+ past-only empirical CDF (the share of earlier values below it) and cut into `n_states` zones at **learned
17
+ thresholds**. Those thresholds are the neural part. Categorical features give fixed atoms (`col == 'red'`).
18
+ The symbolic part is a pool of **weighted rules** `head IF a1 AND ... AND aL`.
19
+
20
+ After every example (`predict_one`, then `learn_one(x, y, weight)`) three mechanisms run:
21
+
22
+ 1. **Rule-weight learning.** One gradient step on the rule weights (classification) or THEN values (regression)
23
+ and on the predicate thresholds.
24
+ 2. **Abductive feedback to the predicates.** If the crisp rules got the example wrong, the model looks for the
25
+ fewest zone changes (up to `max_len`) that would have made them right, and takes one step that moves the
26
+ predicates toward those pseudo-labels. Reasoning corrects perception.
27
+ 3. **Online rule induction and deletion.** A rule whose removal does not raise the loss on the last `window`
28
+ examples is deleted. Free slots are filled with the candidates that lower that loss the most: single conditions,
29
+ or a surviving rule extended by one condition on another feature.
30
+
31
+ How a class is scored (leaky noisy-or): every class has a learned base score, its **leak**, and every firing
32
+ rule of the class adds its weight, `score(class) = 1 - (1 - leak) * prod(1 - weight)`; the highest score wins. The
33
+ leak carries the base rate, so a rule survives only if it separates the classes. `leak=False` gives the plain
34
+ noisy-or (every class starts from 0). When the scores tie exactly, the prediction is the fallback class: the one
35
+ with the largest total example weight so far (an example with weight 0 adds nothing). In regression, the prediction is a base value plus the THEN
36
+ values of the firing rules.
37
+
38
+ ## Examples
39
+
40
+ Jupyter notebooks in [`notebooks/`](https://github.com/athammad/adanesy/tree/main/notebooks), executed with their outputs: classification with the rule
41
+ book, diffs and every plot; regression; and a concept drift with a wrong prior rule, where you can watch rules
42
+ die and new ones take over.
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ pip install adanesy # numpy + torch
48
+ pip install "adanesy[viz]" # + matplotlib, for the plots and the live figure
49
+ pip install "adanesy[rich]" # + rich, colour in the live terminal view (optional)
50
+ pip install "adanesy[test]" # + pytest
51
+ ```
52
+
53
+ From a source checkout without installing: `PYTHONPATH=src python ...`.
54
+
55
+ ## Quickstart: classification
56
+
57
+ ```python
58
+ import numpy as np
59
+ from adanesy import AdaptiveNeSy
60
+
61
+ rng = np.random.default_rng(0)
62
+ x = rng.standard_normal((3000, 2))
63
+ X = [{"x1": a, "x2": b} for a, b in x]
64
+ y = ((x[:, 0] > 0) & (x[:, 1] > 0)).astype(int)
65
+
66
+ m = AdaptiveNeSy(numeric=["x1", "x2"], classes=[0, 1], max_rules=8, max_len=2, window=100, lr=0.1)
67
+ pred = m.fit_stream(X, y) # prequential: predict each example, then learn from it
68
+ print((pred[2000:] == y[2000:]).mean()) # accuracy on the last third
69
+ print(m.describe()) # the rules, strongest first
70
+ ```
71
+
72
+ Example by example, the same thing is:
73
+
74
+ ```python
75
+ for xi, yi in zip(X, y):
76
+ p = m.predict_one(xi)
77
+ m.learn_one(xi, yi) # optional weight=...
78
+ ```
79
+
80
+ `predict_proba_one(x)` returns the per-class noisy-or scores. They are each in [0, 1] and are **not**
81
+ normalised to sum to 1.
82
+
83
+ ## Multi-class with categorical features
84
+
85
+ ```python
86
+ col = rng.choice(["red", "blue"], 3000)
87
+ X = [{"x1": a, "x2": b, "col": c} for (a, b), c in zip(x, col)]
88
+ y = np.where(col == "red", "r", np.where(x[:, 0] > 0, "bp", "bn"))
89
+
90
+ m = AdaptiveNeSy(numeric=["x1", "x2"], categorical={"col": ["red", "blue"]},
91
+ classes=["r", "bp", "bn"], max_rules=8, max_len=2, window=100, lr=0.1)
92
+ m.fit_stream(X, y)
93
+ ```
94
+
95
+ `fit_stream` also takes a pandas DataFrame or a 2-D array (columns in the order numeric + categorical).
96
+ A missing value (`None`, NaN, absent key) makes every condition on that feature false; nothing is imputed.
97
+
98
+ ## Regression
99
+
100
+ ```python
101
+ y = 3 * (x[:, 0] > 0) - 2 * (x[:, 1] < -0.5) + 0.1 * rng.standard_normal(3000)
102
+ m = AdaptiveNeSy(numeric=["x1", "x2"], task="regression", max_rules=8, max_len=2, window=100, lr=0.05)
103
+ m.fit_stream(X, y)
104
+ ```
105
+
106
+ Regression waits one full `window` before it starts learning, so the target scale is not estimated from two or
107
+ three values.
108
+
109
+ ## Prior rules
110
+
111
+ ```python
112
+ m = AdaptiveNeSy(numeric=["x1", "x2"], categorical={"col": ["red", "blue"]}, classes=[0, 1])
113
+ m.add_rule(1, [("x1", "high"), ("col", "red")], weight=0.5) # zones: 0..n_states-1, or 'low' / 'high' ('mid' if 3)
114
+ ```
115
+
116
+ A prior rule is an ordinary rule: it is re-weighted, extended or deleted like any other. A wrong prior is dropped
117
+ once the data contradicts it. Regression takes `head=None` and `weight` as the starting THEN value (std units).
118
+
119
+ ## Reading the rules
120
+
121
+ ```python
122
+ m.rules_() # strongest first: id, slot, head, weight, conditions, body, born, age, origin
123
+ m.describe() # one rule per line
124
+
125
+ # read-only views
126
+ m.thresholds # [n_numeric, n_states-1] cuts as CDF shares
127
+ m.raw_thresholds # the same cuts as raw values: v is above a cut exactly when v > t
128
+ m.target_scale # (mean, std) of the regression target
129
+ m.base # regression prediction when no rule fires
130
+ m.leak # per-class base score (leaky noisy-or)
131
+ m.fallback # class predicted when the scores tie exactly
132
+ m.atom_labels # every predicate as (feature, zone) or (feature, value)
133
+ m.add_listener(fn) # fn(event) on every rule birth / deletion (kind, step, id, slot, head, body, origin, ...)
134
+
135
+ from adanesy import RuleHistory, prequential, to_text, to_markdown, rule_diff, to_python, to_json
136
+ h = RuleHistory(m) # attach before the stream
137
+ out = prequential(m, X, y, history=h) # predictions, noisy-or scores, history recorded after every example
138
+ print(to_text(m)) # the rule book, grouped by class, with weights, ages and the ELSE line
139
+ print(to_markdown(m)) # the same as a Markdown table
140
+ print("\n".join(rule_diff(h, 0, -1))) # + born, - deleted, ~ re-weighted, > threshold moved
141
+ src = to_python(m) # a standalone `def predict(x: dict)`, no library needed
142
+ js = to_json(m) # the rule book as JSON
143
+ ```
144
+
145
+ Example rule book after 1500 examples of `y = 1 iff x1 > 0 and col == 'red'`:
146
+
147
+ ```
148
+ RULE BOOK classification, 8/8 rules, 1500 examples seen
149
+ class 0
150
+ IF col == 'blue' THEN 0 (weight 0.974, age 1499)
151
+ IF x1 <= -1.276 THEN 0 (weight 0.899, age 1497)
152
+ IF -1.276 < x1 <= -0.03965 THEN 0 (weight 0.845, age 1497)
153
+ ...
154
+ class 1
155
+ IF x1 > -0.03965 AND col == 'red' THEN 1 (weight 0.906, age 1212)
156
+ ELSE (no rule fires, or scores tie): 0 (largest total example weight so far)
157
+ score(class) = 1 - prod(1 - weight) over its firing rules; the highest score wins
158
+ ```
159
+
160
+ Every rule has a stable id, its birth step (examples fully learned before it appeared), its age and its origin
161
+ (`prior` from `add_rule`, `induced`). Thresholds everywhere (`rules_()`, the rule book, the exports) are exact:
162
+ `x1 > t` is precisely the zone test the model applies given the values it has seen. `RuleHistory` listens to the
163
+ model's birth / deletion events; several histories can watch one model.
164
+
165
+ ### Exports
166
+
167
+ `to_python(m)` reproduces `predict_one` of the model as it is at export time. For classification it computes the
168
+ noisy-or in float64 where the model uses float32, so two class scores closer than float32 rounding (~1e-7) could
169
+ break the other way; exact ties (no rule fires) give the fallback in both. Regression agrees to float32 precision.
170
+ The export is a snapshot: the live model keeps moving its thresholds as it sees more data.
171
+
172
+ ## Evaluation (prequential)
173
+
174
+ `adanesy.scoring`: `prequential`, `running_mean`, `windowed_mean`, `accuracy`, `balanced_accuracy`,
175
+ `confusion_matrix`, `log_loss` (of the noisy-or scores: per example the sum of per-class binary cross-entropies,
176
+ the loss the model trains on; not a softmax log-loss, since the scores are not normalised), `mse`, `mae`, `r2`,
177
+ and `rule_stats(history)`: pool size, cumulative births and deaths, churn per example, mean rule age, weight
178
+ quantiles, lifetimes of deleted rules.
179
+
180
+ ```python
181
+ from adanesy.scoring import running_mean, windowed_mean, rule_stats
182
+ ok = out["y"] == out["pred"]
183
+ acc_curve, acc_200 = running_mean(ok), windowed_mean(ok, 200)
184
+ stats = rule_stats(h)
185
+ ```
186
+
187
+ ## Watching the rules
188
+
189
+ **In the terminal** (plain text, the main view):
190
+
191
+ ```python
192
+ from adanesy import LiveRuleBook
193
+ view = LiveRuleBook(every=100, history=h) # redraw every 100 examples
194
+ prequential(m, X, y, history=h, view=view)
195
+ ```
196
+
197
+ Each frame: a header (examples seen, running and recent accuracy or MSE, rules in the pool, births / deletions),
198
+ the rule book, and the changes since the previous frame. On a terminal it redraws in place (ANSI, or `rich` with
199
+ colour if installed); into a file or a captured stream it appends frames.
200
+
201
+ **As a figure** (`adanesy[viz]`):
202
+
203
+ ```python
204
+ from adanesy import LiveRuleView
205
+ prequential(m, X, y, view=LiveRuleView(every=200)) # Jupyter (inline) or a script with a GUI backend
206
+ ```
207
+
208
+ **Plots of a run** (`adanesy.viz`): `plot_rule_timeline(h)` (each rule a bar from birth to death, coloured by
209
+ class, opacity by mean weight), `plot_weights(h)` (weight trajectories), `plot_thresholds(h)` (cuts per feature
210
+ over time, raw values or CDF shares), `plot_metrics({...})` (prequential curves). matplotlib is imported only
211
+ when one of these is called.
212
+
213
+ ## Constructor parameters
214
+
215
+ Every argument is validated when the model is built: integers must be integers, `lr` and `sharpness` finite
216
+ and positive, `init_weight` and prior classification weights strictly inside (0, 1); `learn_one` sample weights
217
+ must be finite and non-negative (weight 0 still updates the feature statistics, but teaches the rules nothing).
218
+
219
+ | parameter | default | meaning |
220
+ |---|---|---|
221
+ | `numeric` | `()` | names of numeric features (learned-threshold predicates) |
222
+ | `categorical` | `None` | `{feature: [values]}`, one fixed atom per value |
223
+ | `task` | `"classification"` | or `"regression"` |
224
+ | `classes` | `None` | class labels (classification, at least 2) |
225
+ | `max_rules` | 16 | rule slots in the pool |
226
+ | `max_len` | 2 | maximum conditions per rule; also the abduction search depth |
227
+ | `window` | 50 | recent examples that rule induction and deletion look at |
228
+ | `lr` | 0.05 | SGD learning rate of every online step |
229
+ | `n_states` | 3 | zones per numeric feature (>= 2) |
230
+ | `init_weight` | 0.1 | weight of a newly induced classification rule |
231
+ | `sharpness` | `4 * n_states` | slope of the surrogate membership used for gradients |
232
+ | `abduction` | `True` | run the abductive step |
233
+ | `leak` | `True` | classification: learned per-class base score (leaky noisy-or) |
234
+ | `scaling` | `"running"` | regression target scale: `"running"` (all targets so far), `"fixed"` (first `window` targets, then frozen) or `"none"` (raw units) |
235
+
236
+ ## Life of a rule
237
+
238
+ - **Born.** After each example, every single condition and every pool rule extended by one condition on a feature
239
+ it does not use yet is a candidate, for every head. The candidates with the best likelihood gain
240
+ (classification, at weight `init_weight`) or squared-error gain (regression, at its least-squares THEN value) on
241
+ the last `window` examples fill the free slots. Only a positive gain qualifies.
242
+ - **Extended.** An extension is a new rule (the parent stays until it stops paying for itself), so a rule grows
243
+ one condition at a time up to `max_len`.
244
+ - **Weighted.** Each example moves its weight by one clipped gradient step; the thresholds of its conditions move
245
+ with the predicate updates and the abductive step.
246
+ - **Deleted.** When removing it would not raise the loss on the last `window` examples.
247
+
248
+ ## Speed
249
+
250
+ Milliseconds per `learn_one` (CPU, one process, x86_64, torch 2.14 CPU), after the rule pool has filled
251
+ (`benchmarks/benchmark.py`, stream `y = (x1 > 0) AND (x2 > 0)`, numeric features):
252
+
253
+ | features | max_len | max_rules | ms / example | abduction off |
254
+ |---|---|---|---|---|
255
+ | 2 | 1 | 16 | 5.3 | 3.6 |
256
+ | 2 | 3 | 64 | 7.8 | 2.8 |
257
+ | 10 | 2 | 16 | 4.0 | 2.5 |
258
+ | 10 | 3 | 64 | 5.6 | 3.9 |
259
+ | 30 | 1 | 64 | 13.7 | 17.2 |
260
+ | 30 | 2 | 64 | 8.4 | 6.5 |
261
+ | 30 | 3 | 64 | 14.6 | 10.8 |
262
+
263
+ Roughly 3-15 ms per example in every setting tried (full grid: run the script), i.e. about 70-300 examples per
264
+ second.
265
+
266
+ ## Limitations
267
+
268
+ - **Tabular only.** Features are numbers or categories in a dict.
269
+ - **Short AND rules.** Bodies are conjunctions of at most `max_len` conditions, each on a different feature; no OR
270
+ inside a rule, no negation beyond the zones, no relations between features.
271
+ - **Needs real signal.** Rules are chosen by their gain on the last `window` examples; with weak or no signal
272
+ those gains are noise, and so is the rule book.
273
+ - **Learning speed.** It learns from one pass, slowly: a clean 2-condition rule needed about 250 examples with
274
+ tuned settings before it appeared.
275
+ - **Cost.** Abduction tries zone changes over the features used by rules, up to `max_len` at a time, so its
276
+ cost grows with both; measured (Speed, above) it stays small. `abduction=False` turns it off.
277
+
278
+ ## References
279
+
280
+ - Dai, W.-Z., Xu, Q., Yu, Y., & Zhou, Z.-H. (2019). Bridging machine learning and logical reasoning by abductive
281
+ learning. *Advances in Neural Information Processing Systems 32* (NeurIPS 2019), 2811–2822.
282
+ - Delfosse, Q., Shindo, H., Dhami, D., & Kersting, K. (2023). Interpretable and explainable logical policies via
283
+ neurally guided symbolic abstraction. *Advances in Neural Information Processing Systems 36* (NeurIPS 2023),
284
+ 50838–50858.
285
+ - Huang, Y.-X., Hu, W.-C., Gao, E.-H., & Jiang, Y. (2024). ABLkit: a Python toolkit for abductive learning.
286
+ *Frontiers of Computer Science*, 18(6), 186354. https://doi.org/10.1007/s11704-024-40085-7
287
+ - Li, Z., Huang, J., & Naik, M. (2023). Scallop: A language for neurosymbolic programming. *Proceedings of the ACM
288
+ on Programming Languages*, 7(PLDI), Article 166, 1463–1487. https://doi.org/10.1145/3591280
289
+ - Wang, Z., Zhang, W., Liu, N., & Wang, J. (2021). Scalable rule-based representation learning for interpretable
290
+ classification. *Advances in Neural Information Processing Systems 34* (NeurIPS 2021). arXiv:2109.15103
291
+
292
+ ## Contributing
293
+
294
+ Contributions are welcome, and I am actively looking for them. Feel free to help: open an issue to report a bug,
295
+ propose an idea or ask a question, or send a pull request with code, tests, documentation or new examples.
296
+ Run the test suite before submitting:
297
+
298
+ ```bash
299
+ PYTHONPATH=src python -m pytest -q tests
300
+ ```
301
+
302
+ ## License
303
+
304
+ MIT, Ahmed T. Hammad.