Free cookie consent management tool by TermsFeed Policy Generator

source: branches/TSNE/HeuristicLab.Algorithms.DataAnalysis/3.4/TSNE/TSNEAlgorithm.cs @ 14788

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

#2700: refactoring

File size: 19.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Drawing;
25using System.Linq;
26using System.Threading;
27using HeuristicLab.Analysis;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Optimization;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.Problems.DataAnalysis;
35using HeuristicLab.Random;
36
37namespace HeuristicLab.Algorithms.DataAnalysis {
38  /// <summary>
39  /// t-distributed stochastic neighbourhood embedding (tSNE) projects the data in a low dimensional
40  /// space to allow visual cluster identification.
41  /// </summary>
42  [Item("tSNE", "t-distributed stochastic neighbourhood embedding projects the data in a low " +
43                "dimensional space to allow visual cluster identification.")]
44  [Creatable(CreatableAttribute.Categories.DataAnalysis, Priority = 100)]
45  [StorableClass]
46  public sealed class TSNEAlgorithm : BasicAlgorithm {
47    public override bool SupportsPause {
48      get { return false; }
49    }
50    public override Type ProblemType {
51      get { return typeof(IDataAnalysisProblem); }
52    }
53    public new IDataAnalysisProblem Problem {
54      get { return (IDataAnalysisProblem)base.Problem; }
55      set { base.Problem = value; }
56    }
57
58    #region parameter names
59    private const string DistanceParameterName = "DistanceFunction";
60    private const string PerplexityParameterName = "Perplexity";
61    private const string ThetaParameterName = "Theta";
62    private const string NewDimensionsParameterName = "Dimensions";
63    private const string MaxIterationsParameterName = "MaxIterations";
64    private const string StopLyingIterationParameterName = "StopLyingIteration";
65    private const string MomentumSwitchIterationParameterName = "MomentumSwitchIteration";
66    private const string InitialMomentumParameterName = "InitialMomentum";
67    private const string FinalMomentumParameterName = "FinalMomentum";
68    private const string EtaParameterName = "Eta";
69    private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
70    private const string SeedParameterName = "Seed";
71    private const string ClassesParameterName = "ClassNames";
72    private const string NormalizationParameterName = "Normalization";
73    #endregion
74
75    #region result names
76    private const string IterationResultName = "Iteration";
77    private const string ErrorResultName = "Error";
78    private const string ErrorPlotResultName = "Error plot";
79    private const string ScatterPlotResultName = "Scatterplot";
80    private const string DataResultName = "Projected data";
81    #endregion
82
83    #region parameter properties
84    public IFixedValueParameter<DoubleValue> PerplexityParameter {
85      get { return Parameters[PerplexityParameterName] as IFixedValueParameter<DoubleValue>; }
86    }
87    public IFixedValueParameter<DoubleValue> ThetaParameter {
88      get { return Parameters[ThetaParameterName] as IFixedValueParameter<DoubleValue>; }
89    }
90    public IFixedValueParameter<IntValue> NewDimensionsParameter {
91      get { return Parameters[NewDimensionsParameterName] as IFixedValueParameter<IntValue>; }
92    }
93    public IValueParameter<IDistance<double[]>> DistanceParameter {
94      get { return Parameters[DistanceParameterName] as IValueParameter<IDistance<double[]>>; }
95    }
96    public IFixedValueParameter<IntValue> MaxIterationsParameter {
97      get { return Parameters[MaxIterationsParameterName] as IFixedValueParameter<IntValue>; }
98    }
99    public IFixedValueParameter<IntValue> StopLyingIterationParameter {
100      get { return Parameters[StopLyingIterationParameterName] as IFixedValueParameter<IntValue>; }
101    }
102    public IFixedValueParameter<IntValue> MomentumSwitchIterationParameter {
103      get { return Parameters[MomentumSwitchIterationParameterName] as IFixedValueParameter<IntValue>; }
104    }
105    public IFixedValueParameter<DoubleValue> InitialMomentumParameter {
106      get { return Parameters[InitialMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
107    }
108    public IFixedValueParameter<DoubleValue> FinalMomentumParameter {
109      get { return Parameters[FinalMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
110    }
111    public IFixedValueParameter<DoubleValue> EtaParameter {
112      get { return Parameters[EtaParameterName] as IFixedValueParameter<DoubleValue>; }
113    }
114    public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
115      get { return Parameters[SetSeedRandomlyParameterName] as IFixedValueParameter<BoolValue>; }
116    }
117    public IFixedValueParameter<IntValue> SeedParameter {
118      get { return Parameters[SeedParameterName] as IFixedValueParameter<IntValue>; }
119    }
120    public IFixedValueParameter<StringValue> ClassesParameter {
121      get { return Parameters[ClassesParameterName] as IFixedValueParameter<StringValue>; }
122    }
123    public IFixedValueParameter<BoolValue> NormalizationParameter {
124      get { return Parameters[NormalizationParameterName] as IFixedValueParameter<BoolValue>; }
125    }
126    #endregion
127
128    #region  Properties
129    public IDistance<double[]> Distance {
130      get { return DistanceParameter.Value; }
131    }
132    public double Perplexity {
133      get { return PerplexityParameter.Value.Value; }
134      set { PerplexityParameter.Value.Value = value; }
135    }
136    public double Theta {
137      get { return ThetaParameter.Value.Value; }
138      set { ThetaParameter.Value.Value = value; }
139    }
140    public int NewDimensions {
141      get { return NewDimensionsParameter.Value.Value; }
142      set { NewDimensionsParameter.Value.Value = value; }
143    }
144    public int MaxIterations {
145      get { return MaxIterationsParameter.Value.Value; }
146      set { MaxIterationsParameter.Value.Value = value; }
147    }
148    public int StopLyingIteration {
149      get { return StopLyingIterationParameter.Value.Value; }
150      set { StopLyingIterationParameter.Value.Value = value; }
151    }
152    public int MomentumSwitchIteration {
153      get { return MomentumSwitchIterationParameter.Value.Value; }
154      set { MomentumSwitchIterationParameter.Value.Value = value; }
155    }
156    public double InitialMomentum {
157      get { return InitialMomentumParameter.Value.Value; }
158      set { InitialMomentumParameter.Value.Value = value; }
159    }
160    public double FinalMomentum {
161      get { return FinalMomentumParameter.Value.Value; }
162      set { FinalMomentumParameter.Value.Value = value; }
163    }
164    public double Eta {
165      get { return EtaParameter.Value.Value; }
166      set { EtaParameter.Value.Value = value; }
167    }
168    public bool SetSeedRandomly {
169      get { return SetSeedRandomlyParameter.Value.Value; }
170      set { SetSeedRandomlyParameter.Value.Value = value; }
171    }
172    public int Seed {
173      get { return SeedParameter.Value.Value; }
174      set { SeedParameter.Value.Value = value; }
175    }
176    public string Classes {
177      get { return ClassesParameter.Value.Value; }
178      set { ClassesParameter.Value.Value = value; }
179    }
180    public bool Normalization {
181      get { return NormalizationParameter.Value.Value; }
182      set { NormalizationParameter.Value.Value = value; }
183    }
184    [Storable]
185    public TSNE<double[]> tsne;
186    #endregion
187
188    #region Constructors & Cloning
189    [StorableConstructor]
190    private TSNEAlgorithm(bool deserializing) : base(deserializing) { }
191    private TSNEAlgorithm(TSNEAlgorithm original, Cloner cloner) : base(original, cloner) { }
192    public override IDeepCloneable Clone(Cloner cloner) { return new TSNEAlgorithm(this, cloner); }
193    public TSNEAlgorithm() {
194      Problem = new RegressionProblem();
195      Parameters.Add(new ValueParameter<IDistance<double[]>>(DistanceParameterName, "The distance function used to differentiate similar from non-similar points", new EuclideanDistance()));
196      Parameters.Add(new FixedValueParameter<DoubleValue>(PerplexityParameterName, "Perplexity-Parameter of tSNE. Comparable to k in a k-nearest neighbour algorithm. Recommended value is floor(number of points /3) or lower", new DoubleValue(25)));
197      Parameters.Add(new FixedValueParameter<DoubleValue>(ThetaParameterName, "Value describing how much appoximated gradients my differ from exact gradients. Set to 0 for exact calculation and in [0,1] otherwise \n CAUTION: exact calculation of forces requires building a non-sparse N*N matrix where N is the number of data points\n This may exceed memory limitations", new DoubleValue(0)));
198      Parameters.Add(new FixedValueParameter<IntValue>(NewDimensionsParameterName, "Dimensionality of projected space (usually 2 for easy visual analysis)", new IntValue(2)));
199      Parameters.Add(new FixedValueParameter<IntValue>(MaxIterationsParameterName, "Maximum number of iterations for gradient descent", new IntValue(1000)));
200      Parameters.Add(new FixedValueParameter<IntValue>(StopLyingIterationParameterName, "Number of iterations after which p is no longer approximated", new IntValue(0)));
201      Parameters.Add(new FixedValueParameter<IntValue>(MomentumSwitchIterationParameterName, "Number of iterations after which the momentum in the gradient descent is switched", new IntValue(0)));
202      Parameters.Add(new FixedValueParameter<DoubleValue>(InitialMomentumParameterName, "The initial momentum in the gradient descent", new DoubleValue(0.5)));
203      Parameters.Add(new FixedValueParameter<DoubleValue>(FinalMomentumParameterName, "The final momentum", new DoubleValue(0.8)));
204      Parameters.Add(new FixedValueParameter<DoubleValue>(EtaParameterName, "Gradient descent learning rate", new DoubleValue(200)));
205      Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "If the seed should be random", new BoolValue(true)));
206      Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The seed used if it should not be random", new IntValue(0)));
207      Parameters.Add(new FixedValueParameter<StringValue>(ClassesParameterName, "name of the column specifying the class lables of each data point. \n if the lable column can not be found training/test is used as labels", new StringValue("none")));
208      Parameters.Add(new FixedValueParameter<BoolValue>(NormalizationParameterName, "Whether the data should be zero centered and have variance of 1 for each variable, so different scalings are ignored", new BoolValue(true)));
209
210      MomentumSwitchIterationParameter.Hidden = true;
211      InitialMomentumParameter.Hidden = true;
212      FinalMomentumParameter.Hidden = true;
213      StopLyingIterationParameter.Hidden = true;
214      EtaParameter.Hidden = true;
215    }
216    #endregion
217
218    [Storable]
219    private Dictionary<string, List<int>> dataRowNames;    // TODO
220    [Storable]
221    private Dictionary<string, ScatterPlotDataRow> dataRows; // TODO
222
223
224    protected override void Run(CancellationToken cancellationToken) {
225      var problemData = Problem.ProblemData;
226
227      // set up and run tSNE
228      if (SetSeedRandomly) Seed = new System.Random().Next();
229      var random = new MersenneTwister((uint)Seed);
230      var dataset = problemData.Dataset;
231      var allowedInputVariables = problemData.AllowedInputVariables.ToArray();
232      var data = new double[dataset.Rows][];
233      for (var row = 0; row < dataset.Rows; row++) data[row] = allowedInputVariables.Select(col => dataset.GetDoubleValue(col, row)).ToArray();
234      if (Normalization) data = NormalizeData(data);
235
236      var tsneState = TSNE<double[]>.CreateState(data, Distance, random, NewDimensions, Perplexity, Theta, StopLyingIteration, MomentumSwitchIteration, InitialMomentum, FinalMomentum, Eta);
237
238      SetUpResults(data);
239      for (int iter = 0; iter < MaxIterations && !cancellationToken.IsCancellationRequested; iter++)
240      {
241        TSNE<double[]>.Iterate(tsneState);
242        Analyze(tsneState);
243      }
244    }
245
246    private void SetUpResults(IReadOnlyCollection<double[]> data) {
247      if (Results == null) return;
248      var results = Results;
249      dataRowNames = new Dictionary<string, List<int>>();
250      dataRows = new Dictionary<string, ScatterPlotDataRow>();
251      var problemData = Problem.ProblemData;
252
253      //color datapoints acording to classes variable (be it double or string)
254      if (problemData.Dataset.VariableNames.Contains(Classes)) {
255        if ((problemData.Dataset as Dataset).VariableHasType<string>(Classes)) {
256          var classes = problemData.Dataset.GetStringValues(Classes).ToArray();
257          for (var i = 0; i < classes.Length; i++) {
258            if (!dataRowNames.ContainsKey(classes[i])) dataRowNames.Add(classes[i], new List<int>());
259            dataRowNames[classes[i]].Add(i);
260          }
261        } else if ((problemData.Dataset as Dataset).VariableHasType<double>(Classes)) {
262          var classValues = problemData.Dataset.GetDoubleValues(Classes).ToArray();
263          var max = classValues.Max() + 0.1;     // TODO consts
264          var min = classValues.Min() - 0.1;
265          const int contours = 8;
266          for (var i = 0; i < contours; i++) {
267            var contourname = GetContourName(i, min, max, contours);
268            dataRowNames.Add(contourname, new List<int>());
269            dataRows.Add(contourname, new ScatterPlotDataRow(contourname, "", new List<Point2D<double>>()));
270            dataRows[contourname].VisualProperties.Color = GetHeatMapColor(i, contours);
271            dataRows[contourname].VisualProperties.PointSize = i + 3;
272          }
273          for (var i = 0; i < classValues.Length; i++) {
274            dataRowNames[GetContourName(classValues[i], min, max, contours)].Add(i);
275          }
276        }
277      } else {
278        dataRowNames.Add("Training", problemData.TrainingIndices.ToList());
279        dataRowNames.Add("Test", problemData.TestIndices.ToList());
280      }
281
282      if (!results.ContainsKey(IterationResultName)) results.Add(new Result(IterationResultName, new IntValue(0)));
283      else ((IntValue)results[IterationResultName].Value).Value = 0;
284
285      if (!results.ContainsKey(ErrorResultName)) results.Add(new Result(ErrorResultName, new DoubleValue(0)));
286      else ((DoubleValue)results[ErrorResultName].Value).Value = 0;
287
288      if (!results.ContainsKey(ErrorPlotResultName)) results.Add(new Result(ErrorPlotResultName, new DataTable(ErrorPlotResultName, "Development of errors during gradient descent")));
289      else results[ErrorPlotResultName].Value = new DataTable(ErrorPlotResultName, "Development of errors during gradient descent");
290
291      var plot = results[ErrorPlotResultName].Value as DataTable;
292      if (plot == null) throw new ArgumentException("could not create/access error data table in results collection");
293
294      if (!plot.Rows.ContainsKey("errors")) plot.Rows.Add(new DataRow("errors"));
295      plot.Rows["errors"].Values.Clear();
296
297      results.Add(new Result(ScatterPlotResultName, "Plot of the projected data", new ScatterPlot(DataResultName, "")));
298      results.Add(new Result(DataResultName, "Projected Data", new DoubleMatrix()));
299    }
300
301    private void Analyze(TSNE<double[]>.TSNEState tsneState) {
302      if (Results == null) return;
303      var results = Results;
304      var plot = results[ErrorPlotResultName].Value as DataTable;
305      if (plot == null) throw new ArgumentException("Could not create/access error data table in results collection.");
306      var errors = plot.Rows["errors"].Values;
307      var c = tsneState.EvaluateError();
308      errors.Add(c);
309      ((IntValue)results[IterationResultName].Value).Value = tsneState.iter + 1;
310      ((DoubleValue)results[ErrorResultName].Value).Value = errors.Last();
311
312      var ndata = Normalize(tsneState.newData);
313      results[DataResultName].Value = new DoubleMatrix(ndata);
314      var splot = results[ScatterPlotResultName].Value as ScatterPlot;
315      FillScatterPlot(ndata, splot);
316    }
317
318    private void FillScatterPlot(double[,] lowDimData, ScatterPlot plot) {
319      foreach (var rowName in dataRowNames.Keys) {
320        if (!plot.Rows.ContainsKey(rowName))
321          plot.Rows.Add(dataRows.ContainsKey(rowName) ? dataRows[rowName] : new ScatterPlotDataRow(rowName, "", new List<Point2D<double>>()));
322        plot.Rows[rowName].Points.Replace(dataRowNames[rowName].Select(i => new Point2D<double>(lowDimData[i, 0], lowDimData[i, 1])));
323      }
324    }
325
326    private static double[,] Normalize(double[,] data) {
327      var max = new double[data.GetLength(1)];
328      var min = new double[data.GetLength(1)];
329      var res = new double[data.GetLength(0), data.GetLength(1)];
330      for (var i = 0; i < max.Length; i++) max[i] = min[i] = data[0, i];
331      for (var i = 0; i < data.GetLength(0); i++)
332        for (var j = 0; j < data.GetLength(1); j++) {
333          var v = data[i, j];
334          max[j] = Math.Max(max[j], v);
335          min[j] = Math.Min(min[j], v);
336        }
337      for (var i = 0; i < data.GetLength(0); i++) {
338        for (var j = 0; j < data.GetLength(1); j++) {
339          res[i, j] = (data[i, j] - (max[j] + min[j]) / 2) / (max[j] - min[j]);
340        }
341      }
342      return res;
343    }
344
345    private static double[][] NormalizeData(IReadOnlyList<double[]> data) {
346      var n = data[0].Length;
347      var mean = new double[n];
348      var sd = new double[n];
349      var nData = new double[data.Count][];
350      for (var i = 0; i < n; i++) {
351        var i1 = i;
352        sd[i] = Enumerable.Range(0, data.Count).Select(x => data[x][i1]).StandardDeviation();
353        mean[i] = Enumerable.Range(0, data.Count).Select(x => data[x][i1]).Average();
354      }
355      for (var i = 0; i < data.Count; i++) {
356        nData[i] = new double[n];
357        for (var j = 0; j < n; j++) nData[i][j] = (data[i][j] - mean[j]) / sd[j];
358      }
359      return nData;
360    }
361
362    private static Color GetHeatMapColor(int contourNr, int noContours) {
363      var q = (double)contourNr / noContours;  // q in [0,1]
364      var c = q < 0.5 ? Color.FromArgb((int)(q * 2 * 255), 255, 0) : Color.FromArgb(255, (int)((1 - q) * 2 * 255), 0);
365      return c;
366    }
367
368    private static string GetContourName(double value, double min, double max, int noContours) {
369      var size = (max - min) / noContours;
370      var contourNr = (int)((value - min) / size);
371      return GetContourName(contourNr, min, max, noContours);
372    }
373
374    private static string GetContourName(int i, double min, double max, int noContours) {
375      var size = (max - min) / noContours;
376      return "[" + (min + i * size) + ";" + (min + (i + 1) * size) + ")";
377    }
378  }
379}
Note: See TracBrowser for help on using the repository browser.