Skip to content

K-means

Algorithm

K-means partitions observations into \(k\) clusters, minimizing the sum of squared distances from each observation \(x\) to its cluster centroid \(\mu_j\):

\[ \underset{C_1,\ldots,C_k}{\operatorname{minimize}} \sum_{j=1}^{k}\sum_{x\in C_j}\lVert x-\mu_j\rVert_2^2 \]

Each iteration assigns observations to the nearest centroid and recomputes the centroids from those assignments. Initialization affects which local solution is found.

Inputs and limitations

  • Pass a non-empty rectangular list of finite numeric observations and an integer 1 <= k <= len(samples).
  • Distances are Euclidean; scale features first when their units differ.
  • Choose centroids_init_method="random" or "kmeans++".
  • Duplicate locations can produce fewer non-empty clusters than k, with a warning log. All k centers retain valid coordinates.
  • Set random_seed to an integer for reproducible fits.
  • predict accepts one finite sample with the training feature dimension. Assignment uses floating-point Euclidean distances. When two computed distances round to the same value, the lowest label wins. Fitted centroids use floats, so large integer queries can also lose precision during coordinate subtraction.
  • Training labels correspond to the nearest final centers, including when training stops at max_iter. fit_predict returns a copy of these labels.
  • A failed refit preserves the previous fitted result.

Minimal example

from toyml.clustering import KMeans

samples = [[0.0], [0.1], [4.0], [4.1]]
model = KMeans(k=2, random_seed=42)
print(model.fit_predict(samples))
print(model.predict([0.2]))

API

toyml.clustering.kmeans.KMeans dataclass

KMeans(k: int, max_iter: int = 500, tol: float = 1e-05, centroids_init_method: Literal['random', 'kmeans++'] = 'random', random_seed: int | None = None, distance_metric: Literal['euclidean'] = 'euclidean')

K-means algorithm (with KMeans++ initialization as option).

Examples:

>>> from toyml.clustering import KMeans
>>> dataset = [[1.0, 2.0], [1.0, 4.0], [1.0, 0.0], [10.0, 2.0], [10.0, 4.0], [11.0, 0.0]]
>>> kmeans = KMeans(k=2, random_seed=42).fit(dataset)
>>> kmeans.clusters_
{0: [3, 4, 5], 1: [0, 1, 2]}
>>> kmeans.centroids_
{0: [10.333333333333334, 2.0], 1: [1.0, 2.0]}
>>> kmeans.labels_
[1, 1, 1, 0, 0, 0]
>>> kmeans.predict([0, 1])
1
>>> kmeans.iter_
2

There is a fit_predict method that can be used to fit and predict.

Examples:

>>> from toyml.clustering import KMeans
>>> dataset = [[1, 0], [1, 1], [1, 2], [10, 0], [10, 1], [10, 2]]
>>> KMeans(k=2, random_seed=42).fit_predict(dataset)
[1, 1, 1, 0, 0, 0]
References
  1. Zhou Zhihua
  2. Murphy
Note

Here we just implement the naive K-means algorithm.

See Also

k instance-attribute

k: int

The number of clusters, specified by user.

max_iter class-attribute instance-attribute

max_iter: int = 500

The number of iterations the algorithm will run for if it does not converge before that.

tol class-attribute instance-attribute

tol: float = 1e-05

Stop when every centroid coordinate moves by at most this amount.

centroids_init_method class-attribute instance-attribute

centroids_init_method: Literal['random', 'kmeans++'] = 'random'

The method to initialize the centroids.

random_seed class-attribute instance-attribute

random_seed: int | None = None

Each fit uses a fresh generator. An integer seed reproduces the initialization.

distance_metric class-attribute instance-attribute

distance_metric: Literal['euclidean'] = 'euclidean'

The distance metric to use.(For now we only support euclidean).

clusters_ class-attribute instance-attribute

clusters_: dict[int, list[int]] = field(default_factory=dict, init=False)

The clusters of the dataset.

centroids_ class-attribute instance-attribute

centroids_: dict[int, list[float]] = field(default_factory=dict, init=False)

The centroids of the clusters.

labels_ class-attribute instance-attribute

