【问题标题】:Which unsupervised clustering algorithm from the sklearn library can I use with custom distance?sklearn 库中的哪种无监督聚类算法可以用于自定义距离?
【发布时间】:2014-10-16 09:13:29
【问题描述】:

我有一个函数,它将两个样本作为输入并返回它们的距离,我从这个函数中定义了一个度量

def TwoPointsDistance(x1, x2):
    cord1 = f.rf.apply(x1)
    cord2 = f.rf.apply(x2)
    return 1 - (cord1==cord2).sum()/f.n_trees

metric = sk.neighbors.DistanceMetric.get_metric('pyfunc',
                                                     func=TwoPointsDistance)

现在我想根据这个指标对我的数据进行聚类。我希望看到一些将其用作距离度量的无监督聚类算法示例。

编辑:我对这个算法特别感兴趣: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html#sklearn.cluster.DBSCAN

编辑:我试过了

DBSCAN(metric=metric, algorithm='brute').fit(Xor)

但我收到一个错误:

>>> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/dist-packages/sklearn/cluster/dbscan_.py", line 249, in fit
    clust = dbscan(X, **self.get_params())
  File "/usr/local/lib/python3.4/dist-packages/sklearn/cluster/dbscan_.py", line 100, in dbscan
    metric=metric, p=p)
  File "/usr/local/lib/python3.4/dist-packages/sklearn/neighbors/unsupervised.py", line 83, in __init__
    leaf_size=leaf_size, metric=metric, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/sklearn/neighbors/base.py", line 127, in _init_params
    % (metric, algorithm))
ValueError: Metric '<sklearn.neighbors.dist_metrics.PyFuncDistance object at 0x7ff5c299f358>' not valid for algorithm 'brute'
>>> 

【问题讨论】:

    标签: python scikit-learn cluster-analysis


    【解决方案1】:

    多年后的今天,我仍然在不同的背景下偶然发现了这一点。解决方案很简单:直接将函数作为指标传递。

    BSCAN(metric=TwoPointsDistance, algorithm='brute').fit(Xor)

    【讨论】:

      【解决方案2】:

      我试图弄清楚为什么会出现这个错误...我首先认为sklearn.neighbors.NearestNeighbors(这是 DBSCAN 的基础)将被限制在sklearn.neighbors.base.VALID_METRICS["brute"] 中列出的那些距离。但是从源码来看,任何callable函数都应该没问题——看来你的距离是不可调用的?

      请试试这个:

      DBSCAN(metric=TwoPointsDistance, algorithm='brute').fit(Xor)
      

      即无需将您的距离包装为neighbors.DistanceMetric。现在允许在这里使用这些对我来说似乎有点不一致......

      我自己,我在自定义距离函数上使用 ELKI 取得了巨大成功,并且有一个关于如何编写这些可用的简短教程:http://elki.dbs.ifi.lmu.de/wiki/Tutorial/DistanceFunctions

      【讨论】:

      • 感谢您的回答。最后,我找到了解决方法。我计算了样本之间的距离并将其保存在大小为 n_samples x n_samples 的矩阵 d 中。然后我使用了预先计算的度量和矩阵 d 作为输入。
      猜你喜欢
      • 2020-05-13
      • 2020-01-21
      • 2012-07-09
      • 2015-09-07
      • 2017-04-18
      • 2014-08-06
      • 2018-04-04
      • 1970-01-01
      • 2020-07-21
      相关资源
      最近更新 更多