Skip to content

Learn a rule set: from one rule to many

← Rules

The model starts with one rule and adds rules where the slippage changes.

The mean absolute error of the slippage over 3000 orders, for 25 values of n_min.

1. One rule for everything

The model starts with a single rule that has no conditions: the default rule.

import numpy as np
from dense_armor.core.online.rules import AMRulesRegressor

r = np.random.default_rng(0)
m = AMRulesRegressor(n_min=100, seed=0)
for t in range(1, 101):
    s = float(r.uniform(-1, 1))
    m.learn_one({"size": s, "spread": float(r.uniform(-1, 1))}, 5.0 * (s > 0))
    if t in (1, 99, 100):
        print(t, len(m.rules_))
print(len(m.explain_one({"size": 0.5, "spread": 0.0})), len(m.explain_one({"size": -0.5, "spread": 0.0})))
1 0
99 0
100 1
0 1

In this example the list is still empty after 1 order and after 99 orders, so the default rule answers. At the 100th order (n_min) the first rule appears. Of the two test orders, one is covered by the new rule and the other is still answered by the default rule.

2. Waiting for n_min orders

A rule asks for a cut only after n_min orders.

import numpy as np
from dense_armor.core.online.rules import AMRulesRegressor

for n in (100, 250):
    r = np.random.default_rng(0)
    m = AMRulesRegressor(n_min=n, seed=0)
    for t in range(1, 1000):
        s = float(r.uniform(-1, 1))
        m.learn_one({"size": s, "spread": float(r.uniform(-1, 1))}, 5.0 * (s > 0))
        if m.rules_:
            print(n, t)
            break
100 100
250 250

With n_min = 100 the first rule appears at the 100th order, and with n_min = 250 at the 250th. If a rule does not find a cut, it tries again after n_min more orders.

3. Being sure: the margin and the tie

A rule cuts only if the best feature is clearly better than the second best.

import math

print(round(math.sqrt(math.log(1 / 1e-7) / (2 * 100)), 3), round(math.log(1 / 1e-7) / (2 * 0.05 ** 2), 1))
0.284 3223.6

The margin eps = sqrt(ln(1/delta) / (2n)) comes from the Hoeffding bound and shrinks as the rule sees more orders. With delta = 1e-7 it is 0.284 after 100 orders, and it falls under tau = 0.05 after 3223.6 orders.

To choose where to cut, the rule uses the variance ratio: how much a cut lowers the variance of the slippage inside the two groups, compared with the variance of all the orders. The rule cuts if the best feature is clearly ahead of the second best (the ratio of their variance ratios, plus eps, is below 1), or if eps has fallen under tau: then the two are treated as equal and the best is taken anyway. Which side of the cut becomes the condition is a choice of the library; the paper does not fix it.

With two identical features the rule has no way to choose between them until eps falls under tau:

import numpy as np
from dense_armor.core.online.rules import AMRulesRegressor

r = np.random.default_rng(0)
m = AMRulesRegressor(n_min=100, seed=0)
for t in range(1, 4000):
    s = float(r.uniform(-1, 1))
    m.learn_one({"a": s, "b": s}, 5.0 * (s > 0))
    if m.rules_:
        print(t)
        break
3300

In this example the first cut comes at the 3300th order, the first multiple of n_min after 3223.6.

4. Who answers

The rules that cover an order answer, and the default rule answers if none does.

import numpy as np
from dense_armor.core.online.rules import AMRulesRegressor

r = np.random.default_rng(0)
m = AMRulesRegressor(n_min=100, seed=0)
for _ in range(1500):
    s = float(r.uniform(-1, 1))
    m.learn_one({"size": s, "spread": float(r.uniform(-1, 1))}, 5.0 * (s > 0))
print(len(m.rules_), len(m.explain_one({"size": 0.5, "spread": 0.0})), len(m.explain_one({"size": -0.5, "spread": 0.0})))
2 1 1

After 1500 orders there are 2 rules, and each of the two test orders is covered by one of them. When several rules cover the same order, their answers are averaged (the paper, Section 3.3).

5. What n_min does to the error

The mean absolute error of the slippage for three values of n_min.

The table shows the mean absolute error of the slippage, in basis points, over the block of 100 orders that ends at the order in the header (median of 3 streams):

n_min 100 500 1000 3000
20 1.093 0.245 0.179 0.126
101 2.217 0.272 0.181 0.614
400 2.217 0.225 0.145 0.209

6. The parameters

Parameter Meaning Default
n_min orders a rule sees before it tries to expand 200
delta one minus the confidence of the Hoeffding bound 1e-07
tau tie threshold on the bound 0.05
seed seed of the generator of the initial weights None
feature_keys names of the features; None takes the sorted keys of the first sample None

Source: Duarte, Gama, Bifet (2016), Algorithms 1 and 2, Sections 3.1 to 3.5.

7. The older example: the step

```pythonimport numpy as np from dense_armor.core.online.rules import AMRulesRegressor

rng = np.random.default_rng(0) m = AMRulesRegressor(n_min=100, seed=0) for _ in range(1500): a = float(rng.uniform(-1.0, 1.0)) m.learn_one({"a": a, "b": float(rng.uniform(-1.0, 1.0))}, 5.0 * (a > 0.0)) print(round(m.predict_one({"a": 0.5, "b": 0.0}), 1), round(m.predict_one({"a": -0.5, "b": 0.0}), 1)) print(m.explain_one({"a": 0.5, "b": 0.0}))


5.0 0.0 [[{'feature': 'a', 'op': '>', 'value': -5.4352682762992544e-05}]]
The target is 5 when `a` is positive and 0 otherwise; `b` is noise. The model answers 5.0 and 0.0, and `explain_one` lists the conditions of the rules that cover a sample.

![A step and the condition the rules found](../assets/rules/step_rules.png)

On a longer stream of the same kind (3000 samples, `n_min=100`) the condition found is `a > -0.0108`: the boundary of the step is at 0, and the rule is placed within 0.011 of it. The model holds 8 rules at the end, more than the step needs.

## 8. The same on a robot

The rules for the torque of a joint, after 1500 samples.

```python
import numpy as np
from dense_armor.core.online.rules import AMRulesRegressor

r = np.random.default_rng(1)
m = AMRulesRegressor(n_min=100, seed=0)
for _ in range(1500):
    v = float(r.uniform(-1, 1))
    m.learn_one({"speed": v, "load": float(r.uniform(-1, 1))}, 5.0 * (v > 0))
print(len(m.rules_), len(m.explain_one({"speed": 0.5, "load": 0.0})), len(m.explain_one({"speed": -0.5, "load": 0.0})))

2 1 1

Here too there are 2 rules, and each of the two test samples is covered by one of them.

API reference

AMRulesRegressor

AMRulesRegressor(
    ordered_set: bool = False,
    n_min: int = 200,
    delta: float = 1e-07,
    tau: float = 0.05,
    ph_lambda: float = 35.0,
    ph_phi: float = 0.005,
    alpha: float = 0.99,
    learning_rate: float = 0.01,
    prediction: str = "adaptive",
    anomaly_threshold: float | None = None,
    m_min: int = 30,
    max_split_points: int = 50,
    max_rules: int = 100,
    max_literals: int = 20,
    seed: int | None = None,
    feature_keys: list | None = None,
)

Bases: Regressor

Adaptive Model Rules regressor (Duarte, Gama and Bifet).

Cost and memory. learn_one updates the rules that cover the sample: for each, one insertion in a sorted list per feature (at most max_split_points values) and one small linear model; every n_min samples a rule scans its candidate splits. A model has at most max_rules rules of at most max_literals conditions and d * max_split_points stored split values each, so the state is constant in the length of the stream and linear in the number of features. There is no pure init_state / step form: the state is a set of rules of changing shape.

Parameters:

Name Type Description Default
ordered_set bool

True learns and predicts with the first rule that covers a sample; False (my choice) with all of them.

False
n_min int

samples a rule sees before it tries to expand. Default 200.

200
delta float

one minus the confidence of the Hoeffding bound. Default 1e-7.

