Instantly share code, notes, and snippets.

Last active January 19, 2016 15:15
Show Gist options
• Save blacki/c41127e3593052d6cf4e to your computer and use it in GitHub Desktop.
K-Means Algorithm

K-Means Unsupervised Learning Algorithm. Also see K-Means Equilibria here.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 function randomPoints(_num, _dist, _xR, _yR) { if(arguments.length<2) _dist = 'irwinHall' if(!_xR||!_yR) { var xRange = yRange = [0,1] }else{ var xRange = d3.range(_xR[0],_xR[1]) var yRange = d3.range(_yR[0],_yR[1]) } if(_dist == 'uniform'){ x = d3.range(0,_num).map(function () { return d3.shuffle(xRange)[0] }) y = d3.range(0,_num).map(function () { return d3.shuffle(yRange)[0] }) }else{ x = d3.range(0,_num).map(function () { if(['bates','irwinHall'].indexOf(_dist)>-1){ rnd = d3.random[_dist](_dist=='bates'?8:1)() rnd = Math.round(rnd*d3.max(xRange)) }else if(_dist=='normal'){ rnd = d3.random[_dist](d3.mean(xRange),d3.mean(xRange)/6)() }else if(_dist=='logNormal'){ rnd = d3.random[_dist]()() rnd = Math.round(rnd*d3.mean(xRange)/6) } return rnd }).map(function (d) {return Math.abs(d)}) y = d3.range(0,_num).map(function () { if(['bates','irwinHall'].indexOf(_dist)>-1){ rnd = d3.random[_dist](_dist=='bates'?8:1)() rnd = Math.round(rnd*d3.max(yRange)) }else if(_dist=='normal'){ rnd = d3.random[_dist](d3.mean(yRange),d3.mean(yRange)/6)() }else if(_dist=='logNormal'){ rnd = d3.random[_dist]()() rnd = Math.round(rnd*d3.mean(yRange)/6) } return rnd }).map(function (d) {return Math.abs(d)}) } return d3.zip(x,y).map(function(d){return {x:d[0],y:d[1]}}) } function clusterPoints(numC,numPts,_dist,_xR,_yR){ var clusters = [] d3.range(0,numC).forEach(function (i) { cPts = randomPoints(4,'uniform',_xR,_yR) c={} c.dist = _dist c.xRange = d3.extent(cPts.map(function(p){return p.x})) c.yRange = d3.extent(cPts.map(function(p){return p.y})) c.points = randomPoints(numPts,c.dist,c.xRange,c.yRange) clusters.push(c) }) // clusters.reduce(function (prev,curr) {return prev.concat(curr)}) return clusters }
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 K-means
View raw

(Sorry about that, but we can’t show files that are this big right now.)