Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
MaetDol committed Dec 7, 2021
2 parents 53825da + 96edc87 commit dd6e5ff
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,16 @@ export default class Kmeans {
const weightsSum = this.sum( weights ),
r = Math.random();
let sum = 0;

if( weightsSum === 0 ) return 0;

for( let i=0; i < weights.length; i++ ) {
sum += weights[i] / weightsSum;
if( r <= sum ) {
return i;
}
}
return sum / weights.length;
}

indexOfMax( arr ) {
Expand Down Expand Up @@ -146,6 +150,7 @@ export default class Kmeans {

// Generate k empty arrays
const classifications = Array.from({length: this.k}, ()=>[]);
this.classifications = classifications;
// Clustering
datas.forEach( data => {
const {centroidIndex} = this.nearestOf( data, centroids );
Expand All @@ -155,7 +160,11 @@ export default class Kmeans {
let inTolerance = true;
const previousCentroids = [...centroids];
// Assign centroids as average of cluster
centroids = classifications.map( cls => this.average( cls ));
centroids = classifications.map( (cls, i) => {
return cls.length
? this.average( cls )
: centroids[i];
});

for( let i=0; i < previousCentroids.length; i++ ) {
const difference = this.difference( previousCentroids[i], centroids[i] );
Expand Down

0 comments on commit dd6e5ff

Please sign in to comment.