labels_: list[int] = field(default_factory=list, init=False)

The cluster labels of the dataset.

fit

fit(dataset: list[list[float]]) -> KMeans

Fit the centroids and assign each sample to its nearest final centroid.

A failed fit preserves the previous fitted result.

PARAMETER DESCRIPTION
dataset

One sample per row, with at least k rows. Each row must have the same positive number of features, all with finite numeric values.

TYPE: list[list[float]]

RETURNS DESCRIPTION
KMeans

The fitted instance (self).

RAISES DESCRIPTION
ValueError

If the dataset or model parameters are invalid, or a distance exceeds the floating-point range.

Source code in src/toyml/clustering/kmeans.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def fit(self, dataset: list[list[float]]) -> KMeans:
    """Fit the centroids and assign each sample to its nearest final centroid.

    A failed fit preserves the previous fitted result.

    Args:
        dataset: One sample per row, with at least `k` rows. Each row must have
            the same positive number of features, all with finite numeric values.

    Returns:
        The fitted instance (`self`).

    Raises:
        ValueError: If the dataset or model parameters are invalid, or a
            distance exceeds the floating-point range.
    """
    self._validate_fit(dataset)
    initial = self._initial_centroids(dataset, random.Random(self.random_seed))
    centroids, iterations = self._lloyd(dataset, initial)

    # Even at the iteration limit, report assignments to the final centroids.
    labels = self._assign(dataset, centroids)
    clusters = self._group_by_label(labels)
    self.centroids_, self.iter_ = centroids, iterations
    self.labels_, self.clusters_ = labels, clusters
    nonempty = sum(bool(members) for members in clusters.values())
    if nonempty < self.k:
        logger.warning("Found %d non-empty clusters, fewer than requested k=%d", nonempty, self.k)
    return self

fit_predict

fit_predict(dataset: list[list[float]]) -> list[int]

Fit the model and return the cluster label for each training sample.

PARAMETER DESCRIPTION
dataset

Training samples satisfying the same requirements as fit.

TYPE: list[list[float]]

RETURNS DESCRIPTION
list[int]

A copy of labels_ in input row order. Each label identifies the

list[int]

nearest final centroid, even when fitting stops at max_iter.

RAISES DESCRIPTION
ValueError

If the dataset or model parameters are invalid, or a distance exceeds the floating-point range.

Source code in src/toyml/clustering/kmeans.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def fit_predict(self, dataset: list[list[float]]) -> list[int]:
    """Fit the model and return the cluster label for each training sample.

    Args:
        dataset: Training samples satisfying the same requirements as
            [`fit`][toyml.clustering.kmeans.KMeans.fit].

    Returns:
        A copy of `labels_` in input row order. Each label identifies the
        nearest final centroid, even when fitting stops at `max_iter`.

    Raises:
        ValueError: If the dataset or model parameters are invalid, or a
            distance exceeds the floating-point range.
    """
    return self.fit(dataset).labels_.copy()

predict

predict(point: list[float]) -> int

Assign one sample to its nearest fitted centroid.

PARAMETER DESCRIPTION
point

A sample with finite numeric values and the same number of features as the training samples.

TYPE: list[float]

RETURNS DESCRIPTION
int

The nearest centroid's label. If computed floating-point distances

int

tie for the minimum, the lowest label wins.

RAISES DESCRIPTION
ValueError

If the model is unfitted, the point is invalid, the distance metric is unsupported, or a distance exceeds the floating-point range.

Source code in src/toyml/clustering/kmeans.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def predict(self, point: list[float]) -> int:
    """Assign one sample to its nearest fitted centroid.

    Args:
        point: A sample with finite numeric values and the same number of
            features as the training samples.

    Returns:
        The nearest centroid's label. If computed floating-point distances
        tie for the minimum, the lowest label wins.

    Raises:
        ValueError: If the model is unfitted, the point is invalid, the
            distance metric is unsupported, or a distance exceeds the
            floating-point range.
    """
    if not self.centroids_:
        msg = "The model is not fitted yet"
        raise ValueError(msg)
    self._validate_point(point, len(self.centroids_[0]))
    return self._nearest(point, self.centroids_)