Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2520: merged changes from PersistenceOverhaul branch (r16451:16564) into trunk

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