Skip to content

DriftStream: a stream whose concept changes

DriftStream makes a binary stream whose rule, the concept, is replaced at known places. The overview of the section is on Datasets.

To test a drift detector you need a stream whose rule changes at a known place. This binary stream changes its concept once, half way, gradually: near the change each sample comes from the old or the new concept with a probability that follows a sigmoid.

from dense_armor.core.signals.datasets import DriftStream

ds = DriftStream(n_samples=20000, n_features=2, n_drifts=1, kind="gradual", spacing=20.0, seed=0)
ds.data()
c = ds.concepts_
print([round(float(c[a:a + 1000].mean()), 2) for a in range(7000, 13000, 1000)])
[0.07, 0.22, 0.42, 0.61, 0.82, 0.92]

A concept is the rule that ties the input features to the class. In this generator each concept is two Gaussian clusters, one per class, in a random direction; the paper's own StreamGenerator builds them from make_classification and the Madelon rules (section 3, page 7). The stream visits one concept, then the next; the change sits at sample 10000. Each number in the output is the share of samples from the new concept in a window of 1000, from sample 7000 to 13000; it rises smoothly through the change (0.42 just before, 0.61 just after).

The weight of the new concept at position \(p \in [0, 1]\) of the stream is the sigmoid that Ksieniewicz and Zyblewski (2020) introduce for all three drift types in section 3.2.1 (page 8). The paper does not give its closed form; the generator uses the standard logistic form,

\[s(p) = \frac{1}{1 + e^{-\text{spacing}\,(p - d)}}\]

with \(p\) the position of the sample as a fraction of the stream, \(d = 0.5\) the position of the drift (half way) and spacing how sharp the change is. At \(p = d\) the sigmoid is exactly \(0.5\); with spacing \(= 20\) it goes from \(0.12\) at \(p = 0.4\) to \(0.88\) at \(p = 0.6\). The same sigmoid drives the three drift types of the paper (section 3.2, pages 8–9): "sudden" is the limit for a large spacing and swaps the concept at once, "gradual" draws the old or the new concept at each sample with probability s(p), "incremental" moves the clusters continuously with the same weight.

API reference

drift_stream

Synthetic binary stream with concept drift.

Follows the taxonomy of Ksieniewicz, P., Zyblewski, P. (2020), "stream-learn -- open-source Python library for difficult data stream batch analysis", SoftwareX 11, section 3. Three kinds of drift are generated, each sample marked with its concept identity:

  • "sudden": the concept is replaced at once at the drift position d; this is the limit of the sigmoid s(p) = 1 / (1 + exp(-spacing * (p - d))) of section 3.2.1 for a large spacing, so spacing is not used.
  • "gradual": at each sample the new concept is used with probability s(p) and the old one with 1 - s(p) (section 3.2.2). Samples are drawn from one of the two, never mixed.
  • "incremental": the concept drifts continuously; the mean moves linearly between the two concept means with the same sigmoid weight (section 3.2.3). The paper describes this in words; the linear-in-s interpolation of the means is the concrete formula used here, and the label follows the concept with the larger weight.

Each sample uses the drift nearest to its position p in [0, 1], so a transition is continuous on both sides of its drift.

Each concept is two Gaussian clusters in n_features dimensions, one per class. The clusters are placed along a random unit direction with a fixed separation, and the class labels alternate between concepts: on even-indexed concepts cluster 0 is class 0, on odd-indexed ones it is class 1. Each concept draws its own random direction, so a classifier trained on the earlier concept is wrong after a drift only when the new direction lies on the same side as the old one. On 20 seeds, with one drift and 2000 samples, a linear rule fitted before the change had an accuracy below 0.5 after it on 9 seeds with 2 features and on 7 seeds with 4 features, and above 0.9 on 10 and on 11. The benchmarks of the forests choose their seeds with benchmarks/_drift_seeds.py.

Examples:

>>> from dense_armor.core.signals.datasets import DriftStream
>>> ds = DriftStream(n_samples=100, n_features=2, n_drifts=1,
...                  kind="sudden", spacing=100.0, seed=0)
>>> X, y = ds.data()
>>> X.shape, y.shape
((100, 2), (100,))
>>> len(ds.drift_positions)
1

DriftStream

DriftStream(
    n_samples: int,
    n_features: int,
    n_drifts: int,
    kind: str,
    spacing: float = 10.0,
    seed: int | None = 0,
)

Synthetic binary stream with concept drift.

Parameters:

Name Type Description Default
n_samples int

number of samples in the stream.

required
n_features int

number of input dimensions.

required
n_drifts int

