KMeans#

class sklearn.cluster.KMeans(n_clusters=8, *, init='k-means++', n_init='auto', max_iter=300, tol=0.0001, verbose=0, random_state=None, copy_x=True, algorithm='lloyd')[source]#

K-Means 聚类。

请阅读 用户指南 以了解更多信息。

参数:
n_clustersint, default=8

The number of clusters to form as well as the number of centroids to generate.

关于如何为 n_clusters 选择最优值的示例,请参考 通过轮廓分析选择 KMeans 聚类的簇数

init{‘k-means++’, ‘random’}, callable or array-like of shape (n_clusters, n_features), default=’k-means++’

Method for initialization

  • ‘k-means++’:根据点对整体惯性(inertia)的贡献的经验概率分布进行采样,从而选择初始聚类中心。该技术加快了收敛速度。所实现的算法是“贪心 k-means++”。它与原生 k-means++ 的区别在于,它在每个采样步骤进行多次试验,并在其中选择最佳中心点。

  • ‘random’: choose n_clusters observations (rows) at random from data for the initial centroids.

  • 如果传入数组,其形状应为 (n_clusters, n_features),并提供初始中心点。

  • If a callable is passed, it should take arguments X, n_clusters and a random state and return an initialization.

关于如何使用不同 init 策略的示例,请参阅 手写数字数据上的 K-Means 聚类演示

关于初始化影响的评估,请参阅示例 k-means 初始化影响的经验评估

n_init‘auto’ 或 int,默认=’auto’

使用不同中心点种子运行 k-means 算法的次数。最终结果是 n_init 次连续运行中惯性(inertia)表现最好的一次。对于稀疏高维问题,建议进行多次运行(参见 使用 k-means 对稀疏数据进行聚类)。

n_init='auto' 时,运行次数取决于 init 的值:如果使用 init='random'init 为可调用对象,则为 10;如果使用 init='k-means++'init 为类数组对象,则为 1。

Added in version 1.2: Added ‘auto’ option for n_init.

版本 1.4 中更改:n_init 的默认值更改为 'auto'

max_iterint, default=300

单次运行中 k-means 算法的最大迭代次数。

tolfloat, default=1e-4

关于两次连续迭代中簇中心差值的 Frobenius 范数的相对容差,用于判断是否收敛。

verboseint, default=0

Verbosity mode.

random_stateint, RandomState instance or None, default=None

确定中心点初始化的随机数生成。使用 int 以使随机性确定化。请参阅 术语表

copy_xbool, default=True

在预计算距离时,先对数据进行中心化在数值上更准确。如果 copy_x 为 True(默认值),则不会修改原始数据。如果为 False,则会修改原始数据,并在函数返回前将其恢复,但减去并加上数据均值可能会引入微小的数值差异。注意,如果原始数据不是 C-contiguous(C 连续)的,即使 copy_x 为 False,也会进行复制。如果原始数据是稀疏的但不是 CSR 格式,即使 copy_x 为 False,也会进行复制。

algorithm{“lloyd”, “elkan”}, default=”lloyd”

要使用的 k-means 算法。经典的 EM 风格算法为 "lloyd""elkan" 变体通过利用三角不等式,在某些具有明确簇的数据集上可能更高效。但是,由于需要分配一个形状为 (n_samples, n_clusters) 的额外数组,它更占用内存。

版本 0.18 中更改:添加了 Elkan 算法

版本 1.1 中更改:将“full”重命名为“lloyd”,并弃用了“auto”和“full”。将“auto”更改为使用“lloyd”而不是“elkan”。

属性:
cluster_centers_ndarray of shape (n_clusters, n_features)

簇中心的坐标。如果算法在完全收敛前停止(参见 tolmax_iter),则这些值将与 labels_ 不一致。

labels_ndarray of shape (n_samples,)

每个点的标签

inertia_float

样本与其最近簇中心之间的平方距离之和,如果提供了样本权重,则按样本权重加权。

n_iter_int

运行的迭代次数。

n_features_in_int

拟合 期间看到的特征数。

0.24 版本新增。

feature_names_in_shape 为 (n_features_in_,) 的 ndarray

fit 期间看到的特征名称。仅当 X 具有全部为字符串的特征名称时才定义。

1.0 版本新增。

