Skip to content

Commit

Permalink
fix: improve performance of ward algorithm
Browse files Browse the repository at this point in the history
Use ml-array-median.
  • Loading branch information
targos committed Jul 10, 2019
1 parent b07d3a4 commit 3bad3b6
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 21 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
},
"dependencies": {
"heap": "^0.2.6",
"ml-array-median": "^1.1.1",
"ml-distance-euclidean": "^2.0.0",
"ml-distance-matrix": "^1.0.0"
}
Expand Down
25 changes: 4 additions & 21 deletions src/agnes.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { euclidean } from 'ml-distance-euclidean';
import distanceMatrix from 'ml-distance-matrix';
import median from 'ml-array-median';

import ClusterLeaf from './ClusterLeaf';
import Cluster from './Cluster';
Expand Down Expand Up @@ -90,24 +91,6 @@ function wardLink(cluster1, cluster2, disFun) {
);
}

function compareNumbers(a, b) {
return a - b;
}

function median(values, alreadySorted) {
if (alreadySorted === undefined) alreadySorted = false;
if (!alreadySorted) {
values = [].concat(values).sort(compareNumbers);
}
var l = values.length;
var half = Math.floor(l / 2);
if (l % 2 === 0) {
return (values[half - 1] + values[half]) * 0.5;
} else {
return values[half];
}
}

/**
* Continuously merge nodes that have the least dissimilarity
* @param {Array<Array<number>>} distance - Array of points to be clustered
Expand All @@ -122,7 +105,7 @@ export function agnes(data, options = {}) {
const {
distanceFunction = euclidean,
method = 'single',
isDistanceMatrix = false
isDistanceMatrix = false,
} = options;
let methodFunc;

Expand Down Expand Up @@ -203,10 +186,10 @@ export function agnes(data, options = {}) {
var count = 0;
while (dmin.length > 0) {
let aux = dmin.shift();
const filterInt = function (n) {
const filterInt = (n) => {
return aux.indexOf(n) !== -1;
};
const filterDiff = function (n) {
const filterDiff = (n) => {
return aux.indexOf(n) === -1;
};
for (var q = 0; q < dmin.length; q++) {
Expand Down

0 comments on commit 3bad3b6

Please sign in to comment.