1e-07
tau float

tie threshold on the bound. Default 0.05.

0.05
ph_lambda float

threshold of the Page-Hinkley test. Default 35.0. It is in the unit of the absolute error of the target.

35.0
ph_phi float

magnitude of the changes the Page-Hinkley test allows. Default 0.005.

0.005
alpha float

fading factor of the error that chooses the prediction strategy. Default 0.99.

0.99
learning_rate float

step of the delta rule of the linear models. Default 0.01.

0.01
prediction str

"adaptive", "mean" or "perceptron".

'adaptive'
anomaly_threshold float | None

threshold t of the anomaly score; a sample below it is ignored by the rule that finds it anomalous. None (my choice) turns the test off.

None
m_min int

samples a rule needs before it checks anomalies. Default 30.

30
max_split_points int

split values kept per feature and rule. Default 50.

50
max_rules int

largest number of rules. Default 100.

100
max_literals int

largest number of conditions of a rule. Default 20.

20
seed int | None

seed of the generator of the initial weights.

None
feature_keys list | None

names of the features. None takes the sorted keys of the first sample.

None

Raises:

Type Description
ValueError

on a non-positive n_min, learning_rate, ph_lambda, max_rules, max_literals or max_split_points, on delta outside (0, 1), alpha outside (0, 1), a negative tau, ph_phi or m_min, or an unknown prediction.

Examples:

>>> from dense_armor.core.online.rules.amrules import AMRulesRegressor
>>> model = AMRulesRegressor(seed=0)
>>> model.predict_one({"a": 1.0})
0.0
>>> _ = model.learn_one({"a": 1.0}, 2.0)
>>> model.predict_one({"a": 1.0})
2.0
References

Duarte, Gama, Bifet (2016), Algorithms 1 and 2, Sections 3.1 to 3.5.

Source code in dense_armor/core/online/rules/amrules.py
def __init__(
    self,
    ordered_set: bool = False,
    n_min: int = 200,
    delta: float = 1e-7,
    tau: float = 0.05,
    ph_lambda: float = 35.0,
    ph_phi: float = 0.005,
    alpha: float = 0.99,
    learning_rate: float = 0.01,
    prediction: str = "adaptive",
    anomaly_threshold: float | None = None,
    m_min: int = 30,
    max_split_points: int = 50,
    max_rules: int = 100,
    max_literals: int = 20,
    seed: int | None = None,
    feature_keys: list | None = None,
) -> None:
    if n_min < 1:
        raise ValueError(f"n_min must be >= 1, got {n_min}")
    if not 0.0 < delta < 1.0:
        raise ValueError(f"delta must be in (0, 1), got {delta}")
    if tau < 0.0:
        raise ValueError(f"tau must be >= 0, got {tau}")
    if ph_lambda <= 0.0:
        raise ValueError(f"ph_lambda must be > 0, got {ph_lambda}")
    if ph_phi < 0.0:
        raise ValueError(f"ph_phi must be >= 0, got {ph_phi}")
    if not 0.0 < alpha < 1.0:
        raise ValueError(f"alpha must be in (0, 1), got {alpha}")
    if learning_rate <= 0.0:
        raise ValueError(f"learning_rate must be > 0, got {learning_rate}")
    if prediction not in _PREDICTIONS:
        raise ValueError(
            f"prediction must be one of {_PREDICTIONS}, got {prediction!r}"
        )
    if m_min < 0:
        raise ValueError(f"m_min must be >= 0, got {m_min}")
    if max_split_points < 1 or max_rules < 1 or max_literals < 1:
        raise ValueError(
            "max_split_points, max_rules and max_literals must be >= 1"
        )
    self.ordered_set = ordered_set
    self.n_min = n_min
    self.delta = delta
    self.tau = tau
    self.ph_lambda = ph_lambda
    self.ph_phi = ph_phi
    self.alpha = alpha
    self.learning_rate = learning_rate
    self.prediction = prediction
    self.anomaly_threshold = anomaly_threshold
    self.m_min = m_min
    self.max_split_points = max_split_points
    self.max_rules = max_rules
    self.max_literals = max_literals
    self.seed = seed
    self.feature_keys = feature_keys
    self.rules_: list = []
    self.default_: _Rule | None = None
    self.n_seen_ = 0
    self.n_missing_ = 0
    self.n_anomalies_ = 0
    self.n_removed_ = 0
    self._keys: list | None = None
    self._rng = np.random.default_rng(seed)

