简体   繁体   English

使用自定义排序 function 对 Javascript 中的对象进行聚类

[英]clustering Objects in Javascript using a custom sort function

I have Objects in Javascript that I would like to sort by clustering them based on the distances between them.我在 Javascript 中有对象,我想根据它们之间的距离对它们进行聚类来排序。 I perform the same analysis in Java, where I have combined a custom distance function and hierarchical clustering.我在 Java 中执行了相同的分析,其中我结合了自定义距离 function 和层次聚类。

However, I can't find any good Javascript alternatives that allow you to define a custom distance metric.但是,我找不到任何允许您定义自定义距离度量的好的 Javascript 替代品。 I was trying to implement a standard Arrays.sort function, but after determining the distance between the Objects I am a bit stuck on the compare function.我试图实现一个标准的 Arrays.sort function,但是在确定了对象之间的距离之后,我有点卡在比较 function 上。

Typically a sort comparator is something like:通常,排序比较器类似于:

function comparefunction(a, b) {
  if (a.nr > b.nr) return 1;
  if (a.nr < b.nr) return -1;
  return 0;
}

But now I have the distance between a and b based on the overlap between them但是现在我根据它们之间的重叠得到了 a 和 b 之间的距离

function comparefunction(clusterA, clusterB) {
  let overlap = 0.0;
  if (relativeOverlapBetweenClusters.has(clusterA)) {
    const relativeOverlapForClusterA = relativeOverlapBetweenClusters.get(clusterA);
    if (relativeOverlapForClusterA.has(clusterB)) {
      overlap = relativeOverlapForClusterA.get(clusterB);
    }
  }
  return 1 - overlap;
}

But it's not sorting properly.但它没有正确排序。 Also, I see that the compareFunction is only invoked a limited number of times.另外,我看到 compareFunction 只被调用了有限的次数。

I implemented a traveling salesman problem and it seems to work quite ok.我实施了一个旅行推销员问题,它似乎工作得很好。 Need to tweak a bit with the distances.需要稍微调整一下距离。 Here is some sample code:这是一些示例代码:

https://codesandbox.io/s/musing-davinci-i3tss?file=/src/index.js https://codesandbox.io/s/musing-davinci-i3tss?file=/src/index.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM