Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2988_ModelsOfModels2/HeuristicLab.Algorithms.DataAnalysis/3.4/kMeans/KMeansClusteringUtil.cs @ 16722

Last change on this file since 16722 was 16565, checked in by gkronber, 6 years ago

#2520: merged changes from PersistenceOverhaul branch (r16451:16564) into trunk

File size: 4.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Problems.DataAnalysis;
26
27namespace HeuristicLab.Algorithms.DataAnalysis {
28  public static class KMeansClusteringUtil {
29    public static IEnumerable<int> FindClosestCenters(IEnumerable<double[]> centers, IDataset dataset, IEnumerable<string> allowedInputVariables, IEnumerable<int> rows) {
30      int nRows = rows.Count();
31      int nCols = allowedInputVariables.Count();
32      int[] closestCenter = new int[nRows];
33      double[] bestCenterDistance = Enumerable.Repeat(double.MaxValue, nRows).ToArray();
34      int centerIndex = 1;
35
36      foreach (double[] center in centers) {
37        if (nCols != center.Length) throw new ArgumentException();
38        int rowIndex = 0;
39        foreach (var row in rows) {
40          // calc euclidian distance of point to center
41          double centerDistance = 0;
42          int col = 0;
43          foreach (var inputVariable in allowedInputVariables) {
44            double d = center[col++] - dataset.GetDoubleValue(inputVariable, row);
45            d = d * d; // square;
46            centerDistance += d;
47            if (centerDistance > bestCenterDistance[rowIndex]) break;
48          }
49          if (centerDistance < bestCenterDistance[rowIndex]) {
50            bestCenterDistance[rowIndex] = centerDistance;
51            closestCenter[rowIndex] = centerIndex;
52          }
53          rowIndex++;
54        }
55        centerIndex++;
56      }
57      return closestCenter;
58    }
59
60    public static double CalculateIntraClusterSumOfSquares(KMeansClusteringModel model, IDataset dataset, IEnumerable<int> rows) {
61      List<int> clusterValues = model.GetClusterValues(dataset, rows).ToList();
62      List<string> allowedInputVariables = model.AllowedInputVariables.ToList();
63      int nCols = allowedInputVariables.Count;
64      Dictionary<int, List<double[]>> clusterPoints = new Dictionary<int, List<double[]>>();
65      Dictionary<int, double[]> clusterMeans = new Dictionary<int, double[]>();
66      foreach (var clusterValue in clusterValues.Distinct()) {
67        clusterPoints.Add(clusterValue, new List<double[]>());
68      }
69
70      // collect points of clusters
71      int clusterValueIndex = 0;
72      foreach (var row in rows) {
73        double[] p = new double[allowedInputVariables.Count];
74        for (int i = 0; i < nCols; i++) {
75          p[i] = dataset.GetDoubleValue(allowedInputVariables[i], row);
76        }
77        clusterPoints[clusterValues[clusterValueIndex++]].Add(p);
78      }
79      // calculate cluster means
80      foreach (var pair in clusterPoints) {
81        double[] mean = new double[nCols];
82        foreach (var p in pair.Value) {
83          for (int i = 0; i < nCols; i++) {
84            mean[i] += p[i];
85          }
86        }
87        for (int i = 0; i < nCols; i++) {
88          mean[i] /= pair.Value.Count;
89        }
90        clusterMeans[pair.Key] = mean;
91      }
92      // calculate distances
93      double allCenterDistances = 0;
94      foreach (var pair in clusterMeans) {
95        double[] mean = pair.Value;
96        double centerDistances = 0;
97        foreach (var clusterPoint in clusterPoints[pair.Key]) {
98          double centerDistance = 0;
99          for (int i = 0; i < nCols; i++) {
100            double d = mean[i] - clusterPoint[i];
101            d = d * d;
102            centerDistance += d;
103          }
104          centerDistances += centerDistance;
105        }
106        allCenterDistances += centerDistances;
107      }
108      return allCenterDistances;
109    }
110  }
111}
Note: See TracBrowser for help on using the repository browser.