public static List <List <double> > RecalculateCoordinateOfClusterCenters(Dictionary <List <double>, List <double> > clusters, List <List <double> > clusterCenters) { List <List <double> > newClusterCenters = new List <List <double> >(); foreach (List <double> clusterCenter in clusterCenters) { var map = clusters.Where(point => ListUtils.IsListEqualsToAnother(point.Value, clusterCenter)); List <double> sums = new List <double>(); for (int i = 0; i < clusterCenter.Count; i++) { sums.Add(0); } foreach (KeyValuePair <List <double>, List <double> > point in map) { List <double> pointCoordinates = point.Key; for (int i = 0; i < pointCoordinates.Count; i++) { sums[i] += pointCoordinates[i]; } } for (int i = 0; i < sums.Count; i++) { sums[i] /= map.Count(); } newClusterCenters.Add(sums); } return(newClusterCenters); }
public ActionResult <KMeansResponse> Post([FromForm(Name = "file")] IFormFile file, [FromQuery] int numberOfClusters = 3) { var lines = _getScvRows.GetLines(file); var points = lines.Transform(); var result = new KMeansResponse(); var centroid = new Centroids(); List <List <double> > clusterCenters = AlgorithmsUtils.MakeInitialSeeds(points, numberOfClusters); bool stop = false; Dictionary <List <double>, List <double> > clusters = null; while (!stop) { _logger.LogInformation($"Iteration = {iteration}"); iteration++; clusters = KMeansAlgorithm.MakeClusters(points, clusterCenters); List <List <double> > oldClusterCenters = clusterCenters; //recalculete center of clusters clusterCenters = KMeansAlgorithm.RecalculateCoordinateOfClusterCenters(clusters, clusterCenters); if (ListUtils.IsListEqualsToAnother(clusterCenters, oldClusterCenters)) { int counter = 1; stop = true; result.Centroids = new Centroids(); var list = new List <PointsAndClusterNumber>(); foreach (var center in clusterCenters) { var map = clusters.Where(point => ListUtils.IsListEqualsToAnother(point.Value, center)); foreach (var item in map) { var pointAndCluster = new PointsAndClusterNumber() { Point = new List <double>() }; pointAndCluster.Point = item.Key; pointAndCluster.ClusterNumber = counter; list.Add(pointAndCluster); } counter++; } result.PointsAndClusterNumber = list; result.Centroids.Centroid = clusterCenters; } } return(Ok(result)); }