Skip to content

DenStream: groups of any shape, with outliers

DenStream keeps small micro-clusters, a centre and a weight, lets their weight fade with time, and gives the final groups on demand with macro_clusters(). The overview of the section is on Clustering.

Groups of any shape, with outliers

DenStream keeps small "micro-clusters" (a centre and a weight), lets their weight fade with time, and only groups that keep receiving points become real clusters; an isolated point stays an outlier.

import numpy as np
from dense_armor.core.online.cluster.denstream import DenStream

rng = np.random.default_rng(0)
ds = DenStream(eps=1.0, beta=0.4, mu=3.0, decay=0.01)
centres = np.array([[0.0, 0.0], [8.0, 0.0], [0.0, 8.0]])
t = 0.0
for i in range(600):
    x = centres[i % 3] + rng.normal(0, 0.3, 2) if i % 20 else rng.uniform(-4, 12, 2)
    ds.learn_one({"x": x.tolist()}, t=t)
    t += 1.0
clusters, _ = ds.macro_clusters()
print(len(clusters), [[round(v, 1) for v in c["center"]] for c in clusters])
3 [[8.0, -0.0], [-0.0, 8.0], [-0.1, 0.0]]

Six hundred points around three centres, one in twenty uniform noise; DenStream finds the three groups. The clusters come back in the order they were discovered, not in the order of the input centres, so the first one in the list is the group around (8, 0). The weight of a micro-cluster fades with the damped window of the review of Zubaroğlu and Atalay (2020, section 2.3.1):

\[f(t) = 2^{-\lambda t}\]

\(\lambda\) is the decay rate; a micro-cluster heavier than \(\beta\mu\) is a real (potential) one, lighter ones are candidates (outliers) until more points arrive. An isolated point that lands far from every micro-cluster only creates a candidate, which will be pruned later if no other point comes near it. The offline step macro_clusters() merges reachable real micro-clusters on demand, and the centre of each resulting cluster is the weight-weighted mean of its micro- clusters.

Points of three groups, with the 30 noise points of the stream drawn as crosses, and the three cluster centres that DenStream returns, at (8.0, 0.0), (0.0, 8.0) and (0.0, 0.0).

The picture shows the 600 points of the example. The 30 noise points (one in twenty, crosses) are scattered over the square; macro_clusters() returns three clusters, with centres at (8.0, 0.0), (0.0, 8.0) and (0.0, 0.0), and the isolated points are not in any of them.

The parameters

Parameter Meaning Default
eps neighbourhood radius 0.5
beta multiplier that separates potential micro-clusters from outlier ones, in (0, 1] 0.2
mu minimum weight of a potential micro-cluster 1.0
decay decay rate λ of the damped window 0.1

API reference

denstream

Density-based stream clustering with micro-clusters and a damped window.

A micro-cluster is a small set of close points, kept as a compact summary (centre, weight, timestamp of the last update). Two micro-clusters are directly density reachable when the distance between their centres is at most the sum of their radii; a chain of direct reachability is density reachable (Zubaroglu and Atalay 2020, page 9). Recent points weigh more than old ones through a damped window with the decay function f(t) = 2 ** (-lam * t) (Section 2.3.1, page 5). A micro-cluster whose cardinality is far below the average is an outlier (Section 2.4, page 6).

The stream is summarised with two kinds of micro-clusters:

  • potential micro-clusters (pMCs), with weight at least beta * mu, which are the real clusters;
  • outlier micro-clusters (oMCs), with weight below beta * mu, which are the candidates.

A new point is added to the nearest pMC within eps if any, else to the nearest oMC within eps, else it opens a new oMC. An oMC whose weight reaches beta * mu is promoted to pMC; a pMC whose weight drops below beta * mu is removed, and an oMC whose weight drops below beta * mu / 4 is removed. The last threshold is a choice of this implementation: the review (Section 2.4, page 6) defines an outlier as a cluster whose cardinality is much smaller than the average and does not give a numeric threshold, so a quarter of beta * mu was chosen as a small fraction. In the same section the review is also silent on how to reduce the weight over time for an oMC versus a pMC, so the same decay rate is used for both.

The offline step :meth:macro_clusters merges reachable pMCs on demand into macro-clusters, which is the final answer of the algorithm. Reachability uses eps as the distance between two centres; the review (page 9) states the sum-of-radii rule, but each pMC has radius at most eps (points are only added within eps), so the sum is at most 2 eps and eps is the conservative choice. The macro-cluster centre is the weight-weighted mean of its pMCs.

The weights and centres use the real timestamps passed to learn_one.

Examples:

>>> from dense_armor.core.online.cluster.denstream import DenStream
>>> ds = DenStream(eps=0.5, beta=0.4, mu=1.0, decay=0.1)
>>> for i in range(30):
...     _ = ds.learn_one({"x": [0.0, 0.0]}, t=float(i))
>>> clusters, _ = ds.macro_clusters()
>>> len(clusters)
1
References

Zubaroglu, A., Atalay, V. (2020). Data stream clustering: a review. arXiv:2007.10781. Sections 2.3.1 (page 5), 2.4 (page 6); density reachability on page 9.

DenStream

DenStream(
    eps: float = 0.5,
    beta: float = 0.2,
    mu: float = 1.0,
    decay: float = 0.1,
)

Bases: Transformer

Density-based stream clustering with a damped window.

Potential and outlier micro-clusters fade with time; new points join the nearest reachable micro-cluster, and isolated points stay in the outlier list. The final answer comes from :meth:macro_clusters.

Memory grows with the number of micro-clusters kept: bounded by the effective window set by decay and mu, so the footprint is the size of the current micro-cluster lists.

