Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Weighted TSNE/3.4/TSNE/TSNEAlgorithm.cs @ 15484

Last change on this file since 15484 was 15484, checked in by bwerth, 5 years ago

#2850 changed data extraction

File size: 28.5 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.PluginInfrastructure;
35using HeuristicLab.Problems.DataAnalysis;
36using HeuristicLab.Random;
37
38namespace HeuristicLab.Algorithms.DataAnalysis {
39  /// <summary>
40  /// t-distributed stochastic neighbourhood embedding (tSNE) projects the data in a low dimensional
41  /// space to allow visual cluster identification.
42  /// </summary>
43  [Item("tSNE", "t-distributed stochastic neighbourhood embedding projects the data in a low " +
44                "dimensional space to allow visual cluster identification. Implemented similar to: https://lvdmaaten.github.io/tsne/#implementations (Barnes-Hut t-SNE). Described in : https://lvdmaaten.github.io/publications/papers/JMLR_2014.pdf")]
45  [Creatable(CreatableAttribute.Categories.DataAnalysis, Priority = 100)]
46  [StorableClass]
47  public sealed class TSNEAlgorithm : BasicAlgorithm {
48    public override bool SupportsPause {
49      get { return true; }
50    }
51    public override Type ProblemType {
52      get { return typeof(IDataAnalysisProblem); }
53    }
54    public new IDataAnalysisProblem Problem {
55      get { return (IDataAnalysisProblem) base.Problem; }
56      set { base.Problem = value; }
57    }
58
59    #region Parameter names
60    private const string DistanceFunctionParameterName = "DistanceFunction";
61    private const string PerplexityParameterName = "Perplexity";
62    private const string ThetaParameterName = "Theta";
63    private const string NewDimensionsParameterName = "Dimensions";
64    private const string MaxIterationsParameterName = "MaxIterations";
65    private const string StopLyingIterationParameterName = "StopLyingIteration";
66    private const string MomentumSwitchIterationParameterName = "MomentumSwitchIteration";
67    private const string InitialMomentumParameterName = "InitialMomentum";
68    private const string FinalMomentumParameterName = "FinalMomentum";
69    private const string EtaParameterName = "Eta";
70    private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
71    private const string SeedParameterName = "Seed";
72    private const string ClassesNameParameterName = "ClassesName";
73    private const string NormalizationParameterName = "Normalization";
74    private const string RandomInitializationParameterName = "RandomInitialization";
75    private const string UpdateIntervalParameterName = "UpdateInterval";
76    #endregion
77
78    #region Result names
79    private const string IterationResultName = "Iteration";
80    private const string ErrorResultName = "Error";
81    private const string ErrorPlotResultName = "Error plot";
82    private const string ScatterPlotResultName = "Scatterplot";
83    private const string DataResultName = "Projected data";
84    #endregion
85
86    #region Parameter properties
87    public IFixedValueParameter<DoubleValue> PerplexityParameter {
88      get { return (IFixedValueParameter<DoubleValue>) Parameters[PerplexityParameterName]; }
89    }
90    public IFixedValueParameter<PercentValue> ThetaParameter {
91      get { return (IFixedValueParameter<PercentValue>) Parameters[ThetaParameterName]; }
92    }
93    public IFixedValueParameter<IntValue> NewDimensionsParameter {
94      get { return (IFixedValueParameter<IntValue>) Parameters[NewDimensionsParameterName]; }
95    }
96    public IConstrainedValueParameter<IDistance<double[]>> DistanceFunctionParameter {
97      get { return (IConstrainedValueParameter<IDistance<double[]>>) Parameters[DistanceFunctionParameterName]; }
98    }
99    public IFixedValueParameter<IntValue> MaxIterationsParameter {
100      get { return (IFixedValueParameter<IntValue>) Parameters[MaxIterationsParameterName]; }
101    }
102    public IFixedValueParameter<IntValue> StopLyingIterationParameter {
103      get { return (IFixedValueParameter<IntValue>) Parameters[StopLyingIterationParameterName]; }
104    }
105    public IFixedValueParameter<IntValue> MomentumSwitchIterationParameter {
106      get { return (IFixedValueParameter<IntValue>) Parameters[MomentumSwitchIterationParameterName]; }
107    }
108    public IFixedValueParameter<DoubleValue> InitialMomentumParameter {
109      get { return (IFixedValueParameter<DoubleValue>) Parameters[InitialMomentumParameterName]; }
110    }
111    public IFixedValueParameter<DoubleValue> FinalMomentumParameter {
112      get { return (IFixedValueParameter<DoubleValue>) Parameters[FinalMomentumParameterName]; }
113    }
114    public IFixedValueParameter<DoubleValue> EtaParameter {
115      get { return (IFixedValueParameter<DoubleValue>) Parameters[EtaParameterName]; }
116    }
117    public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
118      get { return (IFixedValueParameter<BoolValue>) Parameters[SetSeedRandomlyParameterName]; }
119    }
120    public IFixedValueParameter<IntValue> SeedParameter {
121      get { return (IFixedValueParameter<IntValue>) Parameters[SeedParameterName]; }
122    }
123    public IConstrainedValueParameter<StringValue> ClassesNameParameter {
124      get { return (IConstrainedValueParameter<StringValue>) Parameters[ClassesNameParameterName]; }
125    }
126    public IFixedValueParameter<BoolValue> NormalizationParameter {
127      get { return (IFixedValueParameter<BoolValue>) Parameters[NormalizationParameterName]; }
128    }
129    public IFixedValueParameter<BoolValue> RandomInitializationParameter {
130      get { return (IFixedValueParameter<BoolValue>) Parameters[RandomInitializationParameterName]; }
131    }
132    public IFixedValueParameter<IntValue> UpdateIntervalParameter {
133      get { return (IFixedValueParameter<IntValue>) Parameters[UpdateIntervalParameterName]; }
134    }
135    #endregion
136
137    #region  Properties
138    public IDistance<double[]> DistanceFunction {
139      get { return DistanceFunctionParameter.Value; }
140    }
141    public double Perplexity {
142      get { return PerplexityParameter.Value.Value; }
143      set { PerplexityParameter.Value.Value = value; }
144    }
145    public double Theta {
146      get { return ThetaParameter.Value.Value; }
147      set { ThetaParameter.Value.Value = value; }
148    }
149    public int NewDimensions {
150      get { return NewDimensionsParameter.Value.Value; }
151      set { NewDimensionsParameter.Value.Value = value; }
152    }
153    public int MaxIterations {
154      get { return MaxIterationsParameter.Value.Value; }
155      set { MaxIterationsParameter.Value.Value = value; }
156    }
157    public int StopLyingIteration {
158      get { return StopLyingIterationParameter.Value.Value; }
159      set { StopLyingIterationParameter.Value.Value = value; }
160    }
161    public int MomentumSwitchIteration {
162      get { return MomentumSwitchIterationParameter.Value.Value; }
163      set { MomentumSwitchIterationParameter.Value.Value = value; }
164    }
165    public double InitialMomentum {
166      get { return InitialMomentumParameter.Value.Value; }
167      set { InitialMomentumParameter.Value.Value = value; }
168    }
169    public double FinalMomentum {
170      get { return FinalMomentumParameter.Value.Value; }
171      set { FinalMomentumParameter.Value.Value = value; }
172    }
173    public double Eta {
174      get { return EtaParameter.Value.Value; }
175      set { EtaParameter.Value.Value = value; }
176    }
177    public bool SetSeedRandomly {
178      get { return SetSeedRandomlyParameter.Value.Value; }
179      set { SetSeedRandomlyParameter.Value.Value = value; }
180    }
181    public int Seed {
182      get { return SeedParameter.Value.Value; }
183      set { SeedParameter.Value.Value = value; }
184    }
185    public string ClassesName {
186      get { return ClassesNameParameter.Value != null ? ClassesNameParameter.Value.Value : null; }
187      set { ClassesNameParameter.Value.Value = value; }
188    }
189    public bool Normalization {
190      get { return NormalizationParameter.Value.Value; }
191      set { NormalizationParameter.Value.Value = value; }
192    }
193    public bool RandomInitialization {
194      get { return RandomInitializationParameter.Value.Value; }
195      set { RandomInitializationParameter.Value.Value = value; }
196    }
197
198    public int UpdateInterval {
199      get { return UpdateIntervalParameter.Value.Value; }
200      set { UpdateIntervalParameter.Value.Value = value; }
201    }
202    #endregion
203
204    #region Storable poperties
205    [Storable]
206    private Dictionary<string, List<int>> dataRowNames;
207    [Storable]
208    private Dictionary<string, ScatterPlotDataRow> dataRows;
209    [Storable]
210    private TSNEStatic<double[]>.TSNEState state;
211    [Storable]
212    private int iter;
213    #endregion
214
215    #region Constructors & Cloning
216    [StorableConstructor]
217    private TSNEAlgorithm(bool deserializing) : base(deserializing) { }
218
219    [StorableHook(HookType.AfterDeserialization)]
220    private void AfterDeserialization() {
221      RegisterParameterEvents();
222    }
223    private TSNEAlgorithm(TSNEAlgorithm original, Cloner cloner) : base(original, cloner) {
224      if (original.dataRowNames != null)
225        dataRowNames = new Dictionary<string, List<int>>(original.dataRowNames);
226      if (original.dataRows != null)
227        dataRows = original.dataRows.ToDictionary(kvp => kvp.Key, kvp => cloner.Clone(kvp.Value));
228      if (original.state != null)
229        state = cloner.Clone(original.state);
230      iter = original.iter;
231    }
232    public override IDeepCloneable Clone(Cloner cloner) {
233      return new TSNEAlgorithm(this, cloner);
234    }
235    public TSNEAlgorithm() {
236      var distances = new ItemSet<IDistance<double[]>>(ApplicationManager.Manager.GetInstances<IDistance<double[]>>());
237      Parameters.Add(new ConstrainedValueParameter<IDistance<double[]>>(DistanceFunctionParameterName, "The distance function used to differentiate similar from non-similar points", distances, distances.OfType<EuclideanDistance>().FirstOrDefault()));
238      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)));
239      Parameters.Add(new FixedValueParameter<PercentValue>(ThetaParameterName, "Value describing how much appoximated " +
240                                                                               "gradients my differ from exact gradients. Set to 0 for exact calculation and in [0,1] otherwise. " +
241                                                                               "Appropriate values for theta are between 0.1 and 0.7 (default = 0.5). CAUTION: exact calculation of " +
242                                                                               "forces requires building a non-sparse N*N matrix where N is the number of data points. This may " +
243                                                                               "exceed memory limitations. The function is designed to run on large (N > 5000) data sets. It may give" +
244                                                                               " poor performance on very small data sets(it is better to use a standard t - SNE implementation on such data).", new PercentValue(0)));
245      Parameters.Add(new FixedValueParameter<IntValue>(NewDimensionsParameterName, "Dimensionality of projected space (usually 2 for easy visual analysis)", new IntValue(2)));
246      Parameters.Add(new FixedValueParameter<IntValue>(MaxIterationsParameterName, "Maximum number of iterations for gradient descent.", new IntValue(1000)));
247      Parameters.Add(new FixedValueParameter<IntValue>(StopLyingIterationParameterName, "Number of iterations after which p is no longer approximated.", new IntValue(0)));
248      Parameters.Add(new FixedValueParameter<IntValue>(MomentumSwitchIterationParameterName, "Number of iterations after which the momentum in the gradient descent is switched.", new IntValue(0)));
249      Parameters.Add(new FixedValueParameter<DoubleValue>(InitialMomentumParameterName, "The initial momentum in the gradient descent.", new DoubleValue(0.5)));
250      Parameters.Add(new FixedValueParameter<DoubleValue>(FinalMomentumParameterName, "The final momentum.", new DoubleValue(0.8)));
251      Parameters.Add(new FixedValueParameter<DoubleValue>(EtaParameterName, "Gradient descent learning rate.", new DoubleValue(10)));
252      Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "If the seed should be random.", new BoolValue(true)));
253      Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The seed used if it should not be random.", new IntValue(0)));
254      Parameters.Add(new OptionalConstrainedValueParameter<StringValue>(ClassesNameParameterName, "Name of the column specifying the class lables of each data point. If this is not set training/test is used as labels."));
255      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)));
256      Parameters.Add(new FixedValueParameter<IntValue>(UpdateIntervalParameterName, "The interval after which the results will be updated.", new IntValue(50)));
257      Parameters.Add(new FixedValueParameter<BoolValue>(RandomInitializationParameterName, "Wether data points should be randomly initialized or according to the first 2 dimensions", new BoolValue(true)));
258
259      Parameters[UpdateIntervalParameterName].Hidden = true;
260
261      MomentumSwitchIterationParameter.Hidden = true;
262      InitialMomentumParameter.Hidden = true;
263      FinalMomentumParameter.Hidden = true;
264      StopLyingIterationParameter.Hidden = true;
265      EtaParameter.Hidden = false;
266      Problem = new RegressionProblem();
267      RegisterParameterEvents();
268    }
269    #endregion
270
271    public override void Prepare() {
272      base.Prepare();
273      dataRowNames = null;
274      dataRows = null;
275      state = null;
276    }
277
278    protected override void Run(CancellationToken cancellationToken) {
279      var problemData = Problem.ProblemData;
280      // set up and initialize everything if necessary
281      if (state == null) {
282        if (SetSeedRandomly) Seed = new System.Random().Next();
283        var random = new MersenneTwister((uint) Seed);
284        var dataset = problemData.Dataset;
285        var allowedInputVariables = problemData.AllowedInputVariables.ToArray();
286        var allindices = Problem.ProblemData.AllIndices.ToArray();
287        var data = Enumerable.Range(0, dataset.Rows).Select(x => new double[allowedInputVariables.Length]).ToArray();
288        var col = 0;
289        foreach (var s in allowedInputVariables) {
290          var row = 0;
291          foreach (var d in dataset.GetDoubleValues(s)) {
292            data[row][col] = d;
293            row++;
294          }
295          col++;
296        }
297
298        //data = allindices.Select(row => allowedInputVariables.Select(col => dataset.GetDoubleValue(col, row)).ToArray()).ToArray();
299        if (Normalization) data = NormalizeInputData(data);
300        state = TSNEStatic<double[]>.CreateState(data, DistanceFunction, random, NewDimensions, Perplexity, Theta, StopLyingIteration, MomentumSwitchIteration, InitialMomentum, FinalMomentum, Eta, RandomInitialization);
301        SetUpResults(allindices);
302        iter = 0;
303      }
304      for (; iter < MaxIterations && !cancellationToken.IsCancellationRequested; iter++) {
305        if (iter % UpdateInterval == 0) Analyze(state);
306        TSNEStatic<double[]>.Iterate(state);
307      }
308      Analyze(state);
309    }
310
311    #region Events
312    protected override void OnProblemChanged() {
313      base.OnProblemChanged();
314      if (Problem == null) return;
315      OnProblemDataChanged(this, null);
316    }
317
318    protected override void RegisterProblemEvents() {
319      base.RegisterProblemEvents();
320      Problem.ProblemDataChanged += OnProblemDataChanged;
321    }
322
323    protected override void DeregisterProblemEvents() {
324      base.DeregisterProblemEvents();
325      Problem.ProblemDataChanged -= OnProblemDataChanged;
326    }
327
328    protected override void OnStopped() {
329      base.OnStopped();
330      state = null;
331      dataRowNames = null;
332      dataRows = null;
333    }
334
335    private void OnProblemDataChanged(object sender, EventArgs args) {
336      if (Problem == null || Problem.ProblemData == null) return;
337      OnPerplexityChanged(this, null);
338      Problem.ProblemData.Changed += OnPerplexityChanged;
339      Problem.ProblemData.Changed += OnColumnsChanged;
340      Problem.ProblemData.Dataset.RowsChanged += OnPerplexityChanged;
341      Problem.ProblemData.Dataset.ColumnsChanged += OnColumnsChanged;
342      if (!Parameters.ContainsKey(ClassesNameParameterName)) return;
343      ClassesNameParameter.ValidValues.Clear();
344      foreach (var input in Problem.ProblemData.InputVariables) ClassesNameParameter.ValidValues.Add(input);
345    }
346
347    private void OnColumnsChanged(object sender, EventArgs e) {
348      if (Problem == null || Problem.ProblemData == null || Problem.ProblemData.Dataset == null || !Parameters.ContainsKey(DistanceFunctionParameterName)) return;
349      DistanceFunctionParameter.ValidValues.OfType<WeightedEuclideanDistance>().Single().Weights = new DoubleArray(Problem.ProblemData.AllowedInputVariables.Select(x => 1.0).ToArray());
350    }
351
352    private void RegisterParameterEvents() {
353      PerplexityParameter.Value.ValueChanged -= OnPerplexityChanged;
354      PerplexityParameter.Value.ValueChanged += OnPerplexityChanged;
355    }
356
357    private void OnPerplexityChanged(object sender, EventArgs e) {
358      if (Problem == null || Problem.ProblemData == null || Problem.ProblemData.Dataset == null || !Parameters.ContainsKey(PerplexityParameterName)) return;
359      PerplexityParameter.Value.ValueChanged -= OnPerplexityChanged;
360      PerplexityParameter.Value.Value = Math.Max(1, Math.Min((Problem.ProblemData.Dataset.Rows - 1) / 3.0, Perplexity));
361      PerplexityParameter.Value.ValueChanged += OnPerplexityChanged;
362    }
363    #endregion
364
365    #region Helpers
366    private void SetUpResults(IReadOnlyList<int> allIndices) {
367      if (Results == null) return;
368      var results = Results;
369      dataRowNames = new Dictionary<string, List<int>>();
370      dataRows = new Dictionary<string, ScatterPlotDataRow>();
371      var problemData = Problem.ProblemData;
372
373      if (!results.ContainsKey(IterationResultName)) results.Add(new Result(IterationResultName, new IntValue(0)));
374      if (!results.ContainsKey(ErrorResultName)) results.Add(new Result(ErrorResultName, new DoubleValue(0)));
375      if (!results.ContainsKey(ScatterPlotResultName)) results.Add(new Result(ScatterPlotResultName, "Plot of the projected data", new ScatterPlot(DataResultName, "")));
376      if (!results.ContainsKey(DataResultName)) results.Add(new Result(DataResultName, "Projected Data", new DoubleMatrix()));
377      if (!results.ContainsKey(ErrorPlotResultName)) {
378        var errortable = new DataTable(ErrorPlotResultName, "Development of errors during gradient descent") {
379          VisualProperties = {
380            XAxisTitle = "UpdateIntervall",
381            YAxisTitle = "Error",
382            YAxisLogScale = true
383          }
384        };
385        errortable.Rows.Add(new DataRow("Errors"));
386        errortable.Rows["Errors"].VisualProperties.StartIndexZero = true;
387        results.Add(new Result(ErrorPlotResultName, errortable));
388      }
389
390      //color datapoints acording to classes variable (be it double or string)
391      if (!problemData.Dataset.VariableNames.Contains(ClassesName)) {
392        dataRowNames.Add("Training", problemData.TrainingIndices.ToList());
393        dataRowNames.Add("Test", problemData.TestIndices.ToList());
394        return;
395      }
396      var classificationData = problemData as ClassificationProblemData;
397      if (classificationData != null && classificationData.TargetVariable.Equals(ClassesName)) {
398        var classNames = classificationData.ClassValues.Zip(classificationData.ClassNames, (v, n) => new {v, n}).ToDictionary(x => x.v, x => x.n);
399        var classes = classificationData.Dataset.GetDoubleValues(classificationData.TargetVariable, allIndices).Select(v => classNames[v]).ToArray();
400        for (var i = 0; i < classes.Length; i++) {
401          if (!dataRowNames.ContainsKey(classes[i])) dataRowNames.Add(classes[i], new List<int>());
402          dataRowNames[classes[i]].Add(i);
403        }
404      }
405      else if (((Dataset) problemData.Dataset).VariableHasType<string>(ClassesName)) {
406        var classes = problemData.Dataset.GetStringValues(ClassesName, allIndices).ToArray();
407        for (var i = 0; i < classes.Length; i++) {
408          if (!dataRowNames.ContainsKey(classes[i])) dataRowNames.Add(classes[i], new List<int>());
409          dataRowNames[classes[i]].Add(i);
410        }
411      }
412      else if (((Dataset) problemData.Dataset).VariableHasType<double>(ClassesName)) {
413        var clusterdata = new Dataset(problemData.Dataset.DoubleVariables, problemData.Dataset.DoubleVariables.Select(v => problemData.Dataset.GetDoubleValues(v, allIndices).ToList()));
414        const int contours = 8;
415        Dictionary<int, string> contourMap;
416        IClusteringModel clusterModel;
417        double[][] borders;
418        CreateClusters(clusterdata, ClassesName, contours, out clusterModel, out contourMap, out borders);
419        var contourorder = borders.Select((x, i) => new {x, i}).OrderBy(x => x.x[0]).Select(x => x.i).ToArray();
420        for (var i = 0; i < contours; i++) {
421          var c = contourorder[i];
422          var contourname = contourMap[c];
423          dataRowNames.Add(contourname, new List<int>());
424          dataRows.Add(contourname, new ScatterPlotDataRow(contourname, "", new List<Point2D<double>>()));
425          dataRows[contourname].VisualProperties.Color = GetHeatMapColor(i, contours);
426        }
427        var allClusters = clusterModel.GetClusterValues(clusterdata, Enumerable.Range(0, clusterdata.Rows)).ToArray();
428        for (var i = 0; i < clusterdata.Rows; i++) dataRowNames[contourMap[allClusters[i] - 1]].Add(i);
429      }
430      else if (((Dataset) problemData.Dataset).VariableHasType<DateTime>(ClassesName)) {
431        var clusterdata = new Dataset(problemData.Dataset.DateTimeVariables, problemData.Dataset.DateTimeVariables.Select(v => problemData.Dataset.GetDoubleValues(v, allIndices).ToList()));
432        const int contours = 8;
433        Dictionary<int, string> contourMap;
434        IClusteringModel clusterModel;
435        double[][] borders;
436        CreateClusters(clusterdata, ClassesName, contours, out clusterModel, out contourMap, out borders);
437        var contourorder = borders.Select((x, i) => new {x, i}).OrderBy(x => x.x[0]).Select(x => x.i).ToArray();
438        for (var i = 0; i < contours; i++) {
439          var c = contourorder[i];
440          var contourname = contourMap[c];
441          dataRowNames.Add(contourname, new List<int>());
442          dataRows.Add(contourname, new ScatterPlotDataRow(contourname, "", new List<Point2D<double>>()));
443          dataRows[contourname].VisualProperties.Color = GetHeatMapColor(i, contours);
444        }
445        var allClusters = clusterModel.GetClusterValues(clusterdata, Enumerable.Range(0, clusterdata.Rows)).ToArray();
446        for (var i = 0; i < clusterdata.Rows; i++) dataRowNames[contourMap[allClusters[i] - 1]].Add(i);
447      }
448      else {
449        dataRowNames.Add("Training", problemData.TrainingIndices.ToList());
450        dataRowNames.Add("Test", problemData.TestIndices.ToList());
451      }
452    }
453
454    private void Analyze(TSNEStatic<double[]>.TSNEState tsneState) {
455      if (Results == null) return;
456      var results = Results;
457      var plot = results[ErrorPlotResultName].Value as DataTable;
458      if (plot == null) throw new ArgumentException("Could not create/access error data table in results collection.");
459      var errors = plot.Rows["Errors"].Values;
460      var c = tsneState.EvaluateError();
461      errors.Add(c);
462      ((IntValue) results[IterationResultName].Value).Value = tsneState.iter;
463      ((DoubleValue) results[ErrorResultName].Value).Value = errors.Last();
464
465      var ndata = NormalizeProjectedData(tsneState.newData);
466      results[DataResultName].Value = new DoubleMatrix(ndata);
467      var splot = results[ScatterPlotResultName].Value as ScatterPlot;
468      FillScatterPlot(ndata, splot);
469    }
470
471    private void FillScatterPlot(double[,] lowDimData, ScatterPlot plot) {
472      foreach (var rowName in dataRowNames.Keys) {
473        if (!plot.Rows.ContainsKey(rowName)) {
474          plot.Rows.Add(dataRows.ContainsKey(rowName) ? dataRows[rowName] : new ScatterPlotDataRow(rowName, "", new List<Point2D<double>>()));
475          plot.Rows[rowName].VisualProperties.PointSize = 8;
476        }
477        plot.Rows[rowName].Points.Replace(dataRowNames[rowName].Select(i => new Point2D<double>(lowDimData[i, 0], lowDimData[i, 1])));
478      }
479    }
480
481    private static double[,] NormalizeProjectedData(double[,] data) {
482      var max = new double[data.GetLength(1)];
483      var min = new double[data.GetLength(1)];
484      var res = new double[data.GetLength(0), data.GetLength(1)];
485      for (var i = 0; i < max.Length; i++) max[i] = min[i] = data[0, i];
486      for (var i = 0; i < data.GetLength(0); i++)
487      for (var j = 0; j < data.GetLength(1); j++) {
488        var v = data[i, j];
489        max[j] = Math.Max(max[j], v);
490        min[j] = Math.Min(min[j], v);
491      }
492      for (var i = 0; i < data.GetLength(0); i++) {
493        for (var j = 0; j < data.GetLength(1); j++) {
494          var d = max[j] - min[j];
495          var s = data[i, j] - (max[j] + min[j]) / 2; //shift data
496          if (d.IsAlmost(0)) res[i, j] = data[i, j]; //no scaling possible
497          else res[i, j] = s / d; //scale data
498        }
499      }
500      return res;
501    }
502
503    private static double[][] NormalizeInputData(IReadOnlyList<IReadOnlyList<double>> data) {
504      // as in tSNE implementation by van der Maaten
505      var n = data[0].Count;
506      var mean = new double[n];
507      var max = new double[n];
508      var nData = new double[data.Count][];
509      for (var i = 0; i < n; i++) {
510        mean[i] = Enumerable.Range(0, data.Count).Select(x => data[x][i]).Average();
511        max[i] = Enumerable.Range(0, data.Count).Max(x => Math.Abs(data[x][i]));
512      }
513      for (var i = 0; i < data.Count; i++) {
514        nData[i] = new double[n];
515        for (var j = 0; j < n; j++) nData[i][j] = max[j].IsAlmost(0) ? data[i][j] - mean[j] : (data[i][j] - mean[j]) / max[j];
516      }
517      return nData;
518    }
519
520    private static Color GetHeatMapColor(int contourNr, int noContours) {
521      return ConvertTotalToRgb(0, noContours, contourNr);
522    }
523
524    private static void CreateClusters(IDataset data, string target, int contours, out IClusteringModel contourCluster, out Dictionary<int, string> contourNames, out double[][] borders) {
525      var cpd = new ClusteringProblemData((Dataset) data, new[] {target});
526      contourCluster = KMeansClustering.CreateKMeansSolution(cpd, contours, 3).Model;
527
528      borders = Enumerable.Range(0, contours).Select(x => new[] {double.MaxValue, double.MinValue}).ToArray();
529      var clusters = contourCluster.GetClusterValues(cpd.Dataset, cpd.AllIndices).ToArray();
530      var targetvalues = cpd.Dataset.GetDoubleValues(target).ToArray();
531      foreach (var i in cpd.AllIndices) {
532        var cl = clusters[i] - 1;
533        var clv = targetvalues[i];
534        if (borders[cl][0] > clv) borders[cl][0] = clv;
535        if (borders[cl][1] < clv) borders[cl][1] = clv;
536      }
537
538      contourNames = new Dictionary<int, string>();
539      for (var i = 0; i < contours; i++)
540        contourNames.Add(i, "[" + borders[i][0] + ";" + borders[i][1] + "]");
541    }
542
543    private static Color ConvertTotalToRgb(double low, double high, double cell) {
544      var colorGradient = ColorGradient.Colors;
545      var range = high - low;
546      var h = cell / range * colorGradient.Count;
547      return colorGradient[(int) h];
548    }
549    #endregion
550  }
551}
Note: See TracBrowser for help on using the repository browser.