另请参阅

MiniBatchKMeans

一种替代的在线实现,它使用小批量(mini-batches)对中心位置进行增量更新。对于大规模学习(例如 n_samples > 10k),MiniBatchKMeans 可能比默认的批处理实现快得多。

注意事项

k-means 问题使用 Lloyd 或 Elkan 算法解决。

平均复杂度为 O(k n T),其中 n 是样本数,T 是迭代次数。

最坏情况下的复杂度为 O(n^(k+2/p)),其中 n = n_samples,p = n_features。详情请参考 “How slow is the k-means method?” D. Arthur and S. Vassilvitskii - SoCG2006.

在实践中,k-means 算法非常快(是现有的最快聚类算法之一),但它容易陷入局部最小值。这就是为什么多次重启它很有用。

如果算法在完全收敛前停止(由于 tolmax_iter),labels_cluster_centers_ 将不一致,即 cluster_centers_ 将不会是每个簇中点的平均值。此外,估计器将在最后一次迭代后重新分配 labels_,以使 labels_ 与训练集上的 predict 一致。

示例

>>> from sklearn.cluster import KMeans
>>> import numpy as np
>>> X = np.array([[1, 2], [1, 4], [1, 0],
...               [10, 2], [10, 4], [10, 0]])
>>> kmeans = KMeans(n_clusters=2, random_state=0, n_init="auto").fit(X)
>>> kmeans.labels_
array([1, 1, 1, 0, 0, 0], dtype=int32)
>>> kmeans.predict([[0, 0], [12, 3]])
array([1, 0], dtype=int32)
>>> kmeans.cluster_centers_
array([[10.,  2.],
       [ 1.,  2.]])

有关 K-Means 常见问题及解决方法,请参见 k-means 假设的演示

关于如何使用 K-Means 对文本文档进行聚类的演示,请参见 使用 k-means 对文本文档进行聚类

关于 K-Means 和 MiniBatchKMeans 的比较,请参考示例 K-Means 和 MiniBatchKMeans 聚类算法的比较

关于 K-Means 和 BisectingKMeans 的比较,请参考示例 二分 K-Means 与常规 K-Means 性能比较

fit(X, y=None, sample_weight=None)[source]#

计算 k-means 聚类。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

要聚类的训练实例。必须注意,数据将被转换为 C 顺序,如果给定数据不是 C-contiguous(C 连续),将导致内存复制。如果传入稀疏矩阵,且它不是 CSR 格式,也会进行复制。

y被忽略

Not used, present here for API consistency by convention.

sample_weightshape 为 (n_samples,) 的 array-like, default=None

X 中每个观测值的权重。如果为 None,则所有观测值被赋予相等的权重。如果 init 是可调用对象或用户提供的数组,则在初始化期间不会使用 sample_weight

0.20 版本新增。

返回:
selfobject

拟合的估计器。

fit_predict(X, y=None, sample_weight=None)[source]#

Compute cluster centers and predict cluster index for each sample.

Convenience method; equivalent to calling fit(X) followed by predict(X).

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

New data to transform.

y被忽略

Not used, present here for API consistency by convention.

sample_weightshape 为 (n_samples,) 的 array-like, default=None

The weights for each observation in X. If None, all observations are assigned equal weight.

返回:
labelsndarray of shape (n_samples,)

Index of the cluster each sample belongs to.

fit_transform(X, y=None, sample_weight=None)[source]#

Compute clustering and transform X to cluster-distance space.

Equivalent to fit(X).transform(X), but more efficiently implemented.

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

New data to transform.

y被忽略

Not used, present here for API consistency by convention.

sample_weightshape 为 (n_samples,) 的 array-like, default=None

The weights for each observation in X. If None, all observations are assigned equal weight.

返回:
X_newndarray of shape (n_samples, n_clusters)

X transformed in the new space.

get_feature_names_out(input_features=None)[source]#

获取转换的输出特征名称。

The feature names out will prefixed by the lowercased class name. For example, if the transformer outputs 3 features, then the feature names out are: ["class_name0", "class_name1", "class_name2"].

参数:
input_featuresarray-like of str or None, default=None

Only used to validate feature names with the names seen in fit.

返回:
feature_names_outstr 对象的 ndarray

转换后的特征名称。

