[14414] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
| 3 | * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
| 4 | *
|
---|
| 5 | * This file is part of HeuristicLab.
|
---|
| 6 | *
|
---|
| 7 | * HeuristicLab is free software: you can redistribute it and/or modify
|
---|
| 8 | * it under the terms of the GNU General Public License as published by
|
---|
| 9 | * the Free Software Foundation, either version 3 of the License, or
|
---|
| 10 | * (at your option) any later version.
|
---|
| 11 | *
|
---|
| 12 | * HeuristicLab is distributed in the hope that it will be useful,
|
---|
| 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
| 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
| 15 | * GNU General Public License for more details.
|
---|
| 16 | *
|
---|
| 17 | * You should have received a copy of the GNU General Public License
|
---|
| 18 | * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
|
---|
| 19 | */
|
---|
| 20 | #endregion
|
---|
| 21 |
|
---|
[14518] | 22 | using System;
|
---|
[14512] | 23 | using System.Collections.Generic;
|
---|
| 24 | using System.Drawing;
|
---|
[14414] | 25 | using System.Linq;
|
---|
[14518] | 26 | using System.Threading;
|
---|
[14414] | 27 | using HeuristicLab.Analysis;
|
---|
| 28 | using HeuristicLab.Common;
|
---|
| 29 | using HeuristicLab.Core;
|
---|
| 30 | using HeuristicLab.Data;
|
---|
[14518] | 31 | using HeuristicLab.Optimization;
|
---|
[14414] | 32 | using HeuristicLab.Parameters;
|
---|
| 33 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
| 34 | using HeuristicLab.Problems.DataAnalysis;
|
---|
| 35 | using HeuristicLab.Random;
|
---|
| 36 |
|
---|
| 37 | namespace HeuristicLab.Algorithms.DataAnalysis {
|
---|
| 38 | /// <summary>
|
---|
[14785] | 39 | /// t-distributed stochastic neighbourhood embedding (tSNE) projects the data in a low dimensional
|
---|
[14767] | 40 | /// space to allow visual cluster identification.
|
---|
[14414] | 41 | /// </summary>
|
---|
[14785] | 42 | [Item("tSNE", "t-distributed stochastic neighbourhood embedding projects the data in a low " +
|
---|
[14767] | 43 | "dimensional space to allow visual cluster identification.")]
|
---|
[14414] | 44 | [Creatable(CreatableAttribute.Categories.DataAnalysis, Priority = 100)]
|
---|
| 45 | [StorableClass]
|
---|
[14785] | 46 | public sealed class TSNEAlgorithm : BasicAlgorithm {
|
---|
[14767] | 47 | public override bool SupportsPause {
|
---|
[14807] | 48 | get { return true; }
|
---|
[14558] | 49 | }
|
---|
[14767] | 50 | public override Type ProblemType {
|
---|
[14518] | 51 | get { return typeof(IDataAnalysisProblem); }
|
---|
| 52 | }
|
---|
[14767] | 53 | public new IDataAnalysisProblem Problem {
|
---|
[14518] | 54 | get { return (IDataAnalysisProblem)base.Problem; }
|
---|
| 55 | set { base.Problem = value; }
|
---|
| 56 | }
|
---|
[14414] | 57 |
|
---|
[14785] | 58 | #region parameter names
|
---|
[14414] | 59 | private const string DistanceParameterName = "DistanceFunction";
|
---|
| 60 | private const string PerplexityParameterName = "Perplexity";
|
---|
| 61 | private const string ThetaParameterName = "Theta";
|
---|
| 62 | private const string NewDimensionsParameterName = "Dimensions";
|
---|
| 63 | private const string MaxIterationsParameterName = "MaxIterations";
|
---|
| 64 | private const string StopLyingIterationParameterName = "StopLyingIteration";
|
---|
| 65 | private const string MomentumSwitchIterationParameterName = "MomentumSwitchIteration";
|
---|
| 66 | private const string InitialMomentumParameterName = "InitialMomentum";
|
---|
| 67 | private const string FinalMomentumParameterName = "FinalMomentum";
|
---|
| 68 | private const string EtaParameterName = "Eta";
|
---|
| 69 | private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
|
---|
| 70 | private const string SeedParameterName = "Seed";
|
---|
[14512] | 71 | private const string ClassesParameterName = "ClassNames";
|
---|
[14518] | 72 | private const string NormalizationParameterName = "Normalization";
|
---|
[14414] | 73 | #endregion
|
---|
| 74 |
|
---|
[14788] | 75 | #region result names
|
---|
| 76 | private const string IterationResultName = "Iteration";
|
---|
| 77 | private const string ErrorResultName = "Error";
|
---|
| 78 | private const string ErrorPlotResultName = "Error plot";
|
---|
| 79 | private const string ScatterPlotResultName = "Scatterplot";
|
---|
| 80 | private const string DataResultName = "Projected data";
|
---|
| 81 | #endregion
|
---|
| 82 |
|
---|
[14785] | 83 | #region parameter properties
|
---|
[14767] | 84 | public IFixedValueParameter<DoubleValue> PerplexityParameter {
|
---|
[14414] | 85 | get { return Parameters[PerplexityParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
| 86 | }
|
---|
[14785] | 87 | public IFixedValueParameter<DoubleValue> ThetaParameter {
|
---|
| 88 | get { return Parameters[ThetaParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
[14414] | 89 | }
|
---|
[14767] | 90 | public IFixedValueParameter<IntValue> NewDimensionsParameter {
|
---|
[14414] | 91 | get { return Parameters[NewDimensionsParameterName] as IFixedValueParameter<IntValue>; }
|
---|
| 92 | }
|
---|
[14785] | 93 | public IValueParameter<IDistance<double[]>> DistanceParameter {
|
---|
| 94 | get { return Parameters[DistanceParameterName] as IValueParameter<IDistance<double[]>>; }
|
---|
[14414] | 95 | }
|
---|
[14767] | 96 | public IFixedValueParameter<IntValue> MaxIterationsParameter {
|
---|
[14414] | 97 | get { return Parameters[MaxIterationsParameterName] as IFixedValueParameter<IntValue>; }
|
---|
| 98 | }
|
---|
[14767] | 99 | public IFixedValueParameter<IntValue> StopLyingIterationParameter {
|
---|
[14414] | 100 | get { return Parameters[StopLyingIterationParameterName] as IFixedValueParameter<IntValue>; }
|
---|
| 101 | }
|
---|
[14767] | 102 | public IFixedValueParameter<IntValue> MomentumSwitchIterationParameter {
|
---|
[14414] | 103 | get { return Parameters[MomentumSwitchIterationParameterName] as IFixedValueParameter<IntValue>; }
|
---|
| 104 | }
|
---|
[14767] | 105 | public IFixedValueParameter<DoubleValue> InitialMomentumParameter {
|
---|
[14414] | 106 | get { return Parameters[InitialMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
| 107 | }
|
---|
[14767] | 108 | public IFixedValueParameter<DoubleValue> FinalMomentumParameter {
|
---|
[14414] | 109 | get { return Parameters[FinalMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
| 110 | }
|
---|
[14767] | 111 | public IFixedValueParameter<DoubleValue> EtaParameter {
|
---|
[14414] | 112 | get { return Parameters[EtaParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
| 113 | }
|
---|
[14767] | 114 | public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
|
---|
[14414] | 115 | get { return Parameters[SetSeedRandomlyParameterName] as IFixedValueParameter<BoolValue>; }
|
---|
| 116 | }
|
---|
[14767] | 117 | public IFixedValueParameter<IntValue> SeedParameter {
|
---|
[14414] | 118 | get { return Parameters[SeedParameterName] as IFixedValueParameter<IntValue>; }
|
---|
| 119 | }
|
---|
[14767] | 120 | public IFixedValueParameter<StringValue> ClassesParameter {
|
---|
[14512] | 121 | get { return Parameters[ClassesParameterName] as IFixedValueParameter<StringValue>; }
|
---|
| 122 | }
|
---|
[14767] | 123 | public IFixedValueParameter<BoolValue> NormalizationParameter {
|
---|
[14518] | 124 | get { return Parameters[NormalizationParameterName] as IFixedValueParameter<BoolValue>; }
|
---|
| 125 | }
|
---|
[14414] | 126 | #endregion
|
---|
| 127 |
|
---|
| 128 | #region Properties
|
---|
[14785] | 129 | public IDistance<double[]> Distance {
|
---|
[14414] | 130 | get { return DistanceParameter.Value; }
|
---|
| 131 | }
|
---|
[14767] | 132 | public double Perplexity {
|
---|
[14414] | 133 | get { return PerplexityParameter.Value.Value; }
|
---|
[14785] | 134 | set { PerplexityParameter.Value.Value = value; }
|
---|
[14414] | 135 | }
|
---|
[14767] | 136 | public double Theta {
|
---|
[14785] | 137 | get { return ThetaParameter.Value.Value; }
|
---|
| 138 | set { ThetaParameter.Value.Value = value; }
|
---|
[14414] | 139 | }
|
---|
[14767] | 140 | public int NewDimensions {
|
---|
[14414] | 141 | get { return NewDimensionsParameter.Value.Value; }
|
---|
[14785] | 142 | set { NewDimensionsParameter.Value.Value = value; }
|
---|
[14414] | 143 | }
|
---|
[14767] | 144 | public int MaxIterations {
|
---|
[14414] | 145 | get { return MaxIterationsParameter.Value.Value; }
|
---|
[14785] | 146 | set { MaxIterationsParameter.Value.Value = value; }
|
---|
[14414] | 147 | }
|
---|
[14767] | 148 | public int StopLyingIteration {
|
---|
[14414] | 149 | get { return StopLyingIterationParameter.Value.Value; }
|
---|
[14785] | 150 | set { StopLyingIterationParameter.Value.Value = value; }
|
---|
[14414] | 151 | }
|
---|
[14767] | 152 | public int MomentumSwitchIteration {
|
---|
[14414] | 153 | get { return MomentumSwitchIterationParameter.Value.Value; }
|
---|
[14785] | 154 | set { MomentumSwitchIterationParameter.Value.Value = value; }
|
---|
[14414] | 155 | }
|
---|
[14767] | 156 | public double InitialMomentum {
|
---|
[14414] | 157 | get { return InitialMomentumParameter.Value.Value; }
|
---|
[14785] | 158 | set { InitialMomentumParameter.Value.Value = value; }
|
---|
[14414] | 159 | }
|
---|
[14767] | 160 | public double FinalMomentum {
|
---|
[14414] | 161 | get { return FinalMomentumParameter.Value.Value; }
|
---|
[14785] | 162 | set { FinalMomentumParameter.Value.Value = value; }
|
---|
[14414] | 163 | }
|
---|
[14767] | 164 | public double Eta {
|
---|
[14785] | 165 | get { return EtaParameter.Value.Value; }
|
---|
| 166 | set { EtaParameter.Value.Value = value; }
|
---|
[14414] | 167 | }
|
---|
[14767] | 168 | public bool SetSeedRandomly {
|
---|
[14414] | 169 | get { return SetSeedRandomlyParameter.Value.Value; }
|
---|
[14785] | 170 | set { SetSeedRandomlyParameter.Value.Value = value; }
|
---|
[14414] | 171 | }
|
---|
[14785] | 172 | public int Seed {
|
---|
| 173 | get { return SeedParameter.Value.Value; }
|
---|
| 174 | set { SeedParameter.Value.Value = value; }
|
---|
[14414] | 175 | }
|
---|
[14767] | 176 | public string Classes {
|
---|
[14512] | 177 | get { return ClassesParameter.Value.Value; }
|
---|
[14785] | 178 | set { ClassesParameter.Value.Value = value; }
|
---|
[14512] | 179 | }
|
---|
[14767] | 180 | public bool Normalization {
|
---|
[14518] | 181 | get { return NormalizationParameter.Value.Value; }
|
---|
[14785] | 182 | set { NormalizationParameter.Value.Value = value; }
|
---|
[14518] | 183 | }
|
---|
[14414] | 184 | #endregion
|
---|
| 185 |
|
---|
| 186 | #region Constructors & Cloning
|
---|
| 187 | [StorableConstructor]
|
---|
[14785] | 188 | private TSNEAlgorithm(bool deserializing) : base(deserializing) { }
|
---|
[14807] | 189 |
|
---|
| 190 | private TSNEAlgorithm(TSNEAlgorithm original, Cloner cloner) : base(original, cloner) {
|
---|
| 191 | this.dataRowNames = new Dictionary<string, List<int>>(original.dataRowNames);
|
---|
| 192 | this.dataRows = original.dataRows.ToDictionary(kvp => kvp.Key, kvp => cloner.Clone(kvp.Value));
|
---|
| 193 | if(original.state != null)
|
---|
| 194 | this.state = cloner.Clone(original.state);
|
---|
| 195 | this.iter = original.iter;
|
---|
| 196 | }
|
---|
[14785] | 197 | public override IDeepCloneable Clone(Cloner cloner) { return new TSNEAlgorithm(this, cloner); }
|
---|
| 198 | public TSNEAlgorithm() {
|
---|
[14414] | 199 | Problem = new RegressionProblem();
|
---|
[14785] | 200 | Parameters.Add(new ValueParameter<IDistance<double[]>>(DistanceParameterName, "The distance function used to differentiate similar from non-similar points", new EuclideanDistance()));
|
---|
[14807] | 201 | Parameters.Add(new FixedValueParameter<DoubleValue>(PerplexityParameterName, "Perplexity-parameter of tSNE. Comparable to k in a k-nearest neighbour algorithm. Recommended value is floor(number of points /3) or lower", new DoubleValue(25)));
|
---|
[14837] | 202 | Parameters.Add(new FixedValueParameter<DoubleValue>(ThetaParameterName, "Value describing how much appoximated " +
|
---|
| 203 | "gradients my differ from exact gradients. Set to 0 for exact calculation and in [0,1] otherwise. " +
|
---|
| 204 | "Appropriate values for theta are between 0.1 and 0.7 (default = 0.5). CAUTION: exact calculation of " +
|
---|
| 205 | "forces requires building a non-sparse N*N matrix where N is the number of data points. This may " +
|
---|
| 206 | "exceed memory limitations. The function is designed to run on large (N > 5000) data sets. It may give" +
|
---|
| 207 | " poor performance on very small data sets(it is better to use a standard t - SNE implementation on such data).", new DoubleValue(0)));
|
---|
[14785] | 208 | Parameters.Add(new FixedValueParameter<IntValue>(NewDimensionsParameterName, "Dimensionality of projected space (usually 2 for easy visual analysis)", new IntValue(2)));
|
---|
[14807] | 209 | Parameters.Add(new FixedValueParameter<IntValue>(MaxIterationsParameterName, "Maximum number of iterations for gradient descent.", new IntValue(1000)));
|
---|
| 210 | Parameters.Add(new FixedValueParameter<IntValue>(StopLyingIterationParameterName, "Number of iterations after which p is no longer approximated.", new IntValue(0)));
|
---|
| 211 | Parameters.Add(new FixedValueParameter<IntValue>(MomentumSwitchIterationParameterName, "Number of iterations after which the momentum in the gradient descent is switched.", new IntValue(0)));
|
---|
| 212 | Parameters.Add(new FixedValueParameter<DoubleValue>(InitialMomentumParameterName, "The initial momentum in the gradient descent.", new DoubleValue(0.5)));
|
---|
| 213 | Parameters.Add(new FixedValueParameter<DoubleValue>(FinalMomentumParameterName, "The final momentum.", new DoubleValue(0.8)));
|
---|
[14837] | 214 | Parameters.Add(new FixedValueParameter<DoubleValue>(EtaParameterName, "Gradient descent learning rate.", new DoubleValue(10)));
|
---|
[14807] | 215 | Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "If the seed should be random.", new BoolValue(true)));
|
---|
| 216 | Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The seed used if it should not be random.", new IntValue(0)));
|
---|
| 217 | Parameters.Add(new FixedValueParameter<StringValue>(ClassesParameterName, "name of the column specifying the class lables of each data point. If the label column can not be found training/test is used as labels.", new StringValue("none")));
|
---|
| 218 | 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)));
|
---|
[14518] | 219 |
|
---|
| 220 | MomentumSwitchIterationParameter.Hidden = true;
|
---|
| 221 | InitialMomentumParameter.Hidden = true;
|
---|
| 222 | FinalMomentumParameter.Hidden = true;
|
---|
| 223 | StopLyingIterationParameter.Hidden = true;
|
---|
[14837] | 224 | EtaParameter.Hidden = false;
|
---|
[14414] | 225 | }
|
---|
| 226 | #endregion
|
---|
| 227 |
|
---|
[14788] | 228 | [Storable]
|
---|
[14807] | 229 | private Dictionary<string, List<int>> dataRowNames;
|
---|
[14788] | 230 | [Storable]
|
---|
[14807] | 231 | private Dictionary<string, ScatterPlotDataRow> dataRows;
|
---|
| 232 | [Storable]
|
---|
| 233 | private TSNEStatic<double[]>.TSNEState state;
|
---|
| 234 | [Storable]
|
---|
| 235 | private int iter;
|
---|
[14414] | 236 |
|
---|
[14807] | 237 | public override void Prepare() {
|
---|
| 238 | base.Prepare();
|
---|
| 239 | dataRowNames = null;
|
---|
| 240 | dataRows = null;
|
---|
| 241 | state = null;
|
---|
| 242 | }
|
---|
[14788] | 243 |
|
---|
[14518] | 244 | protected override void Run(CancellationToken cancellationToken) {
|
---|
[14742] | 245 | var problemData = Problem.ProblemData;
|
---|
[14807] | 246 | // set up and initialized everything if necessary
|
---|
| 247 | if(state == null) {
|
---|
| 248 | if(SetSeedRandomly) Seed = new System.Random().Next();
|
---|
| 249 | var random = new MersenneTwister((uint)Seed);
|
---|
| 250 | var dataset = problemData.Dataset;
|
---|
| 251 | var allowedInputVariables = problemData.AllowedInputVariables.ToArray();
|
---|
| 252 | var data = new double[dataset.Rows][];
|
---|
| 253 | for(var row = 0; row < dataset.Rows; row++)
|
---|
| 254 | data[row] = allowedInputVariables.Select(col => dataset.GetDoubleValue(col, row)).ToArray();
|
---|
[14512] | 255 |
|
---|
[14807] | 256 | if(Normalization) data = NormalizeData(data);
|
---|
[14788] | 257 |
|
---|
[14807] | 258 | state = TSNEStatic<double[]>.CreateState(data, Distance, random, NewDimensions, Perplexity, Theta,
|
---|
| 259 | StopLyingIteration, MomentumSwitchIteration, InitialMomentum, FinalMomentum, Eta);
|
---|
[14788] | 260 |
|
---|
[14807] | 261 | SetUpResults(data);
|
---|
| 262 | iter = 0;
|
---|
[14788] | 263 | }
|
---|
[14807] | 264 | for(; iter < MaxIterations && !cancellationToken.IsCancellationRequested; iter++) {
|
---|
| 265 | TSNEStatic<double[]>.Iterate(state);
|
---|
| 266 | Analyze(state);
|
---|
| 267 | }
|
---|
[14788] | 268 | }
|
---|
| 269 |
|
---|
| 270 | private void SetUpResults(IReadOnlyCollection<double[]> data) {
|
---|
[14807] | 271 | if(Results == null) return;
|
---|
[14788] | 272 | var results = Results;
|
---|
| 273 | dataRowNames = new Dictionary<string, List<int>>();
|
---|
| 274 | dataRows = new Dictionary<string, ScatterPlotDataRow>();
|
---|
| 275 | var problemData = Problem.ProblemData;
|
---|
| 276 |
|
---|
[14785] | 277 | //color datapoints acording to classes variable (be it double or string)
|
---|
[14807] | 278 | if(problemData.Dataset.VariableNames.Contains(Classes)) {
|
---|
| 279 | if((problemData.Dataset as Dataset).VariableHasType<string>(Classes)) {
|
---|
[14512] | 280 | var classes = problemData.Dataset.GetStringValues(Classes).ToArray();
|
---|
[14807] | 281 | for(var i = 0; i < classes.Length; i++) {
|
---|
| 282 | if(!dataRowNames.ContainsKey(classes[i])) dataRowNames.Add(classes[i], new List<int>());
|
---|
[14742] | 283 | dataRowNames[classes[i]].Add(i);
|
---|
[14512] | 284 | }
|
---|
[14807] | 285 | } else if((problemData.Dataset as Dataset).VariableHasType<double>(Classes)) {
|
---|
[14512] | 286 | var classValues = problemData.Dataset.GetDoubleValues(Classes).ToArray();
|
---|
[14855] | 287 | var max = classValues.Max() + 0.1;
|
---|
[14512] | 288 | var min = classValues.Min() - 0.1;
|
---|
[14742] | 289 | const int contours = 8;
|
---|
[14807] | 290 | for(var i = 0; i < contours; i++) {
|
---|
[14742] | 291 | var contourname = GetContourName(i, min, max, contours);
|
---|
| 292 | dataRowNames.Add(contourname, new List<int>());
|
---|
[14788] | 293 | dataRows.Add(contourname, new ScatterPlotDataRow(contourname, "", new List<Point2D<double>>()));
|
---|
| 294 | dataRows[contourname].VisualProperties.Color = GetHeatMapColor(i, contours);
|
---|
| 295 | dataRows[contourname].VisualProperties.PointSize = i + 3;
|
---|
[14512] | 296 | }
|
---|
[14807] | 297 | for(var i = 0; i < classValues.Length; i++) {
|
---|
[14742] | 298 | dataRowNames[GetContourName(classValues[i], min, max, contours)].Add(i);
|
---|
[14512] | 299 | }
|
---|
| 300 | }
|
---|
| 301 | } else {
|
---|
[14518] | 302 | dataRowNames.Add("Training", problemData.TrainingIndices.ToList());
|
---|
| 303 | dataRowNames.Add("Test", problemData.TestIndices.ToList());
|
---|
[14512] | 304 | }
|
---|
| 305 |
|
---|
[14807] | 306 | if(!results.ContainsKey(IterationResultName)) results.Add(new Result(IterationResultName, new IntValue(0)));
|
---|
[14788] | 307 | else ((IntValue)results[IterationResultName].Value).Value = 0;
|
---|
| 308 |
|
---|
[14807] | 309 | if(!results.ContainsKey(ErrorResultName)) results.Add(new Result(ErrorResultName, new DoubleValue(0)));
|
---|
[14788] | 310 | else ((DoubleValue)results[ErrorResultName].Value).Value = 0;
|
---|
| 311 |
|
---|
[14807] | 312 | if(!results.ContainsKey(ErrorPlotResultName)) results.Add(new Result(ErrorPlotResultName, new DataTable(ErrorPlotResultName, "Development of errors during gradient descent")));
|
---|
[14788] | 313 | else results[ErrorPlotResultName].Value = new DataTable(ErrorPlotResultName, "Development of errors during gradient descent");
|
---|
| 314 |
|
---|
| 315 | var plot = results[ErrorPlotResultName].Value as DataTable;
|
---|
[14807] | 316 | if(plot == null) throw new ArgumentException("could not create/access error data table in results collection");
|
---|
[14788] | 317 |
|
---|
[14807] | 318 | if(!plot.Rows.ContainsKey("errors")) plot.Rows.Add(new DataRow("errors"));
|
---|
[14788] | 319 | plot.Rows["errors"].Values.Clear();
|
---|
| 320 |
|
---|
| 321 | results.Add(new Result(ScatterPlotResultName, "Plot of the projected data", new ScatterPlot(DataResultName, "")));
|
---|
| 322 | results.Add(new Result(DataResultName, "Projected Data", new DoubleMatrix()));
|
---|
[14414] | 323 | }
|
---|
| 324 |
|
---|
[14807] | 325 | private void Analyze(TSNEStatic<double[]>.TSNEState tsneState) {
|
---|
| 326 | if(Results == null) return;
|
---|
[14788] | 327 | var results = Results;
|
---|
| 328 | var plot = results[ErrorPlotResultName].Value as DataTable;
|
---|
[14807] | 329 | if(plot == null) throw new ArgumentException("Could not create/access error data table in results collection.");
|
---|
[14788] | 330 | var errors = plot.Rows["errors"].Values;
|
---|
| 331 | var c = tsneState.EvaluateError();
|
---|
| 332 | errors.Add(c);
|
---|
[14807] | 333 | ((IntValue)results[IterationResultName].Value).Value = tsneState.iter;
|
---|
[14788] | 334 | ((DoubleValue)results[ErrorResultName].Value).Value = errors.Last();
|
---|
| 335 |
|
---|
| 336 | var ndata = Normalize(tsneState.newData);
|
---|
| 337 | results[DataResultName].Value = new DoubleMatrix(ndata);
|
---|
| 338 | var splot = results[ScatterPlotResultName].Value as ScatterPlot;
|
---|
| 339 | FillScatterPlot(ndata, splot);
|
---|
| 340 | }
|
---|
| 341 |
|
---|
| 342 | private void FillScatterPlot(double[,] lowDimData, ScatterPlot plot) {
|
---|
[14807] | 343 | foreach(var rowName in dataRowNames.Keys) {
|
---|
| 344 | if(!plot.Rows.ContainsKey(rowName))
|
---|
[14788] | 345 | plot.Rows.Add(dataRows.ContainsKey(rowName) ? dataRows[rowName] : new ScatterPlotDataRow(rowName, "", new List<Point2D<double>>()));
|
---|
| 346 | plot.Rows[rowName].Points.Replace(dataRowNames[rowName].Select(i => new Point2D<double>(lowDimData[i, 0], lowDimData[i, 1])));
|
---|
| 347 | }
|
---|
| 348 | }
|
---|
| 349 |
|
---|
| 350 | private static double[,] Normalize(double[,] data) {
|
---|
| 351 | var max = new double[data.GetLength(1)];
|
---|
| 352 | var min = new double[data.GetLength(1)];
|
---|
| 353 | var res = new double[data.GetLength(0), data.GetLength(1)];
|
---|
[14807] | 354 | for(var i = 0; i < max.Length; i++) max[i] = min[i] = data[0, i];
|
---|
| 355 | for(var i = 0; i < data.GetLength(0); i++)
|
---|
| 356 | for(var j = 0; j < data.GetLength(1); j++) {
|
---|
[14788] | 357 | var v = data[i, j];
|
---|
| 358 | max[j] = Math.Max(max[j], v);
|
---|
| 359 | min[j] = Math.Min(min[j], v);
|
---|
| 360 | }
|
---|
[14807] | 361 | for(var i = 0; i < data.GetLength(0); i++) {
|
---|
| 362 | for(var j = 0; j < data.GetLength(1); j++) {
|
---|
[14788] | 363 | res[i, j] = (data[i, j] - (max[j] + min[j]) / 2) / (max[j] - min[j]);
|
---|
| 364 | }
|
---|
| 365 | }
|
---|
| 366 | return res;
|
---|
| 367 | }
|
---|
| 368 |
|
---|
[14785] | 369 | private static double[][] NormalizeData(IReadOnlyList<double[]> data) {
|
---|
[14518] | 370 | var n = data[0].Length;
|
---|
| 371 | var mean = new double[n];
|
---|
| 372 | var sd = new double[n];
|
---|
[14785] | 373 | var nData = new double[data.Count][];
|
---|
[14807] | 374 | for(var i = 0; i < n; i++) {
|
---|
[14518] | 375 | var i1 = i;
|
---|
[14742] | 376 | sd[i] = Enumerable.Range(0, data.Count).Select(x => data[x][i1]).StandardDeviation();
|
---|
| 377 | mean[i] = Enumerable.Range(0, data.Count).Select(x => data[x][i1]).Average();
|
---|
[14518] | 378 | }
|
---|
[14807] | 379 | for(var i = 0; i < data.Count; i++) {
|
---|
[14785] | 380 | nData[i] = new double[n];
|
---|
[14807] | 381 | for(var j = 0; j < n; j++) nData[i][j] = (data[i][j] - mean[j]) / sd[j];
|
---|
[14518] | 382 | }
|
---|
| 383 | return nData;
|
---|
| 384 | }
|
---|
[14788] | 385 |
|
---|
[14512] | 386 | private static Color GetHeatMapColor(int contourNr, int noContours) {
|
---|
| 387 | var q = (double)contourNr / noContours; // q in [0,1]
|
---|
| 388 | var c = q < 0.5 ? Color.FromArgb((int)(q * 2 * 255), 255, 0) : Color.FromArgb(255, (int)((1 - q) * 2 * 255), 0);
|
---|
| 389 | return c;
|
---|
| 390 | }
|
---|
[14788] | 391 |
|
---|
[14512] | 392 | private static string GetContourName(double value, double min, double max, int noContours) {
|
---|
| 393 | var size = (max - min) / noContours;
|
---|
| 394 | var contourNr = (int)((value - min) / size);
|
---|
| 395 | return GetContourName(contourNr, min, max, noContours);
|
---|
| 396 | }
|
---|
[14788] | 397 |
|
---|
[14512] | 398 | private static string GetContourName(int i, double min, double max, int noContours) {
|
---|
| 399 | var size = (max - min) / noContours;
|
---|
| 400 | return "[" + (min + i * size) + ";" + (min + (i + 1) * size) + ")";
|
---|
| 401 | }
|
---|
[14414] | 402 | }
|
---|
| 403 | }
|
---|