使用预先计算的聚类中心重建 k-means

Reconstructing k-means using pre-computed cluster centres

我正在使用 k-means 聚类,聚类数量为 60。因为一些聚类的意义不大,我已经从聚类中心数组(count = 8)中删除了那些聚类中心,并且保存在 clean_cluster_array

这次,我用 init = clean_cluster_centers 重新拟合 k-means 模型。和 n_clusters = 52max_iter = 1 因为我想尽可能避免重新安装。

基本思想是用 clean_cluster_centers 重新创建新模型。这里的问题是,我们要删除大量的集群;即使 n_iter = 1,该模型也能快速配置到更稳定的中心。有什么方法可以重新创建 k-means 模型吗?

如果您拟合了 KMeans 对象,它具有 cluster_centers_ 属性。您可以通过执行以下操作直接更新它:

cls.cluster_centers_ = new_cluster_centers

因此,如果您想要一个具有干净簇中心的新对象,只需执行以下操作:

cls = KMeans().fit(X)
cls2 = cls.copy()
cls2.cluster_centers_ = new_cluster_centers

现在,由于预测函数仅检查您的对象是否具有名为 cluster_centers_ 的非空属性,您可以使用预测函数

def predict(self, X):
    """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.

    Parameters
    ----------
    X : {array-like, sparse matrix}, shape = [n_samples, n_features]
        New data to predict.

    Returns
    -------
    labels : array, shape [n_samples,]
        Index of the cluster each sample belongs to.
    """
    check_is_fitted(self, 'cluster_centers_')

    X = self._check_test_data(X)
    x_squared_norms = row_norms(X, squared=True)
    return _labels_inertia(X, x_squared_norms, self.cluster_centers_)[0]