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
|
Whether the clusterer can assign labels to new points. |
Classes
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:
- Returns:
Truewhen 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,ABCShared fit and predict for every clusterer.
Subclasses implement
_fit(X) -> labelsand, 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;
-1marks 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_predictwhen 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:
- Return type:
- 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 infit.- Return type:
- 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