get_metadata_routing()[source]#

获取此对象的元数据路由。

请查阅 用户指南,了解路由机制如何工作。

返回:
routingMetadataRequest

封装路由信息的 MetadataRequest

get_params(deep=True)[source]#

获取此估计器的参数。

参数:
deepbool, default=True

如果为 True,将返回此估计器以及包含的子对象(如果它们是估计器)的参数。

返回:
paramsdict

参数名称映射到其值。

predict(X)[source]#

Predict the closest cluster each sample in X belongs to.

In the vector quantization literature, cluster_centers_ is called the code book and each value returned by predict is the index of the closest code in the code book.

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

New data to predict.

返回:
labelsndarray of shape (n_samples,)

Index of the cluster each sample belongs to.

score(X, y=None, sample_weight=None)[source]#

Opposite of the value of X on the K-means objective.

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

New data.

y被忽略

Not used, present here for API consistency by convention.

sample_weightshape 为 (n_samples,) 的 array-like, default=None

The weights for each observation in X. If None, all observations are assigned equal weight.

返回:
scorefloat

Opposite of the value of X on the K-means objective.

set_fit_request(*, sample_weight: bool | None | str = '$UNCHANGED$') KMeans[source]#

配置是否应请求元数据以传递给 fit 方法。

请注意,此方法仅在以下情况下相关:此估计器用作 元估计器 中的子估计器,并且通过 enable_metadata_routing=True 启用了元数据路由(请参阅 sklearn.set_config)。请查看 用户指南 以了解路由机制的工作原理。

每个参数的选项如下:

  • True:请求元数据,如果提供则传递给 fit。如果未提供元数据,则忽略该请求。

  • False:不请求元数据,元估计器不会将其传递给 fit

  • None:不请求元数据,如果用户提供元数据,元估计器将引发错误。

  • str:应将元数据以给定别名而不是原始名称传递给元估计器。

默认值 (sklearn.utils.metadata_routing.UNCHANGED) 保留现有请求。这允许您更改某些参数的请求而不更改其他参数。

在版本 1.3 中新增。

参数:
sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

fit 方法中 sample_weight 参数的元数据路由。

返回:
selfobject

更新后的对象。

set_output(*, transform=None)[source]#

设置输出容器。

请参阅 用户指南 以了解更多详细信息,并参考 引入 set_output API 获取关于如何使用该 API 的示例。

参数:
transform{“default”, “pandas”, “polars”}, default=None

配置 transformfit_transform 的输出。

  • "default": 转换器的默认输出格式

  • "pandas": DataFrame 输出

  • "polars": Polars 输出

  • None: 转换配置保持不变

1.4 版本新增: 添加了 "polars" 选项。

返回:
selfestimator instance

估计器实例。

set_params(**params)[source]#

设置此估计器的参数。

此方法适用于简单的估计器以及嵌套对象(如 Pipeline)。后者具有 <component>__<parameter> 形式的参数,以便可以更新嵌套对象的每个组件。

参数:
**paramsdict

估计器参数。

返回:
selfestimator instance

估计器实例。

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') KMeans[source]#

配置是否应请求元数据以传递给 score 方法。

请注意,此方法仅在以下情况下相关:此估计器用作 元估计器 中的子估计器,并且通过 enable_metadata_routing=True 启用了元数据路由(请参阅 sklearn.set_config)。请查看 用户指南 以了解路由机制的工作原理。

每个参数的选项如下:

  • True:请求元数据,如果提供则传递给 score。如果未提供元数据,则忽略该请求。

  • False:不请求元数据,元估计器不会将其传递给 score

  • None:不请求元数据,如果用户提供元数据,元估计器将引发错误。

  • str:应将元数据以给定别名而不是原始名称传递给元估计器。

默认值 (sklearn.utils.metadata_routing.UNCHANGED) 保留现有请求。这允许您更改某些参数的请求而不更改其他参数。

在版本 1.3 中新增。

参数:
sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

score 方法中 sample_weight 参数的元数据路由。

返回:
selfobject

更新后的对象。

transform(X)[source]#

Transform X to a cluster-distance space.

In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by transform will typically be dense.

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

New data to transform.

返回:
X_newndarray of shape (n_samples, n_clusters)

X transformed in the new space.