Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support initial specification of centroids #2

Merged
merged 3 commits into from
Feb 24, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions lib/KMeansEngine.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class KMeansEngine {
this.k = this.options.k;
this.debug = this.options.debug || false;
this.maxIterations = this.options.maxIterations;
this.initialCentroids = this.options.initialCentroids;
this.callback = callback;

this.validateInput();
Expand Down Expand Up @@ -41,6 +42,21 @@ class KMeansEngine {
(!Number.isInteger(this.maxIterations) || (this.maxIterations <= 0))) {
throw new Error('Max iterations should be a positive integer');
}

if (this.initialCentroids !== undefined) {
if (!_.isArray(this.initialCentroids) || (this.initialCentroids.length !== this.k)) {
throw new Error('Initial centroids should be array of length equal to cluster size')
} else {
// Initial centroids should be array of objects
for (let i = 0; i < this.initialCentroids.length; i += 1) {
const c = this.initialCentroids[i];

if (!_.isObject(c) || _.isArray(c) || _.isFunction(c)) {
throw new Error('Centroids should be array of objects');
}
}
}
}
}

init() {
Expand All @@ -52,11 +68,18 @@ class KMeansEngine {
// map to vector object
this.vectors = this.vectors.map(vector => new Vector(vector));

const randNums = KMeansEngine.getRandomSequence(0, this.vectors.length - 1, this.k);

// randomly pick a vector to be the centroid
for (let i = 0; i < this.k; i += 1) {
this.clusters.push(new Cluster(this.vectors[randNums[i]]));
if (this.initialCentroids === undefined) {
const randNums = KMeansEngine.getRandomSequence(0, this.vectors.length - 1, this.k);
// randomly pick a vector to be the centroid
for (let i = 0; i < this.k; i += 1) {
this.clusters.push(new Cluster(this.vectors[randNums[i]]));
}
} else {
// set things up with the initial centroids
for (let i = 0; i < this.k; i += 1) {
this.clusters.push(new Cluster(new Vector(this.initialCentroids[i])));
}
}

this.showLog(`Number of vectors: ${this.vectors.length}`);
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

54 changes: 54 additions & 0 deletions test/KMeansEngine.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const _ = require('underscore');
const chai = require('chai');

const should = chai.should();
Expand Down Expand Up @@ -47,6 +48,28 @@ describe('KMeansEngine', () => {
kmeans.clusterize(set1, { k: 3, maxIterations: -1 }, () => {});
}).should.to.throw('Max iterations should be a positive integer');
});

it('should only accept initial centroids as array of objects', () => {
(() => {
kmeans.clusterize(set1, { k: 2, initialCentroids: {} }, () => {});
}).should.to.throw('Initial centroids should be array of length equal to cluster size');

(() => {
kmeans.clusterize(set1, { k: 2, initialCentroids: [() => {}, () => {}] }, () => {});
}).should.to.throw('Centroids should be array of objects');

(() => {
kmeans.clusterize(set1, { k: 2, initialCentroids: ['abc', 'def'] }, () => {});
}).should.to.throw('Centroids should be array of objects');

(() => {
kmeans.clusterize(set1, { k: 2, initialCentroids: [123, 456.7] }, () => {});
}).should.to.throw('Centroids should be array of objects');

(() => {
kmeans.clusterize(set1, { k: 2, initialCentroids: [true, true] }, () => {});
}).should.to.throw('Centroids should be array of objects');
});
});

describe('clusterize result', () => {
Expand Down Expand Up @@ -99,5 +122,36 @@ describe('KMeansEngine', () => {
done();
});
});

it('should return same result given same initial centroids', (done) => {
const initialCentroids = [{x: 1, y: 0}, {x: 0, y: 1}, {x: 1, y: 1}];
kmeans.clusterize(set2, { k: 3, maxIterations: 1, initialCentroids: initialCentroids}, (err1, res1) => {
should.not.exist(err1);
res1.should.to.have.property('iterations');
res1.should.to.have.property('clusters');

res1.clusters.should.to.have.lengthOf(3);
res1.clusters.forEach((cluster1) => {
cluster1.should.to.have.property('centroid');
cluster1.should.to.have.property('vectorIds');
});

kmeans.clusterize(set2, { k: 3, maxIterations: 1, initialCentroids: initialCentroids }, (err2, res2) => {
should.not.exist(err2);
res2.should.to.have.property('iterations');
res2.should.to.have.property('clusters');

res2.clusters.should.to.have.lengthOf(3);
res2.clusters.forEach((cluster2) => {
cluster2.should.to.have.property('centroid');
cluster2.should.to.have.property('vectorIds');
});

res1.should.deep.equal(res2);

done();
});
});
});
});
});