Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15802 was 15018, checked in by gkronber, 8 years ago

#2520 introduced StorableConstructorFlag type for StorableConstructors

File size: 21.1 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;
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  [StorableType("d2c00bc0-ece7-40f0-aac3-4ddfa0ec2697")]
46  public sealed class TSNEAlgorithm : BasicAlgorithm {
47    public override bool SupportsPause {
48      get { return true; }
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    private const string UpdateIntervalParameterName = "UpdateInterval";
74    #endregion
75
76    #region result names
77    private const string IterationResultName = "Iteration";
78    private const string ErrorResultName = "Error";
79    private const string ErrorPlotResultName = "Error plot";
80    private const string ScatterPlotResultName = "Scatterplot";
81    private const string DataResultName = "Projected data";
82    #endregion
83
84    #region parameter properties
85    public IFixedValueParameter<DoubleValue> PerplexityParameter {
86      get { return Parameters[PerplexityParameterName] as IFixedValueParameter<DoubleValue>; }
87    }
88    public IFixedValueParameter<DoubleValue> ThetaParameter {
89      get { return Parameters[ThetaParameterName] as IFixedValueParameter<DoubleValue>; }
90    }
91    public IFixedValueParameter<IntValue> NewDimensionsParameter {
92      get { return Parameters[NewDimensionsParameterName] as IFixedValueParameter<IntValue>; }
93    }
94    public IValueParameter<IDistance<double[]>> DistanceParameter {
95      get { return Parameters[DistanceParameterName] as IValueParameter<IDistance<double[]>>; }
96    }
97    public IFixedValueParameter<IntValue> MaxIterationsParameter {
98      get { return Parameters[MaxIterationsParameterName] as IFixedValueParameter<IntValue>; }
99    }
100    public IFixedValueParameter<IntValue> StopLyingIterationParameter {
101      get { return Parameters[StopLyingIterationParameterName] as IFixedValueParameter<IntValue>; }
102    }
103    public IFixedValueParameter<IntValue> MomentumSwitchIterationParameter {
104      get { return Parameters[MomentumSwitchIterationParameterName] as IFixedValueParameter<IntValue>; }
105    }
106    public IFixedValueParameter<DoubleValue> InitialMomentumParameter {
107      get { return Parameters[InitialMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
108    }
109    public IFixedValueParameter<DoubleValue> FinalMomentumParameter {
110      get { return Parameters[FinalMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
111    }
112    public IFixedValueParameter<DoubleValue> EtaParameter {
113      get { return Parameters[EtaParameterName] as IFixedValueParameter<DoubleValue>; }
114    }
115    public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
116      get { return Parameters[SetSeedRandomlyParameterName] as IFixedValueParameter<BoolValue>; }
117    }
118    public IFixedValueParameter<IntValue> SeedParameter {
119      get { return Parameters[SeedParameterName] as IFixedValueParameter<IntValue>; }
120    }
121    public IFixedValueParameter<StringValue> ClassesParameter {
122      get { return Parameters[ClassesParameterName] as IFixedValueParameter<StringValue>; }
123    }
124    public IFixedValueParameter<BoolValue> NormalizationParameter {
125      get { return Parameters[NormalizationParameterName] as IFixedValueParameter<BoolValue>; }
126    }
127    public IFixedValueParameter<IntValue> UpdateIntervalParameter {
128      get { return Parameters[UpdateIntervalParameterName] as IFixedValueParameter<IntValue>; }
129    }
130    #endregion
131
132    #region  Properties
133    public IDistance<double[]> Distance {
134      get { return DistanceParameter.Value; }
135    }
136    public double Perplexity {
137      get { return PerplexityParameter.Value.Value; }
138      set { PerplexityParameter.Value.Value = value; }
139    }
140    public double Theta {
141      get { return ThetaParameter.Value.Value; }
142      set { ThetaParameter.Value.Value = value; }
143    }
144    public int NewDimensions {
145      get { return NewDimensionsParameter.Value.Value; }
146      set { NewDimensionsParameter.Value.Value = value; }
147    }
148    public int MaxIterations {
149      get { return MaxIterationsParameter.Value.Value; }
150      set { MaxIterationsParameter.Value.Value = value; }
151    }
152    public int StopLyingIteration {
153      get { return StopLyingIterationParameter.Value.Value; }
154      set { StopLyingIterationParameter.Value.Value = value; }
155    }
156    public int MomentumSwitchIteration {
157      get { return MomentumSwitchIterationParameter.Value.Value; }
158      set { MomentumSwitchIterationParameter.Value.Value = value; }
159    }
160    public double InitialMomentum {
161      get { return InitialMomentumParameter.Value.Value; }
162      set { InitialMomentumParameter.Value.Value = value; }
163    }
164    public double FinalMomentum {
165      get { return FinalMomentumParameter.Value.Value; }
166      set { FinalMomentumParameter.Value.Value = value; }
167    }
168    public double Eta {
169      get { return EtaParameter.Value.Value; }
170      set { EtaParameter.Value.Value = value; }
171    }
172    public bool SetSeedRandomly {
173      get { return SetSeedRandomlyParameter.Value.Value; }
174      set { SetSeedRandomlyParameter.Value.Value = value; }
175    }
176    public int Seed {
177      get { return SeedParameter.Value.Value; }
178      set { SeedParameter.Value.Value = value; }
179    }
180    public string Classes {
181      get { return ClassesParameter.Value.Value; }
182      set { ClassesParameter.Value.Value = value; }
183    }
184    public bool Normalization {
185      get { return NormalizationParameter.Value.Value; }
186      set { NormalizationParameter.Value.Value = value; }
187    }
188
189    public int UpdateInterval {
190      get { return UpdateIntervalParameter.Value.Value; }
191      set { UpdateIntervalParameter.Value.Value = value; }
192    }
193    #endregion
194
195    #region Constructors & Cloning
196    [StorableConstructor]
197    private TSNEAlgorithm(StorableConstructorFlag deserializing) : base(deserializing) { }
198
199    private TSNEAlgorithm(TSNEAlgorithm original, Cloner cloner) : base(original, cloner) {
200      if (original.dataRowNames != null)
201        this.dataRowNames = new Dictionary<string, List<int>>(original.dataRowNames);
202      if (original.dataRows != null)
203        this.dataRows = original.dataRows.ToDictionary(kvp => kvp.Key, kvp => cloner.Clone(kvp.Value));
204      if (original.state != null)
205        this.state = cloner.Clone(original.state);
206      this.iter = original.iter;
207    }
208    public override IDeepCloneable Clone(Cloner cloner) { return new TSNEAlgorithm(this, cloner); }
209    public TSNEAlgorithm() {
210      Problem = new RegressionProblem();
211      Parameters.Add(new ValueParameter<IDistance<double[]>>(DistanceParameterName, "The distance function used to differentiate similar from non-similar points", new EuclideanDistance()));
212      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)));
213      Parameters.Add(new FixedValueParameter<DoubleValue>(ThetaParameterName, "Value describing how much appoximated " +
214                                                                              "gradients my differ from exact gradients. Set to 0 for exact calculation and in [0,1] otherwise. " +
215                                                                              "Appropriate values for theta are between 0.1 and 0.7 (default = 0.5). CAUTION: exact calculation of " +
216                                                                              "forces requires building a non-sparse N*N matrix where N is the number of data points. This may " +
217                                                                              "exceed memory limitations. The function is designed to run on large (N > 5000) data sets. It may give" +
218                                                                              " poor performance on very small data sets(it is better to use a standard t - SNE implementation on such data).", new DoubleValue(0)));
219      Parameters.Add(new FixedValueParameter<IntValue>(NewDimensionsParameterName, "Dimensionality of projected space (usually 2 for easy visual analysis)", new IntValue(2)));
220      Parameters.Add(new FixedValueParameter<IntValue>(MaxIterationsParameterName, "Maximum number of iterations for gradient descent.", new IntValue(1000)));
221      Parameters.Add(new FixedValueParameter<IntValue>(StopLyingIterationParameterName, "Number of iterations after which p is no longer approximated.", new IntValue(0)));
222      Parameters.Add(new FixedValueParameter<IntValue>(MomentumSwitchIterationParameterName, "Number of iterations after which the momentum in the gradient descent is switched.", new IntValue(0)));
223      Parameters.Add(new FixedValueParameter<DoubleValue>(InitialMomentumParameterName, "The initial momentum in the gradient descent.", new DoubleValue(0.5)));
224      Parameters.Add(new FixedValueParameter<DoubleValue>(FinalMomentumParameterName, "The final momentum.", new DoubleValue(0.8)));
225      Parameters.Add(new FixedValueParameter<DoubleValue>(EtaParameterName, "Gradient descent learning rate.", new DoubleValue(10)));
226      Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "If the seed should be random.", new BoolValue(true)));
227      Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The seed used if it should not be random.", new IntValue(0)));
228      Parameters.Add(new FixedValueParameter<StringValue>(ClassesParameterName, "name of the column specifying the class lables of each data point. If the label column can not be found training/test is used as labels.", new StringValue("none")));
229      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)));
230      Parameters.Add(new FixedValueParameter<IntValue>(UpdateIntervalParameterName, "", new IntValue(50)));
231      Parameters[UpdateIntervalParameterName].Hidden = true;
232
233      MomentumSwitchIterationParameter.Hidden = true;
234      InitialMomentumParameter.Hidden = true;
235      FinalMomentumParameter.Hidden = true;
236      StopLyingIterationParameter.Hidden = true;
237      EtaParameter.Hidden = false;
238    }
239    #endregion
240
241    [Storable]
242    private Dictionary<string, List<int>> dataRowNames;
243    [Storable]
244    private Dictionary<string, ScatterPlotDataRow> dataRows;
245    [Storable]
246    private TSNEStatic<double[]>.TSNEState state;
247    [Storable]
248    private int iter;
249
250    public override void Prepare() {
251      base.Prepare();
252      dataRowNames = null;
253      dataRows = null;
254      state = null;
255    }
256
257    protected override void Run(CancellationToken cancellationToken) {
258      var problemData = Problem.ProblemData;
259      // set up and initialized everything if necessary
260      if (state == null) {
261        if (SetSeedRandomly) Seed = new System.Random().Next();
262        var random = new MersenneTwister((uint)Seed);
263        var dataset = problemData.Dataset;
264        var allowedInputVariables = problemData.AllowedInputVariables.ToArray();
265        var data = new double[dataset.Rows][];
266        for (var row = 0; row < dataset.Rows; row++)
267          data[row] = allowedInputVariables.Select(col => dataset.GetDoubleValue(col, row)).ToArray();
268
269        if (Normalization) data = NormalizeData(data);
270
271        state = TSNEStatic<double[]>.CreateState(data, Distance, random, NewDimensions, Perplexity, Theta,
272          StopLyingIteration, MomentumSwitchIteration, InitialMomentum, FinalMomentum, Eta);
273
274        SetUpResults(data);
275        iter = 0;
276      }
277      for (; iter < MaxIterations && !cancellationToken.IsCancellationRequested; iter++) {
278        if (iter % UpdateInterval == 0)
279          Analyze(state);
280        TSNEStatic<double[]>.Iterate(state);
281      }
282      Analyze(state);
283    }
284
285    private void SetUpResults(IReadOnlyCollection<double[]> data) {
286      if (Results == null) return;
287      var results = Results;
288      dataRowNames = new Dictionary<string, List<int>>();
289      dataRows = new Dictionary<string, ScatterPlotDataRow>();
290      var problemData = Problem.ProblemData;
291
292      //color datapoints acording to classes variable (be it double or string)
293      if (problemData.Dataset.VariableNames.Contains(Classes)) {
294        if ((problemData.Dataset as Dataset).VariableHasType<string>(Classes)) {
295          var classes = problemData.Dataset.GetStringValues(Classes).ToArray();
296          for (var i = 0; i < classes.Length; i++) {
297            if (!dataRowNames.ContainsKey(classes[i])) dataRowNames.Add(classes[i], new List<int>());
298            dataRowNames[classes[i]].Add(i);
299          }
300        } else if ((problemData.Dataset as Dataset).VariableHasType<double>(Classes)) {
301          var classValues = problemData.Dataset.GetDoubleValues(Classes).ToArray();
302          var max = classValues.Max() + 0.1;
303          var min = classValues.Min() - 0.1;
304          const int contours = 8;
305          for (var i = 0; i < contours; i++) {
306            var contourname = GetContourName(i, min, max, contours);
307            dataRowNames.Add(contourname, new List<int>());
308            dataRows.Add(contourname, new ScatterPlotDataRow(contourname, "", new List<Point2D<double>>()));
309            dataRows[contourname].VisualProperties.Color = GetHeatMapColor(i, contours);
310            dataRows[contourname].VisualProperties.PointSize = i + 3;
311          }
312          for (var i = 0; i < classValues.Length; i++) {
313            dataRowNames[GetContourName(classValues[i], min, max, contours)].Add(i);
314          }
315        }
316      } else {
317        dataRowNames.Add("Training", problemData.TrainingIndices.ToList());
318        dataRowNames.Add("Test", problemData.TestIndices.ToList());
319      }
320
321      if (!results.ContainsKey(IterationResultName)) results.Add(new Result(IterationResultName, new IntValue(0)));
322      else ((IntValue)results[IterationResultName].Value).Value = 0;
323
324      if (!results.ContainsKey(ErrorResultName)) results.Add(new Result(ErrorResultName, new DoubleValue(0)));
325      else ((DoubleValue)results[ErrorResultName].Value).Value = 0;
326
327      if (!results.ContainsKey(ErrorPlotResultName)) results.Add(new Result(ErrorPlotResultName, new DataTable(ErrorPlotResultName, "Development of errors during gradient descent")));
328      else results[ErrorPlotResultName].Value = new DataTable(ErrorPlotResultName, "Development of errors during gradient descent");
329
330      var plot = results[ErrorPlotResultName].Value as DataTable;
331      if (plot == null) throw new ArgumentException("could not create/access error data table in results collection");
332
333      if (!plot.Rows.ContainsKey("errors")) plot.Rows.Add(new DataRow("errors"));
334      plot.Rows["errors"].Values.Clear();
335      plot.Rows["errors"].VisualProperties.StartIndexZero = true;
336
337      results.Add(new Result(ScatterPlotResultName, "Plot of the projected data", new ScatterPlot(DataResultName, "")));
338      results.Add(new Result(DataResultName, "Projected Data", new DoubleMatrix()));
339    }
340
341    private void Analyze(TSNEStatic<double[]>.TSNEState tsneState) {
342      if (Results == null) return;
343      var results = Results;
344      var plot = results[ErrorPlotResultName].Value as DataTable;
345      if (plot == null) throw new ArgumentException("Could not create/access error data table in results collection.");
346      var errors = plot.Rows["errors"].Values;
347      var c = tsneState.EvaluateError();
348      errors.Add(c);
349      ((IntValue)results[IterationResultName].Value).Value = tsneState.iter;
350      ((DoubleValue)results[ErrorResultName].Value).Value = errors.Last();
351
352      var ndata = Normalize(tsneState.newData);
353      results[DataResultName].Value = new DoubleMatrix(ndata);
354      var splot = results[ScatterPlotResultName].Value as ScatterPlot;
355      FillScatterPlot(ndata, splot);
356    }
357
358    private void FillScatterPlot(double[,] lowDimData, ScatterPlot plot) {
359      foreach (var rowName in dataRowNames.Keys) {
360        if (!plot.Rows.ContainsKey(rowName))
361          plot.Rows.Add(dataRows.ContainsKey(rowName) ? dataRows[rowName] : new ScatterPlotDataRow(rowName, "", new List<Point2D<double>>()));
362        plot.Rows[rowName].Points.Replace(dataRowNames[rowName].Select(i => new Point2D<double>(lowDimData[i, 0], lowDimData[i, 1])));
363      }
364    }
365
366    private static double[,] Normalize(double[,] data) {
367      var max = new double[data.GetLength(1)];
368      var min = new double[data.GetLength(1)];
369      var res = new double[data.GetLength(0), data.GetLength(1)];
370      for (var i = 0; i < max.Length; i++) max[i] = min[i] = data[0, i];
371      for (var i = 0; i < data.GetLength(0); i++)
372        for (var j = 0; j < data.GetLength(1); j++) {
373          var v = data[i, j];
374          max[j] = Math.Max(max[j], v);
375          min[j] = Math.Min(min[j], v);
376        }
377      for (var i = 0; i < data.GetLength(0); i++) {
378        for (var j = 0; j < data.GetLength(1); j++) {
379          res[i, j] = (data[i, j] - (max[j] + min[j]) / 2) / (max[j] - min[j]);
380        }
381      }
382      return res;
383    }
384
385    private static double[][] NormalizeData(IReadOnlyList<double[]> data) {
386      // as in tSNE implementation by van der Maaten
387      var n = data[0].Length;
388      var mean = new double[n];
389      var max = new double[n];
390      var nData = new double[data.Count][];
391      for (var i = 0; i < n; i++) {
392        mean[i] = Enumerable.Range(0, data.Count).Select(x => data[x][i]).Average();
393        max[i] = Enumerable.Range(0, data.Count).Max(x => Math.Abs(data[x][i]));
394      }
395      for (var i = 0; i < data.Count; i++) {
396        nData[i] = new double[n];
397        for (var j = 0; j < n; j++) nData[i][j] = (data[i][j] - mean[j]) / max[j];
398      }
399      return nData;
400    }
401
402    private static Color GetHeatMapColor(int contourNr, int noContours) {
403      var q = (double)contourNr / noContours;  // q in [0,1]
404      var c = q < 0.5 ? Color.FromArgb((int)(q * 2 * 255), 255, 0) : Color.FromArgb(255, (int)((1 - q) * 2 * 255), 0);
405      return c;
406    }
407
408    private static string GetContourName(double value, double min, double max, int noContours) {
409      var size = (max - min) / noContours;
410      var contourNr = (int)((value - min) / size);
411      return GetContourName(contourNr, min, max, noContours);
412    }
413
414    private static string GetContourName(int i, double min, double max, int noContours) {
415      var size = (max - min) / noContours;
416      return "[" + (min + i * size) + ";" + (min + (i + 1) * size) + ")";
417    }
418  }
419}
Note: See TracBrowser for help on using the repository browser.