number of concept changes. Zero means stationary.

required
kind str

one of "sudden", "gradual", "incremental".

required
spacing float

sharpness of the sigmoid, in inverse position units. Higher values give more abrupt transitions.

10.0
seed int | None

seed of the random generator.

0

Raises:

Type Description
ValueError

on a bad kind or a non-positive count.

Examples:

>>> from dense_armor.core.signals.datasets import DriftStream
>>> ds = DriftStream(n_samples=50, n_features=3, n_drifts=2,
...                  kind="gradual", spacing=20.0, seed=1)
>>> X, y = ds.data()
>>> X.shape
(50, 3)
>>> ds.drift_positions
array([0.33333333, 0.66666667])
Source code in dense_armor/core/signals/datasets/drift_stream.py
def __init__(
    self,
    n_samples: int,
    n_features: int,
    n_drifts: int,
    kind: str,
    spacing: float = 10.0,
    seed: int | None = 0,
) -> None:
    if n_samples < 1:
        raise ValueError(f"n_samples must be >= 1, got {n_samples}")
    if n_features < 1:
        raise ValueError(f"n_features must be >= 1, got {n_features}")
    if n_drifts < 0:
        raise ValueError(f"n_drifts must be >= 0, got {n_drifts}")
    if kind not in self._KINDS:
        raise ValueError(f"kind must be one of {self._KINDS}, got {kind!r}")
    self.n_samples = n_samples
    self.n_features = n_features
    self.n_drifts = n_drifts
    self.kind = kind
    self.spacing = float(spacing)
    self.seed = seed
    rng = np.random.default_rng(seed)
    self._mu = [_make_concept(rng, n_features, j) for j in range(n_drifts + 1)]
    self._scale = self._mu[0][1]
    if n_drifts == 0:
        self.drift_positions = np.zeros(0, dtype=get_default_dtype())
    else:
        self.drift_positions = np.array(
            [(j + 1) / (n_drifts + 1) for j in range(n_drifts)]
        )

data

data() -> tuple[np.ndarray, np.ndarray]

Generate the whole stream.

Returns:

Type Description
ndarray

(X, y) with shapes (n_samples, n_features) and

ndarray

(n_samples,).

Source code in dense_armor/core/signals/datasets/drift_stream.py
def data(self) -> tuple[np.ndarray, np.ndarray]:
    """Generate the whole stream.

    Returns:
        ``(X, y)`` with shapes ``(n_samples, n_features)`` and
        ``(n_samples,)``.
    """
    rng = np.random.default_rng(None if self.seed is None else self.seed + 1)
    X = np.zeros((self.n_samples, self.n_features), dtype=get_default_dtype())
    y = np.zeros(self.n_samples, dtype=int)
    concepts = np.zeros(self.n_samples, dtype=int)
    for i in range(self.n_samples):
        p = i / max(1, self.n_samples - 1)
        x, label, which = self._sample_one(rng, p)
        X[i] = x
        y[i] = label
        concepts[i] = which
    self.concepts_ = concepts
    return X, y

stream

stream() -> Iterator[tuple[Signal, int]]

Yield (Signal, y) pairs in time order.

Source code in dense_armor/core/signals/datasets/drift_stream.py
def stream(self) -> Iterator[tuple[Signal, int]]:
    """Yield ``(Signal, y)`` pairs in time order."""
    X, y = self.data()
    names = [f"x{i}" for i in range(self.n_features)]
    units = ["" for _ in range(self.n_features)]
    for i in range(self.n_samples):
        sig = Signal(
            values=X[i],
            names=names,
            units=units,
            t=float(i),
        )
        yield sig, int(y[i])

Details

  • DriftStream: each concept is two Gaussian clusters, one per class, placed along a random direction; the class of each cluster alternates between concepts, and each concept draws its own random direction, so a model trained on one concept is wrong on the next only when the new direction lies on the same side as the old one: on 20 seeds, with one drift and 2000 samples, a linear rule fitted before the change had an accuracy below 0.5 after it on 9 seeds with 2 features and on 7 with 4 features, and above 0.9 on 10 and on 11. Each sample uses the drift nearest to its position, so every transition is continuous on both sides. "sudden" is the limit of the sigmoid for a large spacing and does not use it; in "incremental" the label follows the concept with the larger weight. Implemented from the description in Ksieniewicz and Zyblewski (2020), sections 3.2.1 to 3.2.3 (pages 8–9).
  • Source: Ksieniewicz, P., Zyblewski, P. (2020), "stream-learn — open-source Python library for difficult data stream batch analysis", arXiv:2001.11077.