xxxxxxxxxx
50
const data = [{ x: 200, y: 159 }, { x: 10, y: 200 }, { x: 123, y: 10 }, { x: 100, y: 100 }, { x: 302, y: 231 },{ x: 123, y: 139 },{ x: 120, y: 230 },{ x: 130, y: 200 }];
const options = {
k: 3,
maxIter: 4,
threshold: 0.5,
};
let calculated = false;
// Initialize the magicFeature
const kmeans = ml5.kmeans(data, options, clustersCalculated);
// When the model is loaded
function setup(){
createCanvas(400,400);
background(125)
}
function draw(){
if(calculated){
for(i = 0; i < kmeans.dataset.length; i++){
let centroid = kmeans.dataset[i].centroid;
let datapointx = kmeans.dataset[i][0];
let datapointy = kmeans.dataset[i][1];
if(centroid == 0){
fill(255,0,0);
}
else if(centroid == 1){
fill(0,0,255)
}
else{
fill(0,255,0);
}
noStroke();
ellipseMode(CENTER)
ellipse(datapointx, datapointy, 20,20);
fill(0);
textAlign(CENTER,CENTER);
text(i,datapointx, datapointy);
}
}
}
function clustersCalculated() {
console.log('Points Clustered!');
console.log(kmeans.dataset);
console.log(kmeans.centroids);
calculated = true;
}