Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/TSNE/TSNEAlgorithm.cs @ 14923

Last change on this file since 14923 was 14863, checked in by gkronber, 8 years ago

#2700 fixed bug in cloning ctor

File size: 21.1 KB
RevLine 
[14414]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
[14518]22using System;
[14512]23using System.Collections.Generic;
24using System.Drawing;
[14414]25using System.Linq;
[14518]26using System.Threading;
[14414]27using HeuristicLab.Analysis;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
[14518]31using HeuristicLab.Optimization;
[14414]32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.Problems.DataAnalysis;
35using HeuristicLab.Random;
36
37namespace HeuristicLab.Algorithms.DataAnalysis {
38  /// <summary>
[14785]39  /// t-distributed stochastic neighbourhood embedding (tSNE) projects the data in a low dimensional
[14767]40  /// space to allow visual cluster identification.
[14414]41  /// </summary>
[14785]42  [Item("tSNE", "t-distributed stochastic neighbourhood embedding projects the data in a low " +
[14767]43                "dimensional space to allow visual cluster identification.")]
[14414]44  [Creatable(CreatableAttribute.Categories.DataAnalysis, Priority = 100)]
45  [StorableClass]
[14785]46  public sealed class TSNEAlgorithm : BasicAlgorithm {
[14767]47    public override bool SupportsPause {
[14807]48      get { return true; }
[14558]49    }
[14767]50    public override Type ProblemType {
[14518]51      get { return typeof(IDataAnalysisProblem); }
52    }
[14767]53    public new IDataAnalysisProblem Problem {
[14518]54      get { return (IDataAnalysisProblem)base.Problem; }
55      set { base.Problem = value; }
56    }
[14414]57
[14785]58    #region parameter names
[14414]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";
[14512]71    private const string ClassesParameterName = "ClassNames";
[14518]72    private const string NormalizationParameterName = "Normalization";
[14859]73    private const string UpdateIntervalParameterName = "UpdateInterval";
[14414]74    #endregion
75
[14788]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
[14785]84    #region parameter properties
[14767]85    public IFixedValueParameter<DoubleValue> PerplexityParameter {
[14414]86      get { return Parameters[PerplexityParameterName] as IFixedValueParameter<DoubleValue>; }
87    }
[14785]88    public IFixedValueParameter<DoubleValue> ThetaParameter {
89      get { return Parameters[ThetaParameterName] as IFixedValueParameter<DoubleValue>; }
[14414]90    }
[14767]91    public IFixedValueParameter<IntValue> NewDimensionsParameter {
[14414]92      get { return Parameters[NewDimensionsParameterName] as IFixedValueParameter<IntValue>; }
93    }
[14785]94    public IValueParameter<IDistance<double[]>> DistanceParameter {
95      get { return Parameters[DistanceParameterName] as IValueParameter<IDistance<double[]>>; }
[14414]96    }
[14767]97    public IFixedValueParameter<IntValue> MaxIterationsParameter {
[14414]98      get { return Parameters[MaxIterationsParameterName] as IFixedValueParameter<IntValue>; }
99    }
[14767]100    public IFixedValueParameter<IntValue> StopLyingIterationParameter {
[14414]101      get { return Parameters[StopLyingIterationParameterName] as IFixedValueParameter<IntValue>; }
102    }
[14767]103    public IFixedValueParameter<IntValue> MomentumSwitchIterationParameter {
[14414]104      get { return Parameters[MomentumSwitchIterationParameterName] as IFixedValueParameter<IntValue>; }
105    }
[14767]106    public IFixedValueParameter<DoubleValue> InitialMomentumParameter {
[14414]107      get { return Parameters[InitialMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
108    }
[14767]109    public IFixedValueParameter<DoubleValue> FinalMomentumParameter {
[14414]110      get { return Parameters[FinalMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
111    }
[14767]112    public IFixedValueParameter<DoubleValue> EtaParameter {
[14414]113      get { return Parameters[EtaParameterName] as IFixedValueParameter<DoubleValue>; }
114    }
[14767]115    public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
[14414]116      get { return Parameters[SetSeedRandomlyParameterName] as IFixedValueParameter<BoolValue>; }
117    }
[14767]118    public IFixedValueParameter<IntValue> SeedParameter {
[14414]119      get { return Parameters[SeedParameterName] as IFixedValueParameter<IntValue>; }
120    }
[14767]121    public IFixedValueParameter<StringValue> ClassesParameter {
[14512]122      get { return Parameters[ClassesParameterName] as IFixedValueParameter<StringValue>; }
123    }
[14767]124    public IFixedValueParameter<BoolValue> NormalizationParameter {
[14518]125      get { return Parameters[NormalizationParameterName] as IFixedValueParameter<BoolValue>; }
126    }
[14859]127    public IFixedValueParameter<IntValue> UpdateIntervalParameter {
128      get { return Parameters[UpdateIntervalParameterName] as IFixedValueParameter<IntValue>; }
129    }
[14414]130    #endregion
131
132    #region  Properties
[14785]133    public IDistance<double[]> Distance {
[14414]134      get { return DistanceParameter.Value; }
135    }
[14767]136    public double Perplexity {
[14414]137      get { return PerplexityParameter.Value.Value; }
[14785]138      set { PerplexityParameter.Value.Value = value; }
[14414]139    }
[14767]140    public double Theta {
[14785]141      get { return ThetaParameter.Value.Value; }
142      set { ThetaParameter.Value.Value = value; }
[14414]143    }
[14767]144    public int NewDimensions {
[14414]145      get { return NewDimensionsParameter.Value.Value; }
[14785]146      set { NewDimensionsParameter.Value.Value = value; }
[14414]147    }
[14767]148    public int MaxIterations {
[14414]149      get { return MaxIterationsParameter.Value.Value; }
[14785]150      set { MaxIterationsParameter.Value.Value = value; }
[14414]151    }
[14767]152    public int StopLyingIteration {
[14414]153      get { return StopLyingIterationParameter.Value.Value; }
[14785]154      set { StopLyingIterationParameter.Value.Value = value; }
[14414]155    }
[14767]156    public int MomentumSwitchIteration {
[14414]157      get { return MomentumSwitchIterationParameter.Value.Value; }
[14785]158      set { MomentumSwitchIterationParameter.Value.Value = value; }
[14414]159    }
[14767]160    public double InitialMomentum {
[14414]161      get { return InitialMomentumParameter.Value.Value; }
[14785]162      set { InitialMomentumParameter.Value.Value = value; }
[14414]163    }
[14767]164    public double FinalMomentum {
[14414]165      get { return FinalMomentumParameter.Value.Value; }
[14785]166      set { FinalMomentumParameter.Value.Value = value; }
[14414]167    }
[14767]168    public double Eta {
[14785]169      get { return EtaParameter.Value.Value; }
170      set { EtaParameter.Value.Value = value; }
[14414]171    }
[14767]172    public bool SetSeedRandomly {
[14414]173      get { return SetSeedRandomlyParameter.Value.Value; }
[14785]174      set { SetSeedRandomlyParameter.Value.Value = value; }
[14414]175    }
[14785]176    public int Seed {
177      get { return SeedParameter.Value.Value; }
178      set { SeedParameter.Value.Value = value; }
[14414]179    }
[14767]180    public string Classes {
[14512]181      get { return ClassesParameter.Value.Value; }
[14785]182      set { ClassesParameter.Value.Value = value; }
[14512]183    }
[14767]184    public bool Normalization {
[14518]185      get { return NormalizationParameter.Value.Value; }
[14785]186      set { NormalizationParameter.Value.Value = value; }
[14518]187    }
[14859]188
189    public int UpdateInterval {
190      get { return UpdateIntervalParameter.Value.Value; }
191      set { UpdateIntervalParameter.Value.Value = value; }
192    }
[14414]193    #endregion
194
195    #region Constructors & Cloning
196    [StorableConstructor]
[14785]197    private TSNEAlgorithm(bool deserializing) : base(deserializing) { }
[14807]198
199    private TSNEAlgorithm(TSNEAlgorithm original, Cloner cloner) : base(original, cloner) {
[14863]200      if(original.dataRowNames!=null)
[14807]201      this.dataRowNames = new Dictionary<string, List<int>>(original.dataRowNames);
[14863]202      if (original.dataRows != null)
203        this.dataRows = original.dataRows.ToDictionary(kvp => kvp.Key, kvp => cloner.Clone(kvp.Value));
[14859]204      if (original.state != null)
[14807]205        this.state = cloner.Clone(original.state);
206      this.iter = original.iter;
207    }
[14785]208    public override IDeepCloneable Clone(Cloner cloner) { return new TSNEAlgorithm(this, cloner); }
209    public TSNEAlgorithm() {
[14414]210      Problem = new RegressionProblem();
[14785]211      Parameters.Add(new ValueParameter<IDistance<double[]>>(DistanceParameterName, "The distance function used to differentiate similar from non-similar points", new EuclideanDistance()));
[14807]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)));
[14837]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)));
[14785]219      Parameters.Add(new FixedValueParameter<IntValue>(NewDimensionsParameterName, "Dimensionality of projected space (usually 2 for easy visual analysis)", new IntValue(2)));
[14807]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)));
[14837]225      Parameters.Add(new FixedValueParameter<DoubleValue>(EtaParameterName, "Gradient descent learning rate.", new DoubleValue(10)));
[14807]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)));
[14859]230      Parameters.Add(new FixedValueParameter<IntValue>(UpdateIntervalParameterName, "", new IntValue(50)));
231      Parameters[UpdateIntervalParameterName].Hidden = true;
[14518]232
233      MomentumSwitchIterationParameter.Hidden = true;
234      InitialMomentumParameter.Hidden = true;
235      FinalMomentumParameter.Hidden = true;
236      StopLyingIterationParameter.Hidden = true;
[14837]237      EtaParameter.Hidden = false;
[14414]238    }
239    #endregion
240
[14788]241    [Storable]
[14807]242    private Dictionary<string, List<int>> dataRowNames;
[14788]243    [Storable]
[14807]244    private Dictionary<string, ScatterPlotDataRow> dataRows;
245    [Storable]
246    private TSNEStatic<double[]>.TSNEState state;
247    [Storable]
248    private int iter;
[14414]249
[14807]250    public override void Prepare() {
251      base.Prepare();
252      dataRowNames = null;
253      dataRows = null;
254      state = null;
255    }
[14788]256
[14518]257    protected override void Run(CancellationToken cancellationToken) {
[14742]258      var problemData = Problem.ProblemData;
[14807]259      // set up and initialized everything if necessary
[14859]260      if (state == null) {
261        if (SetSeedRandomly) Seed = new System.Random().Next();
[14807]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][];
[14859]266        for (var row = 0; row < dataset.Rows; row++)
[14807]267          data[row] = allowedInputVariables.Select(col => dataset.GetDoubleValue(col, row)).ToArray();
[14512]268
[14859]269        if (Normalization) data = NormalizeData(data);
[14788]270
[14807]271        state = TSNEStatic<double[]>.CreateState(data, Distance, random, NewDimensions, Perplexity, Theta,
272          StopLyingIteration, MomentumSwitchIteration, InitialMomentum, FinalMomentum, Eta);
[14788]273
[14807]274        SetUpResults(data);
275        iter = 0;
[14788]276      }
[14859]277      for (; iter < MaxIterations && !cancellationToken.IsCancellationRequested; iter++) {
278        if (iter % UpdateInterval == 0)
279          Analyze(state);
[14807]280        TSNEStatic<double[]>.Iterate(state);
281      }
[14859]282      Analyze(state);
[14788]283    }
284
285    private void SetUpResults(IReadOnlyCollection<double[]> data) {
[14859]286      if (Results == null) return;
[14788]287      var results = Results;
288      dataRowNames = new Dictionary<string, List<int>>();
289      dataRows = new Dictionary<string, ScatterPlotDataRow>();
290      var problemData = Problem.ProblemData;
291
[14785]292      //color datapoints acording to classes variable (be it double or string)
[14859]293      if (problemData.Dataset.VariableNames.Contains(Classes)) {
294        if ((problemData.Dataset as Dataset).VariableHasType<string>(Classes)) {
[14512]295          var classes = problemData.Dataset.GetStringValues(Classes).ToArray();
[14859]296          for (var i = 0; i < classes.Length; i++) {
297            if (!dataRowNames.ContainsKey(classes[i])) dataRowNames.Add(classes[i], new List<int>());
[14742]298            dataRowNames[classes[i]].Add(i);
[14512]299          }
[14859]300        } else if ((problemData.Dataset as Dataset).VariableHasType<double>(Classes)) {
[14512]301          var classValues = problemData.Dataset.GetDoubleValues(Classes).ToArray();
[14859]302          var max = classValues.Max() + 0.1;
[14512]303          var min = classValues.Min() - 0.1;
[14742]304          const int contours = 8;
[14859]305          for (var i = 0; i < contours; i++) {
[14742]306            var contourname = GetContourName(i, min, max, contours);
307            dataRowNames.Add(contourname, new List<int>());
[14788]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;
[14512]311          }
[14859]312          for (var i = 0; i < classValues.Length; i++) {
[14742]313            dataRowNames[GetContourName(classValues[i], min, max, contours)].Add(i);
[14512]314          }
315        }
316      } else {
[14518]317        dataRowNames.Add("Training", problemData.TrainingIndices.ToList());
318        dataRowNames.Add("Test", problemData.TestIndices.ToList());
[14512]319      }
320
[14859]321      if (!results.ContainsKey(IterationResultName)) results.Add(new Result(IterationResultName, new IntValue(0)));
[14788]322      else ((IntValue)results[IterationResultName].Value).Value = 0;
323
[14859]324      if (!results.ContainsKey(ErrorResultName)) results.Add(new Result(ErrorResultName, new DoubleValue(0)));
[14788]325      else ((DoubleValue)results[ErrorResultName].Value).Value = 0;
326
[14859]327      if (!results.ContainsKey(ErrorPlotResultName)) results.Add(new Result(ErrorPlotResultName, new DataTable(ErrorPlotResultName, "Development of errors during gradient descent")));
[14788]328      else results[ErrorPlotResultName].Value = new DataTable(ErrorPlotResultName, "Development of errors during gradient descent");
329
330      var plot = results[ErrorPlotResultName].Value as DataTable;
[14859]331      if (plot == null) throw new ArgumentException("could not create/access error data table in results collection");
[14788]332
[14859]333      if (!plot.Rows.ContainsKey("errors")) plot.Rows.Add(new DataRow("errors"));
[14788]334      plot.Rows["errors"].Values.Clear();
[14859]335      plot.Rows["errors"].VisualProperties.StartIndexZero = true;
[14788]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()));
[14414]339    }
340
[14807]341    private void Analyze(TSNEStatic<double[]>.TSNEState tsneState) {
[14859]342      if (Results == null) return;
[14788]343      var results = Results;
344      var plot = results[ErrorPlotResultName].Value as DataTable;
[14859]345      if (plot == null) throw new ArgumentException("Could not create/access error data table in results collection.");
[14788]346      var errors = plot.Rows["errors"].Values;
347      var c = tsneState.EvaluateError();
348      errors.Add(c);
[14807]349      ((IntValue)results[IterationResultName].Value).Value = tsneState.iter;
[14788]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) {
[14859]359      foreach (var rowName in dataRowNames.Keys) {
360        if (!plot.Rows.ContainsKey(rowName))
[14788]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)];
[14859]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++) {
[14788]373          var v = data[i, j];
374          max[j] = Math.Max(max[j], v);
375          min[j] = Math.Min(min[j], v);
376        }
[14859]377      for (var i = 0; i < data.GetLength(0); i++) {
378        for (var j = 0; j < data.GetLength(1); j++) {
[14788]379          res[i, j] = (data[i, j] - (max[j] + min[j]) / 2) / (max[j] - min[j]);
380        }
381      }
382      return res;
383    }
384
[14785]385    private static double[][] NormalizeData(IReadOnlyList<double[]> data) {
[14859]386      // as in tSNE implementation by van der Maaten
[14518]387      var n = data[0].Length;
388      var mean = new double[n];
[14859]389      var max = new double[n];
[14785]390      var nData = new double[data.Count][];
[14859]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]));
[14518]394      }
[14859]395      for (var i = 0; i < data.Count; i++) {
[14785]396        nData[i] = new double[n];
[14859]397        for (var j = 0; j < n; j++) nData[i][j] = (data[i][j] - mean[j]) / max[j];
[14518]398      }
399      return nData;
400    }
[14788]401
[14512]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    }
[14788]407
[14512]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    }
[14788]413
[14512]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    }
[14414]418  }
419}
Note: See TracBrowser for help on using the repository browser.