learn_one

learn_one(
    x: Any, y: Any, t: float | None = None
) -> AMRulesRegressor

Update the rule set with one sample.

A sample with a missing or non-finite value or target is skipped and counted in n_missing.

Source code in dense_armor/core/online/rules/amrules.py
def learn_one(self, x: Any, y: Any, t: float | None = None) -> "AMRulesRegressor":
    """Update the rule set with one sample.

    A sample with a missing or non-finite value or target is skipped
    and counted in ``n_missing``.
    """
    self._time_step(t)
    try:
        target = float(y)
    except (TypeError, ValueError):
        target = math.nan
    v = self._vector(x) if math.isfinite(target) else None
    if v is None:
        self.n_missing_ += 1
        return self
    if self.default_ is None:
        self.default_ = _Rule(len(v), self._rng)
    self.n_seen_ += 1
    covered = False
    for rule in list(self.rules_):
        if not rule.covers(v):
            continue
        covered = True
        if self.anomaly_threshold is not None and rule.is_anomaly(
            v, self.anomaly_threshold, self.m_min
        ):
            self.n_anomalies_ += 1
        else:
            err = abs(rule.predict(v, self.prediction) - target)
            if rule.change_detected(err, self.ph_phi, self.ph_lambda):
                self.rules_.remove(rule)
                self.n_removed_ += 1
            else:
                rule.learn(
                    v, target, self.learning_rate, self.alpha, self.max_split_points
                )
                if rule.e_n % self.n_min == 0:
                    self._expand_rule(rule)
        if self.ordered_set:
            break
    if not covered:
        default = self.default_
        default.learn(
            v, target, self.learning_rate, self.alpha, self.max_split_points
        )
        if default.e_n % self.n_min == 0:
            self._expand_default()
    return self

predict_one

predict_one(
    x: Any, t: float | None = None, return_std: bool = False
) -> Any

Prediction of the covering rules, 0.0 before the first sample.

With return_std the result is a pair: the prediction and the mean of the standard deviations of the targets of the covering rules.

Source code in dense_armor/core/online/rules/amrules.py
def predict_one(
    self, x: Any, t: float | None = None, return_std: bool = False
) -> Any:
    """Prediction of the covering rules, 0.0 before the first sample.

    With ``return_std`` the result is a pair: the prediction and the
    mean of the standard deviations of the targets of the covering
    rules.
    """
    v = self._vector(x) if self.default_ is not None else None
    if v is None:
        return (0.0, 0.0) if return_std else 0.0
    rules = self._covering(v)
    out = float(np.mean([r.predict(v, self.prediction) for r in rules]))
    if return_std:
        return out, float(np.mean([r.target.std for r in rules]))
    return out

explain_one

explain_one(x: Any) -> list

Conditions of the rules that cover x ([] for the default rule).

Source code in dense_armor/core/online/rules/amrules.py
def explain_one(self, x: Any) -> list:
    """Conditions of the rules that cover ``x`` ([] for the default rule)."""
    v = self._vector(x) if self.default_ is not None else None
    if v is None or self._keys is None:
        return []
    keys = self._keys
    return [
        [
            {"feature": keys[j], "op": "<=" if le else ">", "value": c}
            for j, le, c in r.literals
        ]
        for r in self._covering(v)
        if r is not self.default_
    ]

Details

Choices

  • The figures are drawn by docs/assets/rules/make_rules_style_figures.py: orders with three features between -1 and 1, slippage 5 when the size is above 0 plus a noise of 0.1, error of the prediction made before each order is learned, blocks of 100 orders, median of 3 seeds. The value 101 of n_min is the nearest to 100 on the grid of 25 values.
  • The older toy stream of the page is in the section 7.