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 |
|
---|
22 | using System;
|
---|
23 | using System.Collections.Generic;
|
---|
24 | using System.Drawing;
|
---|
25 | using System.Linq;
|
---|
26 | using System.Threading;
|
---|
27 | using HeuristicLab.Analysis;
|
---|
28 | using HeuristicLab.Common;
|
---|
29 | using HeuristicLab.Core;
|
---|
30 | using HeuristicLab.Data;
|
---|
31 | using HeuristicLab.Optimization;
|
---|
32 | using HeuristicLab.Parameters;
|
---|
33 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
34 | using HeuristicLab.PluginInfrastructure;
|
---|
35 | using HeuristicLab.Problems.DataAnalysis;
|
---|
36 | using HeuristicLab.Random;
|
---|
37 |
|
---|
38 | namespace 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 Parameters[PerplexityParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
89 | }
|
---|
90 | public IFixedValueParameter<PercentValue> ThetaParameter {
|
---|
91 | get { return Parameters[ThetaParameterName] as IFixedValueParameter<PercentValue>; }
|
---|
92 | }
|
---|
93 | public IFixedValueParameter<IntValue> NewDimensionsParameter {
|
---|
94 | get { return Parameters[NewDimensionsParameterName] as IFixedValueParameter<IntValue>; }
|
---|
95 | }
|
---|
96 | public IConstrainedValueParameter<IDistance<double[]>> DistanceFunctionParameter {
|
---|
97 | get { return Parameters[DistanceFunctionParameterName] as IConstrainedValueParameter<IDistance<double[]>>; }
|
---|
98 | }
|
---|
99 | public IFixedValueParameter<IntValue> MaxIterationsParameter {
|
---|
100 | get { return Parameters[MaxIterationsParameterName] as IFixedValueParameter<IntValue>; }
|
---|
101 | }
|
---|
102 | public IFixedValueParameter<IntValue> StopLyingIterationParameter {
|
---|
103 | get { return Parameters[StopLyingIterationParameterName] as IFixedValueParameter<IntValue>; }
|
---|
104 | }
|
---|
105 | public IFixedValueParameter<IntValue> MomentumSwitchIterationParameter {
|
---|
106 | get { return Parameters[MomentumSwitchIterationParameterName] as IFixedValueParameter<IntValue>; }
|
---|
107 | }
|
---|
108 | public IFixedValueParameter<DoubleValue> InitialMomentumParameter {
|
---|
109 | get { return Parameters[InitialMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
110 | }
|
---|
111 | public IFixedValueParameter<DoubleValue> FinalMomentumParameter {
|
---|
112 | get { return Parameters[FinalMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
113 | }
|
---|
114 | public IFixedValueParameter<DoubleValue> EtaParameter {
|
---|
115 | get { return Parameters[EtaParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
116 | }
|
---|
117 | public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
|
---|
118 | get { return Parameters[SetSeedRandomlyParameterName] as IFixedValueParameter<BoolValue>; }
|
---|
119 | }
|
---|
120 | public IFixedValueParameter<IntValue> SeedParameter {
|
---|
121 | get { return Parameters[SeedParameterName] as IFixedValueParameter<IntValue>; }
|
---|
122 | }
|
---|
123 | public IConstrainedValueParameter<StringValue> ClassesNameParameter {
|
---|
124 | get { return Parameters[ClassesNameParameterName] as IConstrainedValueParameter<StringValue>; }
|
---|
125 | }
|
---|
126 | public IFixedValueParameter<BoolValue> NormalizationParameter {
|
---|
127 | get { return Parameters[NormalizationParameterName] as IFixedValueParameter<BoolValue>; }
|
---|
128 | }
|
---|
129 | public IFixedValueParameter<BoolValue> RandomInitializationParameter {
|
---|
130 | get { return Parameters[RandomInitializationParameterName] as IFixedValueParameter<BoolValue>; }
|
---|
131 | }
|
---|
132 | public IFixedValueParameter<IntValue> UpdateIntervalParameter {
|
---|
133 | get { return Parameters[UpdateIntervalParameterName] as IFixedValueParameter<IntValue>; }
|
---|
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 Constructors & Cloning
|
---|
205 | [StorableConstructor]
|
---|
206 | private TSNEAlgorithm(bool deserializing) : base(deserializing) { }
|
---|
207 |
|
---|
208 | private TSNEAlgorithm(TSNEAlgorithm original, Cloner cloner) : base(original, cloner) {
|
---|
209 | if (original.dataRowNames != null)
|
---|
210 | dataRowNames = new Dictionary<string, List<int>>(original.dataRowNames);
|
---|
211 | if (original.dataRows != null)
|
---|
212 | dataRows = original.dataRows.ToDictionary(kvp => kvp.Key, kvp => cloner.Clone(kvp.Value));
|
---|
213 | if (original.state != null)
|
---|
214 | state = cloner.Clone(original.state);
|
---|
215 | iter = original.iter;
|
---|
216 | }
|
---|
217 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
218 | return new TSNEAlgorithm(this, cloner);
|
---|
219 | }
|
---|
220 | public TSNEAlgorithm() {
|
---|
221 | var distances = new ItemSet<IDistance<double[]>>(ApplicationManager.Manager.GetInstances<IDistance<double[]>>());
|
---|
222 | Parameters.Add(new ConstrainedValueParameter<IDistance<double[]>>(DistanceFunctionParameterName, "The distance function used to differentiate similar from non-similar points", distances, distances.OfType<EuclideanDistance>().FirstOrDefault()));
|
---|
223 | 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)));
|
---|
224 | Parameters.Add(new FixedValueParameter<PercentValue>(ThetaParameterName, "Value describing how much appoximated " +
|
---|
225 | "gradients my differ from exact gradients. Set to 0 for exact calculation and in [0,1] otherwise. " +
|
---|
226 | "Appropriate values for theta are between 0.1 and 0.7 (default = 0.5). CAUTION: exact calculation of " +
|
---|
227 | "forces requires building a non-sparse N*N matrix where N is the number of data points. This may " +
|
---|
228 | "exceed memory limitations. The function is designed to run on large (N > 5000) data sets. It may give" +
|
---|
229 | " poor performance on very small data sets(it is better to use a standard t - SNE implementation on such data).", new PercentValue(0)));
|
---|
230 | Parameters.Add(new FixedValueParameter<IntValue>(NewDimensionsParameterName, "Dimensionality of projected space (usually 2 for easy visual analysis)", new IntValue(2)));
|
---|
231 | Parameters.Add(new FixedValueParameter<IntValue>(MaxIterationsParameterName, "Maximum number of iterations for gradient descent.", new IntValue(1000)));
|
---|
232 | Parameters.Add(new FixedValueParameter<IntValue>(StopLyingIterationParameterName, "Number of iterations after which p is no longer approximated.", new IntValue(0)));
|
---|
233 | Parameters.Add(new FixedValueParameter<IntValue>(MomentumSwitchIterationParameterName, "Number of iterations after which the momentum in the gradient descent is switched.", new IntValue(0)));
|
---|
234 | Parameters.Add(new FixedValueParameter<DoubleValue>(InitialMomentumParameterName, "The initial momentum in the gradient descent.", new DoubleValue(0.5)));
|
---|
235 | Parameters.Add(new FixedValueParameter<DoubleValue>(FinalMomentumParameterName, "The final momentum.", new DoubleValue(0.8)));
|
---|
236 | Parameters.Add(new FixedValueParameter<DoubleValue>(EtaParameterName, "Gradient descent learning rate.", new DoubleValue(10)));
|
---|
237 | Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "If the seed should be random.", new BoolValue(true)));
|
---|
238 | Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The seed used if it should not be random.", new IntValue(0)));
|
---|
239 | 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."));
|
---|
240 | 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)));
|
---|
241 | Parameters.Add(new FixedValueParameter<IntValue>(UpdateIntervalParameterName, "The interval after which the results will be updated.", new IntValue(50)));
|
---|
242 | Parameters.Add(new FixedValueParameter<BoolValue>(RandomInitializationParameterName, "Wether data points should be randomly initialized or according to the first 2 dimensions", new BoolValue(true)));
|
---|
243 |
|
---|
244 | Parameters[UpdateIntervalParameterName].Hidden = true;
|
---|
245 |
|
---|
246 | MomentumSwitchIterationParameter.Hidden = true;
|
---|
247 | InitialMomentumParameter.Hidden = true;
|
---|
248 | FinalMomentumParameter.Hidden = true;
|
---|
249 | StopLyingIterationParameter.Hidden = true;
|
---|
250 | EtaParameter.Hidden = false;
|
---|
251 | Problem = new RegressionProblem();
|
---|
252 | }
|
---|
253 | #endregion
|
---|
254 |
|
---|
255 | [Storable]
|
---|
256 | private Dictionary<string, List<int>> dataRowNames;
|
---|
257 | [Storable]
|
---|
258 | private Dictionary<string, ScatterPlotDataRow> dataRows;
|
---|
259 | [Storable]
|
---|
260 | private TSNEStatic<double[]>.TSNEState state;
|
---|
261 | [Storable]
|
---|
262 | private int iter;
|
---|
263 |
|
---|
264 | public override void Prepare() {
|
---|
265 | base.Prepare();
|
---|
266 | dataRowNames = null;
|
---|
267 | dataRows = null;
|
---|
268 | state = null;
|
---|
269 | }
|
---|
270 |
|
---|
271 | protected override void Run(CancellationToken cancellationToken) {
|
---|
272 | var problemData = Problem.ProblemData;
|
---|
273 | // set up and initialize everything if necessary
|
---|
274 | if (state == null) {
|
---|
275 | if (SetSeedRandomly) Seed = new System.Random().Next();
|
---|
276 | var random = new MersenneTwister((uint) Seed);
|
---|
277 | var dataset = problemData.Dataset;
|
---|
278 | var allowedInputVariables = problemData.AllowedInputVariables.ToArray();
|
---|
279 | var allindices = Problem.ProblemData.AllIndices.ToArray();
|
---|
280 | var data = allindices.Select(row => allowedInputVariables.Select(col => dataset.GetDoubleValue(col, row)).ToArray()).ToArray();
|
---|
281 | if (Normalization) data = NormalizeInputData(data);
|
---|
282 | state = TSNEStatic<double[]>.CreateState(data, DistanceFunction, random, NewDimensions, Perplexity, Theta, StopLyingIteration, MomentumSwitchIteration, InitialMomentum, FinalMomentum, Eta, RandomInitialization);
|
---|
283 | SetUpResults(allindices);
|
---|
284 | iter = 0;
|
---|
285 | }
|
---|
286 | for (; iter < MaxIterations && !cancellationToken.IsCancellationRequested; iter++) {
|
---|
287 | if (iter % UpdateInterval == 0)
|
---|
288 | Analyze(state);
|
---|
289 | TSNEStatic<double[]>.Iterate(state);
|
---|
290 | }
|
---|
291 | Analyze(state);
|
---|
292 | dataRowNames = null;
|
---|
293 | dataRows = null;
|
---|
294 | state = null;
|
---|
295 | }
|
---|
296 |
|
---|
297 | #region Events
|
---|
298 | protected override void OnProblemChanged() {
|
---|
299 | base.OnProblemChanged();
|
---|
300 | if (Problem == null) return;
|
---|
301 | OnProblemDataChanged(this, null);
|
---|
302 | }
|
---|
303 |
|
---|
304 | protected override void RegisterProblemEvents() {
|
---|
305 | base.RegisterProblemEvents();
|
---|
306 | Problem.ProblemDataChanged += OnProblemDataChanged;
|
---|
307 | }
|
---|
308 | protected override void DeregisterProblemEvents() {
|
---|
309 | base.DeregisterProblemEvents();
|
---|
310 | Problem.ProblemDataChanged -= OnProblemDataChanged;
|
---|
311 | }
|
---|
312 |
|
---|
313 | private void OnProblemDataChanged(object sender, EventArgs args) {
|
---|
314 | if (Problem == null || Problem.ProblemData == null) return;
|
---|
315 | if (!Parameters.ContainsKey(ClassesNameParameterName)) return;
|
---|
316 | ClassesNameParameter.ValidValues.Clear();
|
---|
317 | foreach (var input in Problem.ProblemData.InputVariables) ClassesNameParameter.ValidValues.Add(input);
|
---|
318 | }
|
---|
319 | #endregion
|
---|
320 |
|
---|
321 | #region Helpers
|
---|
322 | private void SetUpResults(IReadOnlyList<int> allIndices) {
|
---|
323 | if (Results == null) return;
|
---|
324 | var results = Results;
|
---|
325 | dataRowNames = new Dictionary<string, List<int>>();
|
---|
326 | dataRows = new Dictionary<string, ScatterPlotDataRow>();
|
---|
327 | var problemData = Problem.ProblemData;
|
---|
328 |
|
---|
329 | //color datapoints acording to classes variable (be it double or string)
|
---|
330 | if (problemData.Dataset.VariableNames.Contains(ClassesName)) {
|
---|
331 | var classificationData = problemData as ClassificationProblemData;
|
---|
332 | if (classificationData != null && classificationData.TargetVariable.Equals(ClassesName)) {
|
---|
333 | var classNames = classificationData.ClassValues.Zip(classificationData.ClassNames, (v, n) => new {v, n}).ToDictionary(x => x.v, x => x.n);
|
---|
334 | var classes = classificationData.Dataset.GetDoubleValues(classificationData.TargetVariable, allIndices).Select(v => classNames[v]).ToArray();
|
---|
335 | for (var i = 0; i < classes.Length; i++) {
|
---|
336 | if (!dataRowNames.ContainsKey(classes[i])) dataRowNames.Add(classes[i], new List<int>());
|
---|
337 | dataRowNames[classes[i]].Add(i);
|
---|
338 | }
|
---|
339 | }
|
---|
340 | else if (((Dataset) problemData.Dataset).VariableHasType<string>(ClassesName)) {
|
---|
341 | var classes = problemData.Dataset.GetStringValues(ClassesName, allIndices).ToArray();
|
---|
342 | for (var i = 0; i < classes.Length; i++) {
|
---|
343 | if (!dataRowNames.ContainsKey(classes[i])) dataRowNames.Add(classes[i], new List<int>());
|
---|
344 | dataRowNames[classes[i]].Add(i);
|
---|
345 | }
|
---|
346 | }
|
---|
347 | else if (((Dataset) problemData.Dataset).VariableHasType<double>(ClassesName)) {
|
---|
348 | var clusterdata = new Dataset(problemData.Dataset.DoubleVariables, problemData.Dataset.DoubleVariables.Select(v => problemData.Dataset.GetDoubleValues(v, allIndices).ToList()));
|
---|
349 | const int contours = 8;
|
---|
350 | Dictionary<int, string> contourMap;
|
---|
351 | IClusteringModel clusterModel;
|
---|
352 | double[][] borders;
|
---|
353 | CreateClusters(clusterdata, ClassesName, contours, out clusterModel, out contourMap, out borders);
|
---|
354 | var contourorder = borders.Select((x, i) => new {x, i}).OrderBy(x => x.x[0]).Select(x => x.i).ToArray();
|
---|
355 | for (var i = 0; i < contours; i++) {
|
---|
356 | var c = contourorder[i];
|
---|
357 | var contourname = contourMap[c];
|
---|
358 | dataRowNames.Add(contourname, new List<int>());
|
---|
359 | dataRows.Add(contourname, new ScatterPlotDataRow(contourname, "", new List<Point2D<double>>()));
|
---|
360 | dataRows[contourname].VisualProperties.Color = GetHeatMapColor(i, contours);
|
---|
361 | dataRows[contourname].VisualProperties.PointSize = i + 3;
|
---|
362 | }
|
---|
363 | var allClusters = clusterModel.GetClusterValues(clusterdata, Enumerable.Range(0, clusterdata.Rows)).ToArray();
|
---|
364 | for (var i = 0; i < clusterdata.Rows; i++) dataRowNames[contourMap[allClusters[i] - 1]].Add(i);
|
---|
365 | }
|
---|
366 | else if (((Dataset) problemData.Dataset).VariableHasType<DateTime>(ClassesName)) {
|
---|
367 | var clusterdata = new Dataset(problemData.Dataset.DateTimeVariables, problemData.Dataset.DateTimeVariables.Select(v => problemData.Dataset.GetDoubleValues(v, allIndices).ToList()));
|
---|
368 | const int contours = 8;
|
---|
369 | Dictionary<int, string> contourMap;
|
---|
370 | IClusteringModel clusterModel;
|
---|
371 | double[][] borders;
|
---|
372 | CreateClusters(clusterdata, ClassesName, contours, out clusterModel, out contourMap, out borders);
|
---|
373 | var contourorder = borders.Select((x, i) => new {x, i}).OrderBy(x => x.x[0]).Select(x => x.i).ToArray();
|
---|
374 | for (var i = 0; i < contours; i++) {
|
---|
375 | var c = contourorder[i];
|
---|
376 | var contourname = contourMap[c];
|
---|
377 | dataRowNames.Add(contourname, new List<int>());
|
---|
378 | dataRows.Add(contourname, new ScatterPlotDataRow(contourname, "", new List<Point2D<double>>()));
|
---|
379 | dataRows[contourname].VisualProperties.Color = GetHeatMapColor(i, contours);
|
---|
380 | dataRows[contourname].VisualProperties.PointSize = i + 3;
|
---|
381 | }
|
---|
382 | var allClusters = clusterModel.GetClusterValues(clusterdata, Enumerable.Range(0, clusterdata.Rows)).ToArray();
|
---|
383 | for (var i = 0; i < clusterdata.Rows; i++) dataRowNames[contourMap[allClusters[i] - 1]].Add(i);
|
---|
384 | }
|
---|
385 | else {
|
---|
386 | dataRowNames.Add("Training", problemData.TrainingIndices.ToList());
|
---|
387 | dataRowNames.Add("Test", problemData.TestIndices.ToList());
|
---|
388 | }
|
---|
389 |
|
---|
390 | if (!results.ContainsKey(IterationResultName)) results.Add(new Result(IterationResultName, new IntValue(0)));
|
---|
391 | else ((IntValue) results[IterationResultName].Value).Value = 0;
|
---|
392 |
|
---|
393 | if (!results.ContainsKey(ErrorResultName)) results.Add(new Result(ErrorResultName, new DoubleValue(0)));
|
---|
394 | else ((DoubleValue) results[ErrorResultName].Value).Value = 0;
|
---|
395 |
|
---|
396 | if (!results.ContainsKey(ErrorPlotResultName)) results.Add(new Result(ErrorPlotResultName, new DataTable(ErrorPlotResultName, "Development of errors during gradient descent")));
|
---|
397 | else results[ErrorPlotResultName].Value = new DataTable(ErrorPlotResultName, "Development of errors during gradient descent");
|
---|
398 |
|
---|
399 | var plot = results[ErrorPlotResultName].Value as DataTable;
|
---|
400 | if (plot == null) throw new ArgumentException("could not create/access error data table in results collection");
|
---|
401 |
|
---|
402 | if (!plot.Rows.ContainsKey("errors")) plot.Rows.Add(new DataRow("errors"));
|
---|
403 | plot.Rows["errors"].Values.Clear();
|
---|
404 | plot.Rows["errors"].VisualProperties.StartIndexZero = true;
|
---|
405 |
|
---|
406 | results.Add(new Result(ScatterPlotResultName, "Plot of the projected data", new ScatterPlot(DataResultName, "")));
|
---|
407 | results.Add(new Result(DataResultName, "Projected Data", new DoubleMatrix()));
|
---|
408 | }
|
---|
409 | }
|
---|
410 |
|
---|
411 | private void Analyze(TSNEStatic<double[]>.TSNEState tsneState) {
|
---|
412 | if (Results == null) return;
|
---|
413 | var results = Results;
|
---|
414 | var plot = results[ErrorPlotResultName].Value as DataTable;
|
---|
415 | if (plot == null) throw new ArgumentException("Could not create/access error data table in results collection.");
|
---|
416 | var errors = plot.Rows["errors"].Values;
|
---|
417 | var c = tsneState.EvaluateError();
|
---|
418 | errors.Add(c);
|
---|
419 | ((IntValue) results[IterationResultName].Value).Value = tsneState.iter;
|
---|
420 | ((DoubleValue) results[ErrorResultName].Value).Value = errors.Last();
|
---|
421 |
|
---|
422 | var ndata = NormalizeProjectedData(tsneState.newData);
|
---|
423 | results[DataResultName].Value = new DoubleMatrix(ndata);
|
---|
424 | var splot = results[ScatterPlotResultName].Value as ScatterPlot;
|
---|
425 | FillScatterPlot(ndata, splot);
|
---|
426 | }
|
---|
427 |
|
---|
428 | private void FillScatterPlot(double[,] lowDimData, ScatterPlot plot) {
|
---|
429 | foreach (var rowName in dataRowNames.Keys) {
|
---|
430 | if (!plot.Rows.ContainsKey(rowName)) {
|
---|
431 | plot.Rows.Add(dataRows.ContainsKey(rowName) ? dataRows[rowName] : new ScatterPlotDataRow(rowName, "", new List<Point2D<double>>()));
|
---|
432 | plot.Rows[rowName].VisualProperties.PointSize = 6;
|
---|
433 | }
|
---|
434 | plot.Rows[rowName].Points.Replace(dataRowNames[rowName].Select(i => new Point2D<double>(lowDimData[i, 0], lowDimData[i, 1])));
|
---|
435 | }
|
---|
436 | }
|
---|
437 |
|
---|
438 | private static double[,] NormalizeProjectedData(double[,] data) {
|
---|
439 | var max = new double[data.GetLength(1)];
|
---|
440 | var min = new double[data.GetLength(1)];
|
---|
441 | var res = new double[data.GetLength(0), data.GetLength(1)];
|
---|
442 | for (var i = 0; i < max.Length; i++) max[i] = min[i] = data[0, i];
|
---|
443 | for (var i = 0; i < data.GetLength(0); i++)
|
---|
444 | for (var j = 0; j < data.GetLength(1); j++) {
|
---|
445 | var v = data[i, j];
|
---|
446 | max[j] = Math.Max(max[j], v);
|
---|
447 | min[j] = Math.Min(min[j], v);
|
---|
448 | }
|
---|
449 | for (var i = 0; i < data.GetLength(0); i++) {
|
---|
450 | for (var j = 0; j < data.GetLength(1); j++) {
|
---|
451 | var d = max[j] - min[j];
|
---|
452 | var s = data[i, j] - (max[j] + min[j]) / 2; //shift data
|
---|
453 | if (d.IsAlmost(0)) res[i, j] = data[i, j]; //no scaling possible
|
---|
454 | else res[i, j] = s / d; //scale data
|
---|
455 | }
|
---|
456 | }
|
---|
457 | return res;
|
---|
458 | }
|
---|
459 |
|
---|
460 | private static double[][] NormalizeInputData(IReadOnlyList<IReadOnlyList<double>> data) {
|
---|
461 | // as in tSNE implementation by van der Maaten
|
---|
462 | var n = data[0].Count;
|
---|
463 | var mean = new double[n];
|
---|
464 | var max = new double[n];
|
---|
465 | var nData = new double[data.Count][];
|
---|
466 | for (var i = 0; i < n; i++) {
|
---|
467 | mean[i] = Enumerable.Range(0, data.Count).Select(x => data[x][i]).Average();
|
---|
468 | max[i] = Enumerable.Range(0, data.Count).Max(x => Math.Abs(data[x][i]));
|
---|
469 | }
|
---|
470 | for (var i = 0; i < data.Count; i++) {
|
---|
471 | nData[i] = new double[n];
|
---|
472 | 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];
|
---|
473 | }
|
---|
474 | return nData;
|
---|
475 | }
|
---|
476 |
|
---|
477 | private static Color GetHeatMapColor(int contourNr, int noContours) {
|
---|
478 | return ConvertTotalToRgb(0, noContours, contourNr);
|
---|
479 | }
|
---|
480 |
|
---|
481 | private static void CreateClusters(IDataset data, string target, int contours, out IClusteringModel contourCluster, out Dictionary<int, string> contourNames, out double[][] borders) {
|
---|
482 | var cpd = new ClusteringProblemData((Dataset) data, new[] {target});
|
---|
483 | contourCluster = KMeansClustering.CreateKMeansSolution(cpd, contours, 3).Model;
|
---|
484 |
|
---|
485 | borders = Enumerable.Range(0, contours).Select(x => new[] {double.MaxValue, double.MinValue}).ToArray();
|
---|
486 | var clusters = contourCluster.GetClusterValues(cpd.Dataset, cpd.AllIndices).ToArray();
|
---|
487 | var targetvalues = cpd.Dataset.GetDoubleValues(target).ToArray();
|
---|
488 | foreach (var i in cpd.AllIndices) {
|
---|
489 | var cl = clusters[i] - 1;
|
---|
490 | var clv = targetvalues[i];
|
---|
491 | if (borders[cl][0] > clv) borders[cl][0] = clv;
|
---|
492 | if (borders[cl][1] < clv) borders[cl][1] = clv;
|
---|
493 | }
|
---|
494 |
|
---|
495 | contourNames = new Dictionary<int, string>();
|
---|
496 | for (var i = 0; i < contours; i++)
|
---|
497 | contourNames.Add(i, "[" + borders[i][0] + ";" + borders[i][1] + "]");
|
---|
498 | }
|
---|
499 |
|
---|
500 | private static Color ConvertTotalToRgb(double low, double high, double cell) {
|
---|
501 | var range = high - low;
|
---|
502 | var h = cell / range;
|
---|
503 | return HsVtoRgb(h * 0.5, 1.0f, 1.0f);
|
---|
504 | }
|
---|
505 |
|
---|
506 | private static Color HsVtoRgb(double hue, double saturation, double value) {
|
---|
507 | while (hue > 1f) { hue -= 1f; }
|
---|
508 | while (hue < 0f) { hue += 1f; }
|
---|
509 | while (saturation > 1f) { saturation -= 1f; }
|
---|
510 | while (saturation < 0f) { saturation += 1f; }
|
---|
511 | while (value > 1f) { value -= 1f; }
|
---|
512 | while (value < 0f) { value += 1f; }
|
---|
513 | if (hue > 0.999f) { hue = 0.999f; }
|
---|
514 | if (hue < 0.001f) { hue = 0.001f; }
|
---|
515 | if (saturation > 0.999f) { saturation = 0.999f; }
|
---|
516 | if (saturation < 0.001f) { return Color.FromArgb((int) (value * 255f), (int) (value * 255f), (int) (value * 255f)); }
|
---|
517 | if (value > 0.999f) { value = 0.999f; }
|
---|
518 | if (value < 0.001f) { value = 0.001f; }
|
---|
519 |
|
---|
520 | var h6 = hue * 6f;
|
---|
521 | if (h6.IsAlmost(6f)) { h6 = 0f; }
|
---|
522 | var ihue = (int) h6;
|
---|
523 | var p = value * (1f - saturation);
|
---|
524 | var q = value * (1f - saturation * (h6 - ihue));
|
---|
525 | var t = value * (1f - saturation * (1f - (h6 - ihue)));
|
---|
526 | switch (ihue) {
|
---|
527 | case 0:
|
---|
528 | return Color.FromArgb((int) (value * 255), (int) (t * 255), (int) (p * 255));
|
---|
529 | case 1:
|
---|
530 | return Color.FromArgb((int) (q * 255), (int) (value * 255), (int) (p * 255));
|
---|
531 | case 2:
|
---|
532 | return Color.FromArgb((int) (p * 255), (int) (value * 255), (int) (t * 255));
|
---|
533 | case 3:
|
---|
534 | return Color.FromArgb((int) (p * 255), (int) (q * 255), (int) (value * 255));
|
---|
535 | case 4:
|
---|
536 | return Color.FromArgb((int) (t * 255), (int) (p * 255), (int) (value * 255));
|
---|
537 | default:
|
---|
538 | return Color.FromArgb((int) (value * 255), (int) (p * 255), (int) (q * 255));
|
---|
539 | }
|
---|
540 | }
|
---|
541 | #endregion
|
---|
542 | }
|
---|
543 | } |
---|