|
@@ -54,7 +54,7 @@ function clusterize(vector, options, callback) { |
|
|
if (!options || !options.k || options.k<1) return callback(new Error('Provide a correct number k of clusters'));
|
|
|
if (!_.isArray(vector)) return callback(new Error('Provide an array of data'));
|
|
|
this.options = options;
|
|
|
- this.v = vector;
|
|
|
+ this.v = this.checkV(vector);
|
|
|
this.k = this.options.k;
|
|
|
if (this.v.length < this.k) return callback(new Error('The number of points must be greater than the number k of clusters'));
|
|
|
|
|
@@ -78,6 +78,33 @@ function clusterize(vector, options, callback) { |
|
|
};
|
|
|
|
|
|
|
|
|
+/**
|
|
|
+ * Check vector
|
|
|
+ * - if all the elements have the same dimension
|
|
|
+ * - parseFloat()
|
|
|
+ * - !isNaN()
|
|
|
+ */
|
|
|
+clusterize.prototype.checkV = function(v) {
|
|
|
+ var dim = 1;
|
|
|
+ if (_.isArray(v[0])) dim = v[0].length;
|
|
|
+ for (var i=0; i<v.length; ++i) {
|
|
|
+ if (!_.isArray(v[i])) {
|
|
|
+ if (dim!=1) throw new Error('All the elements must have the same dimension');
|
|
|
+ v[i] = parseFloat(v[i]);
|
|
|
+ if (isNaN(v[i])) throw new Error('All the elements must be float type');
|
|
|
+ }
|
|
|
+ else {
|
|
|
+ if (v[i].length != dim) throw new Error('All the elements must have the same dimension');
|
|
|
+ for (var j=0; j<v[i].length; ++j) {
|
|
|
+ v[i][j] = parseFloat(v[i][j]);
|
|
|
+ if (isNaN(v[i][j])) throw new Error('All the elements must be float type');
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return v;
|
|
|
+};
|
|
|
+
|
|
|
+
|
|
|
/**
|
|
|
* Initialize the groups arrays
|
|
|
*/
|
|
@@ -86,7 +113,7 @@ clusterize.prototype.initialize = function() { |
|
|
for (var i=0; i<this.k; ++i)
|
|
|
this.groups[i] = new Group(this);
|
|
|
this.indexes = new Array(); // used to choose randomly the initial centroids
|
|
|
- for (var i=0; i<this.v.length; i++)
|
|
|
+ for (var i=0; i<this.v.length; ++i)
|
|
|
this.indexes[i] = i;
|
|
|
return this;
|
|
|
};
|
|
@@ -178,8 +205,13 @@ Group.prototype.defineCentroid = function(self){ |
|
|
this.centroidIndex = self.indexes[i];
|
|
|
self.indexes.splice(i,1);
|
|
|
this.centroid = new Array();
|
|
|
- for (var i=0; i<self.v[this.centroidIndex].length; ++i)
|
|
|
- this.centroid[i] = self.v[this.centroidIndex][i];
|
|
|
+ if (!_.isArray(self.v[this.centroidIndex])) { // only one dimension
|
|
|
+ this.centroid[0] = self.v[this.centroidIndex];
|
|
|
+ }
|
|
|
+ else {
|
|
|
+ for (var i=0; i<self.v[this.centroidIndex].length; ++i)
|
|
|
+ this.centroid[i] = self.v[this.centroidIndex][i];
|
|
|
+ }
|
|
|
}
|
|
|
this.centroidMoved = (_.isEqual(this.centroid,this.centroidOld)) ? false : true;
|
|
|
if (this.centroid.length == 0) console.log('1. was passiert hier??');
|
|
|
0 comments on commit
34aa104