【问题标题】:How to assign new observations to cluster using distance matrix and kmedoids?如何使用距离矩阵和 kmedoids 将新的观察结果分配给集群?
【发布时间】:2021-11-23 06:12:16
【问题描述】:

我有一个数据框,其中包含我的数据框中每个文档之间的 Word Mover 距离。我正在为此运行 kmediods 以生成集群。

       1      2     3      4      5   
  1  0.00   0.05  0.07   0.04   0.05
  2  0.05   0.00  0.06   0.04   0.05
  3. 0.07   0.06  0.00   0.06   0.06
  4  0.04   0.04. 0.06   0.00   0.04
  5  0.05   0.05  0.06   0.04   0.00

  kmed = KMedoids(n_clusters= 3, random_state=123, method  ='pam').fit(distance)

在这个初始矩阵上运行并生成集群后,我想添加新的点进行集群。将新文档添加到距离矩阵后,我最终得到:

       1      2     3      4      5      6
  1  0.00   0.05  0.07   0.04   0.05   0.12
  2  0.05   0.00  0.06   0.04   0.05   0.21 
  3. 0.07   0.06  0.00   0.06   0.06   0.01
  4  0.04   0.04. 0.06   0.00   0.04   0.05
  5  0.05   0.05  0.06   0.04   0.00   0.12
  6. 0.12   0.21  0.01   0.05   0.12   0.00

我已尝试在新行上使用 kmed.predict。

kmed.predict(new_distance.loc[-1: ])

但是,这给了我一个尺寸不兼容的错误X.shape[1] == 6Y.shape[1] == 5

如何使用新文档的这个距离来确定它应该属于哪个集群?这甚至可能吗,还是我每次都必须重新计算集群?谢谢!

【问题讨论】:

  • 如何计算文档之间的距离?
  • 这些只是示例中的随机数。在实践中,它是每个文档之间的单词移动器的距离。如果值为 0,则没有距离,因为文档是相同的。

标签: python nlp cluster-analysis distance k-means


【解决方案1】:

k-medoids 的 source code 说明如下:

def transform(self, X):
    """Transforms X to cluster-distance space.

    Parameters
    ----------
    X : {array-like, sparse matrix}, shape (n_query, n_features), \
            or (n_query, n_indexed) if metric == 'precomputed'
        Data to transform.
   """

我假设您使用 precomputed 度量标准(因为您计算分类器外部的距离),所以在您的情况下,n_query 是新文档的数量,n_indexed 是文档的数量调用了fit 方法。

在您的特定情况下,当您在 5 个文档上拟合模型然后想要对第 6 个文档进行分类时,用于分类的 X 应该具有形状 (1,5),可以计算为

kmed.predict(new_distance.loc[-1: , :-1])

【讨论】:

  • 我使用 metric = 'precomputed' 与 method = 'pam' 和 'pam' 进行了测试,结果总是更好。我必须更改提供的索引代码才能从距离矩阵中实际获取新行。然后,我能够得到预测。有没有办法验证这些结果?我的显示所有相同的集群
【解决方案2】:

这是我的试验,我们每次都要重新计算新点和旧点之间的距离。

import pandas as pd
from sklearn_extra.cluster import KMedoids
from  sklearn.metrics import pairwise_distances
import numpy as np

# dummy data for trial
df = pd.DataFrame({0: [0,1],1 : [1,2]})
# calculatie distance
distance = pairwise_distances(df.values, df.values)
# fit model
kmed = KMedoids(n_clusters=2, random_state=123, method='pam').fit(distance)
new_point = [2,3]
distance = pairwise_distances(np.array(new_point).reshape(1, -1), df.values)
#calculate the distance between the new point and the initial dataset
print(distance)
#get ride of the last element which is the ditance of the new point with itself
print(kmed.predict(distance[0][:2].reshape(1, -1)))

【讨论】:

    猜你喜欢
    • 2012-11-12
    • 2016-06-07
    • 2016-12-19
    • 1970-01-01
    • 2015-11-06
    • 2018-05-14
    • 2023-01-15
    • 2013-04-03
    • 1970-01-01
    相关资源
    最近更新 更多