Parameters:

Name Type Description Default
eps float

neighbourhood radius.

0.5
beta float

multiplier that separates pMCs from oMCs.

0.2
mu float

minimum weight of a pMC.

1.0
decay float

decay rate lam of the damped window.

0.1

Raises:

Type Description
ValueError

if any parameter is not positive, or beta is not in (0, 1].

Source code in dense_armor/core/online/cluster/denstream.py
def __init__(
    self,
    eps: float = 0.5,
    beta: float = 0.2,
    mu: float = 1.0,
    decay: float = 0.1,
) -> None:
    if eps <= 0:
        raise ValueError(f"eps must be > 0, got {eps}")
    if not 0.0 < beta <= 1.0:
        raise ValueError(f"beta must be in (0, 1], got {beta}")
    if mu <= 0:
        raise ValueError(f"mu must be > 0, got {mu}")
    if decay <= 0:
        raise ValueError(f"decay must be > 0, got {decay}")
    self.eps = eps
    self.beta = beta
    self.mu = mu
    self.decay = decay
    self.pmc_: list[_MC] = []
    self.omc_: list[_MC] = []
    self.n_seen_ = 0
    self.n_missing_ = 0

learn_one

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

Process one sample: fade, join, promote, prune.

Source code in dense_armor/core/online/cluster/denstream.py
def learn_one(
    self, x: Any, y: Any = None, t: float | None = None
) -> "DenStream":
    """Process one sample: fade, join, promote, prune."""
    self._time_step(t)
    v = _vec(x)
    if v is None:
        self.n_missing_ += 1
        return self
    tt = float(t) if t is not None else float(self.n_seen_)
    self.n_seen_ += 1
    p, dp = self._nearest(self.pmc_, v)
    if p is not None and dp <= self.eps:
        self._merge(p, v, tt)
    else:
        o, do = self._nearest(self.omc_, v)
        if o is not None and do <= self.eps:
            self._merge(o, v, tt)
            if o.w >= self.beta * self.mu:
                self.omc_.remove(o)
                self.pmc_.append(o)
        else:
            self.omc_.append(_MC(v.copy(), 1.0, tt))
    self._prune(tt)
    return self

transform_one

transform_one(x: Any, t: float | None = None) -> dict

Return the nearest pMC index within eps, or -1.

Source code in dense_armor/core/online/cluster/denstream.py
def transform_one(self, x: Any, t: float | None = None) -> dict:
    """Return the nearest pMC index within ``eps``, or ``-1``."""
    v = _vec(x)
    if v is None or not self.pmc_:
        return {"cluster": -1, "distance": float("inf")}
    best_i = -1
    best_d = float("inf")
    for i, mc in enumerate(self.pmc_):
        d = float(np.linalg.norm(mc.c - v))
        if d < best_d:
            best_d = d
            best_i = i
    if best_d > self.eps:
        return {"cluster": -1, "distance": best_d}
    return {"cluster": best_i, "distance": best_d}

macro_clusters

macro_clusters() -> tuple[list[dict], list[int]]

Merge reachable pMCs into macro-clusters on demand.

Two pMCs are directly density reachable when the distance between their centres is at most eps (see the module docstring for the choice). The macro-cluster centre is the weight-weighted mean of its pMCs.

Returns:

Type Description
list[dict]

A tuple (clusters, labels): clusters is a list of

list[int]

dicts with keys "center", "weight" and

tuple[list[dict], list[int]]

"n_pmc", and labels assigns each pMC in

tuple[list[dict], list[int]]

attr:pmc_ to a macro-cluster index.

Source code in dense_armor/core/online/cluster/denstream.py
def macro_clusters(self) -> tuple[list[dict], list[int]]:
    """Merge reachable pMCs into macro-clusters on demand.

    Two pMCs are directly density reachable when the distance
    between their centres is at most ``eps`` (see the module
    docstring for the choice). The macro-cluster centre is the
    weight-weighted mean of its pMCs.

    Returns:
        A tuple ``(clusters, labels)``: ``clusters`` is a list of
        dicts with keys ``"center"``, ``"weight"`` and
        ``"n_pmc"``, and ``labels`` assigns each pMC in
        :attr:`pmc_` to a macro-cluster index.
    """
    n = len(self.pmc_)
    labels = [-1] * n
    clusters: list[dict] = []
    for i in range(n):
        if labels[i] != -1:
            continue
        cid = len(clusters)
        stack = [i]
        labels[i] = cid
        members: list[int] = []
        while stack:
            j = stack.pop()
            members.append(j)
            cj = self.pmc_[j].c
            for k in range(n):
                if labels[k] != -1:
                    continue
                if float(np.linalg.norm(cj - self.pmc_[k].c)) <= self.eps:
                    labels[k] = cid
                    stack.append(k)
        ws = np.array([self.pmc_[m].w for m in members])
        cs = np.stack([self.pmc_[m].c for m in members])
        center = (ws[:, None] * cs).sum(axis=0) / ws.sum()
        clusters.append(
            {
                "center": center.tolist(),
                "weight": float(ws.sum()),
                "n_pmc": len(members),
            }
        )
    return clusters, labels

Details

  • DenStream: an outlier micro-cluster is removed when its weight falls below \(\beta\mu/4\) (the review gives no number); two micro-clusters are reachable when their centres are within eps (the review, p. 9, uses the sum of the radii; each radius is at most eps).
  • Sources: Zubaroğlu, A., Atalay, V. (2020), "Data stream clustering: a review", Artificial Intelligence Review, arXiv:2007.10781.