Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2850 worked on weighted tSNE

File size: 28.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.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 = allindices.Select(row => allowedInputVariables.Select(col => dataset.GetDoubleValue(col, row)).ToArray()).ToArray();
288        if (Normalization) data = NormalizeInputData(data);
289        state = TSNEStatic<double[]>.CreateState(data, DistanceFunction, random, NewDimensions, Perplexity, Theta, StopLyingIteration, MomentumSwitchIteration, InitialMomentum, FinalMomentum, Eta, RandomInitialization);
290        SetUpResults(allindices);
291        iter = 0;
292      }
293      for (; iter < MaxIterations && !cancellationToken.IsCancellationRequested; iter++) {
294        if (iter % UpdateInterval == 0) Analyze(state);
295        TSNEStatic<double[]>.Iterate(state);
296      }
297      Analyze(state);
298    }
299
300    #region Events
301    protected override void OnProblemChanged() {
302      base.OnProblemChanged();
303      if (Problem == null) return;
304      OnProblemDataChanged(this, null);
305    }
306
307    protected override void RegisterProblemEvents() {
308      base.RegisterProblemEvents();
309      Problem.ProblemDataChanged += OnProblemDataChanged;
310    }
311
312    protected override void DeregisterProblemEvents() {
313      base.DeregisterProblemEvents();
314      Problem.ProblemDataChanged -= OnProblemDataChanged;
315    }
316
317    protected override void OnStopped() {
318      base.OnStopped();
319      state = null;
320      dataRowNames = null;
321      dataRows = null;
322    }
323
324    private void OnProblemDataChanged(object sender, EventArgs args) {
325      if (Problem == null || Problem.ProblemData == null) return;
326      OnPerplexityChanged(this, null);
327      Problem.ProblemData.Changed += OnPerplexityChanged;
328      Problem.ProblemData.Changed += OnColumnsChanged;
329      Problem.ProblemData.Dataset.RowsChanged += OnPerplexityChanged;
330      Problem.ProblemData.Dataset.ColumnsChanged += OnColumnsChanged;
331      if (!Parameters.ContainsKey(ClassesNameParameterName)) return;
332      ClassesNameParameter.ValidValues.Clear();
333      foreach (var input in Problem.ProblemData.InputVariables) ClassesNameParameter.ValidValues.Add(input);
334    }
335    private void OnColumnsChanged(object sender, EventArgs e) {
336      if (Problem == null || Problem.ProblemData == null || Problem.ProblemData.Dataset == null || !Parameters.ContainsKey(DistanceFunctionParameterName)) return;
337      DistanceFunctionParameter.ValidValues.OfType<WeightedEuclideanDistance>().Single().Weights = new DoubleArray(Problem.ProblemData.AllowedInputVariables.Select(x => 1.0).ToArray());
338    }
339
340    private void RegisterParameterEvents() {
341      PerplexityParameter.Value.ValueChanged -= OnPerplexityChanged;
342      PerplexityParameter.Value.ValueChanged += OnPerplexityChanged;
343    }
344
345    private void OnPerplexityChanged(object sender, EventArgs e) {
346      if (Problem == null || Problem.ProblemData == null || Problem.ProblemData.Dataset == null || !Parameters.ContainsKey(PerplexityParameterName)) return;
347      PerplexityParameter.Value.ValueChanged -= OnPerplexityChanged;
348      PerplexityParameter.Value.Value = Math.Max(1, Math.Min((Problem.ProblemData.Dataset.Rows - 1) / 3.0, Perplexity));
349      PerplexityParameter.Value.ValueChanged += OnPerplexityChanged;
350    }
351    #endregion
352
353    #region Helpers
354    private void SetUpResults(IReadOnlyList<int> allIndices) {
355      if (Results == null) return;
356      var results = Results;
357      dataRowNames = new Dictionary<string, List<int>>();
358      dataRows = new Dictionary<string, ScatterPlotDataRow>();
359      var problemData = Problem.ProblemData;
360
361      if (!results.ContainsKey(IterationResultName)) results.Add(new Result(IterationResultName, new IntValue(0)));
362      if (!results.ContainsKey(ErrorResultName)) results.Add(new Result(ErrorResultName, new DoubleValue(0)));
363      if (!results.ContainsKey(ScatterPlotResultName)) results.Add(new Result(ScatterPlotResultName, "Plot of the projected data", new ScatterPlot(DataResultName, "")));
364      if (!results.ContainsKey(DataResultName)) results.Add(new Result(DataResultName, "Projected Data", new DoubleMatrix()));
365      if (!results.ContainsKey(ErrorPlotResultName)) {
366        var errortable = new DataTable(ErrorPlotResultName, "Development of errors during gradient descent") {
367          VisualProperties = {
368            XAxisTitle = "UpdateIntervall",
369            YAxisTitle = "Error",
370            YAxisLogScale = true
371          }
372        };
373        errortable.Rows.Add(new DataRow("Errors"));
374        errortable.Rows["Errors"].VisualProperties.StartIndexZero = true;
375        results.Add(new Result(ErrorPlotResultName, errortable));
376      }
377
378      //color datapoints acording to classes variable (be it double or string)
379      if (!problemData.Dataset.VariableNames.Contains(ClassesName)) {
380        dataRowNames.Add("Training", problemData.TrainingIndices.ToList());
381        dataRowNames.Add("Test", problemData.TestIndices.ToList());
382        return;
383      }
384      var classificationData = problemData as ClassificationProblemData;
385      if (classificationData != null && classificationData.TargetVariable.Equals(ClassesName)) {
386        var classNames = classificationData.ClassValues.Zip(classificationData.ClassNames, (v, n) => new {v, n}).ToDictionary(x => x.v, x => x.n);
387        var classes = classificationData.Dataset.GetDoubleValues(classificationData.TargetVariable, allIndices).Select(v => classNames[v]).ToArray();
388        for (var i = 0; i < classes.Length; i++) {
389          if (!dataRowNames.ContainsKey(classes[i])) dataRowNames.Add(classes[i], new List<int>());
390          dataRowNames[classes[i]].Add(i);
391        }
392      }
393      else if (((Dataset) problemData.Dataset).VariableHasType<string>(ClassesName)) {
394        var classes = problemData.Dataset.GetStringValues(ClassesName, allIndices).ToArray();
395        for (var i = 0; i < classes.Length; i++) {
396          if (!dataRowNames.ContainsKey(classes[i])) dataRowNames.Add(classes[i], new List<int>());
397          dataRowNames[classes[i]].Add(i);
398        }
399      }
400      else if (((Dataset) problemData.Dataset).VariableHasType<double>(ClassesName)) {
401        var clusterdata = new Dataset(problemData.Dataset.DoubleVariables, problemData.Dataset.DoubleVariables.Select(v => problemData.Dataset.GetDoubleValues(v, allIndices).ToList()));
402        const int contours = 8;
403        Dictionary<int, string> contourMap;
404        IClusteringModel clusterModel;
405        double[][] borders;
406        CreateClusters(clusterdata, ClassesName, contours, out clusterModel, out contourMap, out borders);
407        var contourorder = borders.Select((x, i) => new {x, i}).OrderBy(x => x.x[0]).Select(x => x.i).ToArray();
408        for (var i = 0; i < contours; i++) {
409          var c = contourorder[i];
410          var contourname = contourMap[c];
411          dataRowNames.Add(contourname, new List<int>());
412          dataRows.Add(contourname, new ScatterPlotDataRow(contourname, "", new List<Point2D<double>>()));
413          dataRows[contourname].VisualProperties.Color = GetHeatMapColor(i, contours);
414        }
415        var allClusters = clusterModel.GetClusterValues(clusterdata, Enumerable.Range(0, clusterdata.Rows)).ToArray();
416        for (var i = 0; i < clusterdata.Rows; i++) dataRowNames[contourMap[allClusters[i] - 1]].Add(i);
417      }
418      else if (((Dataset) problemData.Dataset).VariableHasType<DateTime>(ClassesName)) {
419        var clusterdata = new Dataset(problemData.Dataset.DateTimeVariables, problemData.Dataset.DateTimeVariables.Select(v => problemData.Dataset.GetDoubleValues(v, allIndices).ToList()));
420        const int contours = 8;
421        Dictionary<int, string> contourMap;
422        IClusteringModel clusterModel;
423        double[][] borders;
424        CreateClusters(clusterdata, ClassesName, contours, out clusterModel, out contourMap, out borders);
425        var contourorder = borders.Select((x, i) => new {x, i}).OrderBy(x => x.x[0]).Select(x => x.i).ToArray();
426        for (var i = 0; i < contours; i++) {
427          var c = contourorder[i];
428          var contourname = contourMap[c];
429          dataRowNames.Add(contourname, new List<int>());
430          dataRows.Add(contourname, new ScatterPlotDataRow(contourname, "", new List<Point2D<double>>()));
431          dataRows[contourname].VisualProperties.Color = GetHeatMapColor(i, contours);
432        }
433        var allClusters = clusterModel.GetClusterValues(clusterdata, Enumerable.Range(0, clusterdata.Rows)).ToArray();
434        for (var i = 0; i < clusterdata.Rows; i++) dataRowNames[contourMap[allClusters[i] - 1]].Add(i);
435      }
436      else {
437        dataRowNames.Add("Training", problemData.TrainingIndices.ToList());
438        dataRowNames.Add("Test", problemData.TestIndices.ToList());
439      }
440    }
441
442    private void Analyze(TSNEStatic<double[]>.TSNEState tsneState) {
443      if (Results == null) return;
444      var results = Results;
445      var plot = results[ErrorPlotResultName].Value as DataTable;
446      if (plot == null) throw new ArgumentException("Could not create/access error data table in results collection.");
447      var errors = plot.Rows["Errors"].Values;
448      var c = tsneState.EvaluateError();
449      errors.Add(c);
450      ((IntValue) results[IterationResultName].Value).Value = tsneState.iter;
451      ((DoubleValue) results[ErrorResultName].Value).Value = errors.Last();
452
453      var ndata = NormalizeProjectedData(tsneState.newData);
454      results[DataResultName].Value = new DoubleMatrix(ndata);
455      var splot = results[ScatterPlotResultName].Value as ScatterPlot;
456      FillScatterPlot(ndata, splot);
457    }
458
459    private void FillScatterPlot(double[,] lowDimData, ScatterPlot plot) {
460      foreach (var rowName in dataRowNames.Keys) {
461        if (!plot.Rows.ContainsKey(rowName)) {
462          plot.Rows.Add(dataRows.ContainsKey(rowName) ? dataRows[rowName] : new ScatterPlotDataRow(rowName, "", new List<Point2D<double>>()));
463          plot.Rows[rowName].VisualProperties.PointSize = 8;
464        }
465        plot.Rows[rowName].Points.Replace(dataRowNames[rowName].Select(i => new Point2D<double>(lowDimData[i, 0], lowDimData[i, 1])));
466      }
467    }
468
469    private static double[,] NormalizeProjectedData(double[,] data) {
470      var max = new double[data.GetLength(1)];
471      var min = new double[data.GetLength(1)];
472      var res = new double[data.GetLength(0), data.GetLength(1)];
473      for (var i = 0; i < max.Length; i++) max[i] = min[i] = data[0, i];
474      for (var i = 0; i < data.GetLength(0); i++)
475      for (var j = 0; j < data.GetLength(1); j++) {
476        var v = data[i, j];
477        max[j] = Math.Max(max[j], v);
478        min[j] = Math.Min(min[j], v);
479      }
480      for (var i = 0; i < data.GetLength(0); i++) {
481        for (var j = 0; j < data.GetLength(1); j++) {
482          var d = max[j] - min[j];
483          var s = data[i, j] - (max[j] + min[j]) / 2; //shift data
484          if (d.IsAlmost(0)) res[i, j] = data[i, j]; //no scaling possible
485          else res[i, j] = s / d; //scale data
486        }
487      }
488      return res;
489    }
490
491    private static double[][] NormalizeInputData(IReadOnlyList<IReadOnlyList<double>> data) {
492      // as in tSNE implementation by van der Maaten
493      var n = data[0].Count;
494      var mean = new double[n];
495      var max = new double[n];
496      var nData = new double[data.Count][];
497      for (var i = 0; i < n; i++) {
498        mean[i] = Enumerable.Range(0, data.Count).Select(x => data[x][i]).Average();
499        max[i] = Enumerable.Range(0, data.Count).Max(x => Math.Abs(data[x][i]));
500      }
501      for (var i = 0; i < data.Count; i++) {
502        nData[i] = new double[n];
503        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];
504      }
505      return nData;
506    }
507
508    private static Color GetHeatMapColor(int contourNr, int noContours) {
509      return ConvertTotalToRgb(0, noContours, contourNr);
510    }
511
512    private static void CreateClusters(IDataset data, string target, int contours, out IClusteringModel contourCluster, out Dictionary<int, string> contourNames, out double[][] borders) {
513      var cpd = new ClusteringProblemData((Dataset) data, new[] {target});
514      contourCluster = KMeansClustering.CreateKMeansSolution(cpd, contours, 3).Model;
515
516      borders = Enumerable.Range(0, contours).Select(x => new[] {double.MaxValue, double.MinValue}).ToArray();
517      var clusters = contourCluster.GetClusterValues(cpd.Dataset, cpd.AllIndices).ToArray();
518      var targetvalues = cpd.Dataset.GetDoubleValues(target).ToArray();
519      foreach (var i in cpd.AllIndices) {
520        var cl = clusters[i] - 1;
521        var clv = targetvalues[i];
522        if (borders[cl][0] > clv) borders[cl][0] = clv;
523        if (borders[cl][1] < clv) borders[cl][1] = clv;
524      }
525
526      contourNames = new Dictionary<int, string>();
527      for (var i = 0; i < contours; i++)
528        contourNames.Add(i, "[" + borders[i][0] + ";" + borders[i][1] + "]");
529    }
530
531    private static Color ConvertTotalToRgb(double low, double high, double cell) {
532      var colorGradient = ColorGradient.Colors;
533      var range = high - low;
534      var h = cell / range * colorGradient.Count;
535      return colorGradient[(int) h];
536    }
537    #endregion
538  }
539}
Note: See TracBrowser for help on using the repository browser.