milia.cluster.base#

Base class for clusterers, following scikit-learn’s clustering API.

fit(X) sets labels_ and n_clusters_; fit_predict(X) comes from ClusterMixin. predict(X) exists only for clusterers that can assign new points (centroid and mixture models); density and hierarchical methods do not define it, exactly as in scikit-learn. Noise points are labelled -1 and are not counted in n_clusters_.

Every clusterer that partitions into a fixed number of groups takes the hyperparameter n_clusters, so model-selection code can sweep k with clone(clusterer).set_params(n_clusters=k) whatever the algorithm.

Functions

predictive(estimator)

Whether the clusterer can assign labels to new points.

Classes

BaseClusterer()

Shared fit and predict for every clusterer.

milia.cluster.base.predictive(estimator)#

Whether the clusterer can assign labels to new points.

Parameters:

estimator (BaseClusterer) – A clusterer.

Return type:

bool

Returns:

True when it defines _predict.

Examples

>>> from milia import make
>>> predictive(make("clusterer", "kmeans")), predictive(make("clusterer", "dbscan"))
(True, False)
class milia.cluster.base.BaseClusterer#

Bases: ClusterMixin, BaseEstimator, ABC

Shared fit and predict for every clusterer.

Subclasses implement _fit(X) -> labels and, when they can label new points, _predict(X) -> labels. Hyperparameters are keyword arguments of __init__, stored unchanged.

Variables:
  • labels – Cluster label of each training row; -1 marks noise.

  • n_clusters – Number of clusters found, noise excluded.

  • n_features_in – Number of features seen during fit.

Examples

A clusterer is written by implementing _fit (and _predict when it can label new points):

>>> import numpy as np
>>> class Sign(BaseClusterer):
...     def _fit(self, X):
...         return (X[:, 0] > 0).astype(int)
>>> model = Sign().fit(np.array([[-1.0], [2.0], [3.0]]))
>>> model.labels_.tolist(), model.n_clusters_, hasattr(model, "predict")
([0, 1, 1], 2, False)
fit(X, y=None)#

Cluster the training data.

Parameters:
  • X (ArrayLike) – Data of shape (n_samples, n_features), or a square distance matrix when the clusterer is built with metric="precomputed".

  • y (None) – Ignored; present for API consistency.

Return type:

BaseClusterer

Returns:

The fitted clusterer.

predict(X)#

Assign new rows to the fitted clusters.

Only available on clusterers that can label new points (centroid and mixture models); density and hierarchical clusterers do not define it.

Parameters:

X (ArrayLike) – Rows with the number of features seen in fit.

Return type:

ndarray

Returns:

One cluster label per row.

Examples

>>> import numpy as np
>>> from milia import make
>>> model = make("clusterer", "kmeans", n_clusters=2).fit(np.array([[0.0], [0.2], [5.0], [5.2]]))
>>> bool(model.predict([[0.1]])[0] == model.labels_[0])
True