Skip to content

When the world changes: the alarm that removes a rule

← Rules

A rule that starts to fail is removed, and the default rule learns again.

The mean absolute error when the rule of the desk is swapped after 2000 orders, for 25 values of the Page-Hinkley threshold.

1. The alarm

In this example the rule of the slippage is swapped at the 1500th order: from then on the slippage is 5 when the size is not above 0.

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(2600):
    s = float(r.uniform(-1, 1))
    m.learn_one({"size": s, "spread": float(r.uniform(-1, 1))}, 5.0 * ((s > 0) == (t < 1500)))
    if t in (1499, 1599, 2599):
        print(t + 1, len(m.rules_), m.n_removed_)
1500 2 0
1600 1 1
2600 2 1

At the 1500th order the list has 2 rules and none has been removed. By the 1600th order 1 rule has been removed and 1 is left. At the 2600th order there are 2 rules again, and 1 rule has been removed in total.

Every rule keeps count of its own absolute error on the orders it covers. The Page-Hinkley test compares each error with the mean error so far: it adds up the gap, minus a small tolerance phi, and remembers the lowest value that the sum has reached. When the sum rises more than lambda above that lowest value, the error has been growing for too long to be chance, and the rule is removed (the paper, Section 3.4).

2. The threshold

The threshold ph_lambda is the size of the rise that the test accepts.

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

for lam in (0.5, 35.0, 1e9):
    r = np.random.default_rng(0)
    m = AMRulesRegressor(n_min=100, ph_lambda=lam, seed=0)
    for t in range(2600):
        s = float(r.uniform(-1, 1))
        m.learn_one({"size": s, "spread": float(r.uniform(-1, 1))}, 5.0 * ((s > 0) == (t < 1500)))
    print(lam, m.n_removed_)
0.5 9
35.0 1
1000000000.0 0

With ph_lambda = 0.5, 9 rules are removed; with 35, 1; with 1e9, none. A larger lambda gives fewer false alarms, but it may delay the detection of a change (the paper, Section 3.4).

3. After the alarm

The order that rings the alarm is not learned by any rule. The orders that the removed rule used to cover are learned by 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, max_rules=1, seed=0)
for _ in range(150):
    s = float(r.uniform(-1, 1))
    m.learn_one({"size": s, "spread": float(r.uniform(-1, 1))}, 5.0 * (s > 0) + 0.1 * float(r.normal()))
x = {"size": 0.5, "spread": 0.0}
print(len(m.explain_one(x)))
for _ in range(500):
    if not m.rules_:
        break
    m.learn_one({"size": float(r.uniform(0.1, 1)), "spread": float(r.uniform(-1, 1))}, 0.0)
print(len(m.explain_one(x)), round(m.predict_one(x), 2))
1
0 0.15

Before the alarm one rule covers the order. After it, none does, and the default rule answers.

4. What the threshold does to the error

The mean absolute error when the rule is swapped, for three values of ph_lambda.

The table shows the mean absolute error, in basis points, over the block of 100 orders that ends at the order in the header (the rule is swapped after 2000 orders; median of 3 streams):

ph_lambda 1900 2100 2500 4000
2 0.267 2.181 0.184 0.351
37.2 0.361 3.098 0.212 0.164
300 0.361 2.999 0.818 0.567

5. The parameters

Parameter Meaning Default
ph_lambda threshold of the Page-Hinkley test, in the unit of the absolute error of the target 35.0
ph_phi magnitude of the changes that the test allows 0.005
alpha fading factor of the error that chooses the prediction strategy 0.99

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

6. The older example: the targets are swapped

The next figure swaps the targets after the model has learned the step: the target is now 5 when a is not positive.

Error over the stream after the targets are swapped

The error over the first 100 samples after the swap is 2.93 and over the last 300 of 2000 it is 0.17; the Page-Hinkley test removed 7 rules on the way. The recovery is not smooth: the curve shows bumps while new rules replace the removed ones.

7. The same on a robot

The rule of the torque is swapped at the sample 1500.

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 t in range(2600):
    v = float(r.uniform(-1, 1))
    m.learn_one({"speed": v, "load": float(r.uniform(-1, 1))}, 5.0 * ((v > 0) == (t < 1500)))
    if t in (1499, 1599, 2599):
        print(t + 1, len(m.rules_), m.n_removed_)
1500 2 0
1600 1 2
2600 3 2

At the 1500th sample the list has 2 rules and none has been removed. By the 1600th sample 2 rules have been removed and 1 is left. At the 2600th sample there are 3 rules, and 2 rules have been removed in total.

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: 4000 orders, the rule swapped after 2000, n_min = 100, blocks of 100 orders, median of 3 seeds. The value 37.2 is the nearest to 35 on the grid of 25 values.
  • The older figure of the page, with its numbers, is in the section 6.