二分KMeans#
- class sklearn.cluster.BisectingKMeans(n_clusters=8, *, init='random', n_init=1, random_state=None, max_iter=300, verbose=0, tol=0.0001, copy_x=True, algorithm='lloyd', bisecting_strategy='biggest_inertia')[source]#
Bisecting K-Means 聚类。
在用户指南中阅读更多内容。
版本 1.1 中新增。
- 参数:
- n_clustersint, default=8
The number of clusters to form as well as the number of centroids to generate.
- init{‘k-means++’, ‘random’} 或 callable, 默认值=’random’
每次二分法的初始化方法。
‘k-means++’:以智能方式选择k-均值聚类的初始簇中心,以加速收敛。详见 k_init 中的注意事项。
‘random’: choose
n_clustersobservations (rows) at random from data for the initial centroids.如果传入一个可调用对象,它应该接受参数 X、n_clusters 和一个随机状态,并返回一个初始化。请注意,二分算法总是执行2路分裂,因此可调用对象将始终以
n_clusters=2调用,并且应该返回2个质心。- n_initint, default=1
每次二分中,内部k-means算法将以不同的质心种子运行的次数。这将使得每次二分都能根据惯性(inertia)在 n_init 次连续运行中产生最佳输出。
- random_stateint, RandomState instance or None, default=None
确定内部K-Means中质心初始化的随机数生成。使用整数可使随机性确定。详见术语表。
- max_iterint, default=300
每次二分时,内部k-means算法的最大迭代次数。
- verboseint, default=0
Verbosity mode.
- tolfloat, default=1e-4
相对于连续两次迭代中簇中心差异的Frobenius范数的相对容差,用于声明收敛。在每次二分中的内部k-means算法中使用,以选择最佳可能的簇。
- copy_xbool, default=True
预计算距离时,首先对数据进行中心化会更精确。如果 copy_x 为 True(默认值),则不会修改原始数据。如果为 False,则会修改原始数据,并在函数返回前恢复,但通过减去再添加数据均值可能会引入微小的数值差异。请注意,如果原始数据不是C-连续的,即使 copy_x 为 False 也会创建副本。如果原始数据是稀疏的,但不是 CSR 格式,即使 copy_x 为 False 也会创建副本。
- algorithm{“lloyd”, “elkan”}, default=”lloyd”
二分法中使用的内部K-means算法。经典的EM风格算法是
"lloyd"。"elkan"变体通过使用三角不等式,在某些具有明确定义簇的数据集上可能更有效。然而,由于需要额外分配形状为(n_samples, n_clusters)的数组,它会占用更多内存。- bisecting_strategy{“biggest_inertia”, “largest_cluster”}, 默认值=”biggest_inertia”
定义应如何执行二分。
“biggest_inertia” 意味着 BisectingKMeans 将始终检查所有已计算的簇,找出具有最大 SSE(平方误差和)的簇并将其二分。这种方法注重精度,但可能在执行时间方面成本较高(特别是对于大量数据点)。
“largest_cluster” - BisectingKMeans 将始终从所有先前计算的簇中,分割分配点数最多的簇。这应该比通过 SSE 选择(“biggest_inertia”)更快,并且在大多数情况下可能会产生相似的结果。
- 属性:
- cluster_centers_ndarray of shape (n_clusters, n_features)
簇中心的坐标。如果算法在完全收敛之前停止(参见
tol和max_iter),这些将与labels_不一致。- labels_ndarray of shape (n_samples,)
每个点的标签。
- inertia_float
样本到其最近簇中心的平方距离之和,如果提供了样本权重则按其加权。
- n_features_in_int
在 拟合 期间看到的特征数。
- feature_names_in_shape 为 (
n_features_in_,) 的 ndarray 在 fit 期间看到的特征名称。仅当
X具有全部为字符串的特征名称时才定义。
另请参阅
KMeansK-Means算法的原始实现。
注意事项
当 n_cluster 小于3时,由于不必要的计算,效率可能不高。
示例
>>> from sklearn.cluster import BisectingKMeans >>> import numpy as np >>> X = np.array([[1, 1], [10, 1], [3, 1], ... [10, 0], [2, 1], [10, 2], ... [10, 8], [10, 9], [10, 10]]) >>> bisect_means = BisectingKMeans(n_clusters=3, random_state=0).fit(X) >>> bisect_means.labels_ array([0, 2, 0, 2, 0, 2, 1, 1, 1], dtype=int32) >>> bisect_means.predict([[0, 0], [12, 3]]) array([0, 2], dtype=int32) >>> bisect_means.cluster_centers_ array([[ 2., 1.], [10., 9.], [10., 1.]])
有关二分KMeans和K-Means的比较,请参阅示例二分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连续的,这将导致内存复制。
- y被忽略
Not used, present here for API consistency by convention.
- sample_weightshape 为 (n_samples,) 的 array-like, default=None
X中每个观测值的权重。如果为 None,所有观测值都被赋予相同的权重。如果
init是一个可调用对象,则在初始化期间不使用sample_weight。
- 返回:
- self
拟合的估计器。
- 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]#
预测X中每个样本所属的簇。
预测是通过沿着层次树向下寻找最近的叶簇来完成的。
In the vector quantization literature,
cluster_centers_is called the code book and each value returned bypredictis 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$') BisectingKMeans[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
配置
transform和fit_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$') BisectingKMeans[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
transformwill 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.