Skip to content

Commit

Permalink
Merge pull request #125 from llimllib/master
Browse files Browse the repository at this point in the history
Fix ckmeans
  • Loading branch information
tmcw committed Aug 17, 2015
2 parents 519799b + 95abb23 commit b938e56
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
4 changes: 2 additions & 2 deletions src/ckmeans.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,14 @@ function ckmeans(data, nClusters) {
var squaredDifference = Math.pow(
sorted[sortedIdx] - firstClusterMean, 2);
matrix[cluster][sortedIdx] = matrix[cluster][sortedIdx - 1] +
((sortedIdx - 1) / sortedIdx) * squaredDifference;
(sortedIdx / (sortedIdx + 1)) * squaredDifference;

// We're computing a running mean by taking the previous
// mean value, multiplying it by the number of elements
// seen so far, and then dividing it by the number of
// elements total.
var newSum = sortedIdx * firstClusterMean + sorted[sortedIdx];
firstClusterMean = newSum / sortedIdx;
firstClusterMean = newSum / (sortedIdx + 1);

} else {

Expand Down
12 changes: 7 additions & 5 deletions test/ckmeans.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@ test('C k-means', function(t) {
t.deepEqual(example, [[-1, -1, -1, -1], [2, 2, 2], [4, 5, 6]]);
t.deepEqual(cK([1, 2, 3], 3), [[1], [2], [3]]);

// is this right?
t.deepEqual(cK([1, 2, 2, 3], 3), [[1, 2], [2], [3]]);
t.deepEqual(cK([1, 2, 2, 3, 3], 3), [[1, 2], [2], [3, 3]]);
t.deepEqual(cK([1, 2, 3, 2, 3], 3), [[1, 2], [2], [3, 3]]);
t.deepEqual(cK([3, 2, 3, 2, 1], 3), [[1, 2], [2], [3, 3]]);
t.deepEqual(cK([0, 3, 4], 2), [[0], [3, 4]]),
t.deepEqual(cK([-3, 0, 4], 2), [[-3, 0], [4]]),

t.deepEqual(cK([1, 2, 2, 3], 3), [[1], [2, 2], [3]]);
t.deepEqual(cK([1, 2, 2, 3, 3], 3), [[1], [2, 2], [3, 3]]);
t.deepEqual(cK([1, 2, 3, 2, 3], 3), [[1], [2, 2], [3, 3]]);
t.deepEqual(cK([3, 2, 3, 2, 1], 3), [[1], [2, 2], [3, 3]]);
t.deepEqual(cK([3, 2, 3, 5, 2, 1], 3), [[1, 2, 2], [3, 3], [5]]);

t.deepEqual(cK([0, 1, 2, 100, 101, 103], 2), [[0, 1, 2], [100, 101, 103]]);
Expand Down

0 comments on commit b938e56

Please sign in to comment.