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.Encodings.RealVectorEncoding;
|
---|
32 | using HeuristicLab.Optimization;
|
---|
33 | using HeuristicLab.Parameters;
|
---|
34 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
35 | using HeuristicLab.Problems.DataAnalysis;
|
---|
36 | using HeuristicLab.Random;
|
---|
37 |
|
---|
38 | namespace HeuristicLab.Algorithms.DataAnalysis {
|
---|
39 | /// <summary>
|
---|
40 | /// Linear regression data analysis algorithm.
|
---|
41 | /// </summary>
|
---|
42 | [Item("TSNE", "t-distributed stochastic neighbourhood embedding projects the data in a low dimensional space to allow visual cluster identification")]
|
---|
43 | [Creatable(CreatableAttribute.Categories.DataAnalysis, Priority = 100)]
|
---|
44 | [StorableClass]
|
---|
45 | public sealed class TSNEAnalysis : BasicAlgorithm {
|
---|
46 | public override bool SupportsPause
|
---|
47 | {
|
---|
48 | get { return false; }
|
---|
49 | }
|
---|
50 | public override Type ProblemType
|
---|
51 | {
|
---|
52 | get { return typeof(IDataAnalysisProblem); }
|
---|
53 | }
|
---|
54 | public new IDataAnalysisProblem Problem
|
---|
55 | {
|
---|
56 | get { return (IDataAnalysisProblem)base.Problem; }
|
---|
57 | set { base.Problem = value; }
|
---|
58 | }
|
---|
59 |
|
---|
60 | #region Parameternames
|
---|
61 | private const string DistanceParameterName = "DistanceFunction";
|
---|
62 | private const string PerplexityParameterName = "Perplexity";
|
---|
63 | private const string ThetaParameterName = "Theta";
|
---|
64 | private const string NewDimensionsParameterName = "Dimensions";
|
---|
65 | private const string MaxIterationsParameterName = "MaxIterations";
|
---|
66 | private const string StopLyingIterationParameterName = "StopLyingIteration";
|
---|
67 | private const string MomentumSwitchIterationParameterName = "MomentumSwitchIteration";
|
---|
68 | private const string InitialMomentumParameterName = "InitialMomentum";
|
---|
69 | private const string FinalMomentumParameterName = "FinalMomentum";
|
---|
70 | private const string EtaParameterName = "Eta";
|
---|
71 | private const string SetSeedRandomlyParameterName = "SetSeedRandomly";
|
---|
72 | private const string SeedParameterName = "Seed";
|
---|
73 | private const string ClassesParameterName = "ClassNames";
|
---|
74 | private const string NormalizationParameterName = "Normalization";
|
---|
75 | #endregion
|
---|
76 |
|
---|
77 | #region Parameterproperties
|
---|
78 | public IFixedValueParameter<DoubleValue> PerplexityParameter
|
---|
79 | {
|
---|
80 | get { return Parameters[PerplexityParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
81 | }
|
---|
82 | public OptionalValueParameter<DoubleValue> ThetaParameter
|
---|
83 | {
|
---|
84 | get { return Parameters[ThetaParameterName] as OptionalValueParameter<DoubleValue>; }
|
---|
85 | }
|
---|
86 | public IFixedValueParameter<IntValue> NewDimensionsParameter
|
---|
87 | {
|
---|
88 | get { return Parameters[NewDimensionsParameterName] as IFixedValueParameter<IntValue>; }
|
---|
89 | }
|
---|
90 | public IValueParameter<IDistance<RealVector>> DistanceParameter
|
---|
91 | {
|
---|
92 | get { return Parameters[DistanceParameterName] as IValueParameter<IDistance<RealVector>>; }
|
---|
93 | }
|
---|
94 | public IFixedValueParameter<IntValue> MaxIterationsParameter
|
---|
95 | {
|
---|
96 | get { return Parameters[MaxIterationsParameterName] as IFixedValueParameter<IntValue>; }
|
---|
97 | }
|
---|
98 | public IFixedValueParameter<IntValue> StopLyingIterationParameter
|
---|
99 | {
|
---|
100 | get { return Parameters[StopLyingIterationParameterName] as IFixedValueParameter<IntValue>; }
|
---|
101 | }
|
---|
102 | public IFixedValueParameter<IntValue> MomentumSwitchIterationParameter
|
---|
103 | {
|
---|
104 | get { return Parameters[MomentumSwitchIterationParameterName] as IFixedValueParameter<IntValue>; }
|
---|
105 | }
|
---|
106 | public IFixedValueParameter<DoubleValue> InitialMomentumParameter
|
---|
107 | {
|
---|
108 | get { return Parameters[InitialMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
109 | }
|
---|
110 | public IFixedValueParameter<DoubleValue> FinalMomentumParameter
|
---|
111 | {
|
---|
112 | get { return Parameters[FinalMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
113 | }
|
---|
114 | public IFixedValueParameter<DoubleValue> EtaParameter
|
---|
115 | {
|
---|
116 | get { return Parameters[EtaParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
117 | }
|
---|
118 | public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter
|
---|
119 | {
|
---|
120 | get { return Parameters[SetSeedRandomlyParameterName] as IFixedValueParameter<BoolValue>; }
|
---|
121 | }
|
---|
122 | public IFixedValueParameter<IntValue> SeedParameter
|
---|
123 | {
|
---|
124 | get { return Parameters[SeedParameterName] as IFixedValueParameter<IntValue>; }
|
---|
125 | }
|
---|
126 | public IFixedValueParameter<StringValue> ClassesParameter
|
---|
127 | {
|
---|
128 | get { return Parameters[ClassesParameterName] as IFixedValueParameter<StringValue>; }
|
---|
129 | }
|
---|
130 | public IFixedValueParameter<BoolValue> NormalizationParameter
|
---|
131 | {
|
---|
132 | get { return Parameters[NormalizationParameterName] as IFixedValueParameter<BoolValue>; }
|
---|
133 | }
|
---|
134 | #endregion
|
---|
135 |
|
---|
136 | #region Properties
|
---|
137 | public IDistance<RealVector> Distance
|
---|
138 | {
|
---|
139 | get { return DistanceParameter.Value; }
|
---|
140 | }
|
---|
141 | public double Perplexity
|
---|
142 | {
|
---|
143 | get { return PerplexityParameter.Value.Value; }
|
---|
144 | }
|
---|
145 | public double Theta
|
---|
146 | {
|
---|
147 | get { return ThetaParameter.Value == null ? 0 : ThetaParameter.Value.Value; }
|
---|
148 | }
|
---|
149 | public int NewDimensions
|
---|
150 | {
|
---|
151 | get { return NewDimensionsParameter.Value.Value; }
|
---|
152 | }
|
---|
153 | public int MaxIterations
|
---|
154 | {
|
---|
155 | get { return MaxIterationsParameter.Value.Value; }
|
---|
156 | }
|
---|
157 | public int StopLyingIteration
|
---|
158 | {
|
---|
159 | get { return StopLyingIterationParameter.Value.Value; }
|
---|
160 | }
|
---|
161 | public int MomentumSwitchIteration
|
---|
162 | {
|
---|
163 | get { return MomentumSwitchIterationParameter.Value.Value; }
|
---|
164 | }
|
---|
165 | public double InitialMomentum
|
---|
166 | {
|
---|
167 | get { return InitialMomentumParameter.Value.Value; }
|
---|
168 | }
|
---|
169 | public double FinalMomentum
|
---|
170 | {
|
---|
171 | get { return FinalMomentumParameter.Value.Value; }
|
---|
172 | }
|
---|
173 | public double Eta
|
---|
174 | {
|
---|
175 | get
|
---|
176 | {
|
---|
177 | return EtaParameter.Value == null ? 0 : EtaParameter.Value.Value;
|
---|
178 | }
|
---|
179 | }
|
---|
180 | public bool SetSeedRandomly
|
---|
181 | {
|
---|
182 | get { return SetSeedRandomlyParameter.Value.Value; }
|
---|
183 | }
|
---|
184 | public uint Seed
|
---|
185 | {
|
---|
186 | get { return (uint)SeedParameter.Value.Value; }
|
---|
187 | }
|
---|
188 | public string Classes
|
---|
189 | {
|
---|
190 | get { return ClassesParameter.Value.Value; }
|
---|
191 | }
|
---|
192 | public bool Normalization
|
---|
193 | {
|
---|
194 | get { return NormalizationParameter.Value.Value; }
|
---|
195 | }
|
---|
196 | [Storable]
|
---|
197 | public TSNE<RealVector> tsne;
|
---|
198 | #endregion
|
---|
199 |
|
---|
200 | #region Constructors & Cloning
|
---|
201 | [StorableConstructor]
|
---|
202 | private TSNEAnalysis(bool deserializing) : base(deserializing) { }
|
---|
203 | private TSNEAnalysis(TSNEAnalysis original, Cloner cloner) : base(original, cloner) { }
|
---|
204 | public override IDeepCloneable Clone(Cloner cloner) { return new TSNEAnalysis(this, cloner); }
|
---|
205 | public TSNEAnalysis() {
|
---|
206 | Problem = new RegressionProblem();
|
---|
207 | Parameters.Add(new ValueParameter<IDistance<RealVector>>(DistanceParameterName, "The distance function used to differentiate similar from non-similar points", new EuclidianDistance()));
|
---|
208 | 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)));
|
---|
209 | Parameters.Add(new OptionalValueParameter<DoubleValue>(ThetaParameterName, "Value describing how much appoximated gradients my differ from exact gradients. Set to 0 for exact calculation and in [0,1] otherwise \n CAUTION: exact calculation of forces requires building a non-sparse N*N matrix where N is the number of data points\n This may exceed memory limitations", new DoubleValue(0.1)));
|
---|
210 | Parameters.Add(new FixedValueParameter<IntValue>(NewDimensionsParameterName, "Dimensionality of projected space (usually 2 for easy visual analysis", new IntValue(2)));
|
---|
211 | Parameters.Add(new FixedValueParameter<IntValue>(MaxIterationsParameterName, "Maximum number of iterations for gradient descent", new IntValue(1000)));
|
---|
212 | Parameters.Add(new FixedValueParameter<IntValue>(StopLyingIterationParameterName, "Number of iterations after which p is no longer approximated", new IntValue(0)));
|
---|
213 | Parameters.Add(new FixedValueParameter<IntValue>(MomentumSwitchIterationParameterName, "Number of iterations after which the momentum in the gradient descent is switched", new IntValue(0)));
|
---|
214 | Parameters.Add(new FixedValueParameter<DoubleValue>(InitialMomentumParameterName, "The initial momentum in the gradient descent", new DoubleValue(0.5)));
|
---|
215 | Parameters.Add(new FixedValueParameter<DoubleValue>(FinalMomentumParameterName, "The final momentum", new DoubleValue(0.8)));
|
---|
216 | Parameters.Add(new FixedValueParameter<DoubleValue>(EtaParameterName, "Gradient Descent learning rate", new DoubleValue(200)));
|
---|
217 | Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "If the seed should be random", new BoolValue(true)));
|
---|
218 | Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The seed used if it should not be random", new IntValue(0)));
|
---|
219 | Parameters.Add(new FixedValueParameter<StringValue>(ClassesParameterName, "name of the column specifying the class lables of each data point. \n if the lable column can not be found Training/Test is used as labels", new StringValue("none")));
|
---|
220 | Parameters.Add(new FixedValueParameter<BoolValue>(NormalizationParameterName, "Wether the data should be zero centered and have variance of 1 for each variable, so different scalings are ignored", new BoolValue(true)));
|
---|
221 |
|
---|
222 | MomentumSwitchIterationParameter.Hidden = true;
|
---|
223 | InitialMomentumParameter.Hidden = true;
|
---|
224 | FinalMomentumParameter.Hidden = true;
|
---|
225 | StopLyingIterationParameter.Hidden = true;
|
---|
226 | EtaParameter.Hidden = true;
|
---|
227 | }
|
---|
228 | #endregion
|
---|
229 |
|
---|
230 | public override void Stop() {
|
---|
231 | base.Stop();
|
---|
232 | if (tsne != null) tsne.Running = false;
|
---|
233 | }
|
---|
234 |
|
---|
235 | protected override void Run(CancellationToken cancellationToken) {
|
---|
236 | var dataRowNames = new Dictionary<string, List<int>>();
|
---|
237 | var rows = new Dictionary<string, ScatterPlotDataRow>();
|
---|
238 | var problemData = Problem.ProblemData;
|
---|
239 |
|
---|
240 | //color datapoints acording to Classes-Variable (be it double or string)
|
---|
241 | if (problemData.Dataset.VariableNames.Contains(Classes)) {
|
---|
242 | if ((problemData.Dataset as Dataset).VariableHasType<string>(Classes)) {
|
---|
243 | var classes = problemData.Dataset.GetStringValues(Classes).ToArray();
|
---|
244 | for (var i = 0; i < classes.Length; i++) {
|
---|
245 | if (!dataRowNames.ContainsKey(classes[i])) dataRowNames.Add(classes[i], new List<int>());
|
---|
246 | dataRowNames[classes[i]].Add(i);
|
---|
247 | }
|
---|
248 | } else if ((problemData.Dataset as Dataset).VariableHasType<double>(Classes)) {
|
---|
249 | var classValues = problemData.Dataset.GetDoubleValues(Classes).ToArray();
|
---|
250 | var max = classValues.Max() + 0.1;
|
---|
251 | var min = classValues.Min() - 0.1;
|
---|
252 | const int contours = 8;
|
---|
253 | for (var i = 0; i < contours; i++) {
|
---|
254 | var contourname = GetContourName(i, min, max, contours);
|
---|
255 | dataRowNames.Add(contourname, new List<int>());
|
---|
256 | rows.Add(contourname, new ScatterPlotDataRow(contourname, "", new List<Point2D<double>>()));
|
---|
257 | rows[contourname].VisualProperties.Color = GetHeatMapColor(i, contours);
|
---|
258 | rows[contourname].VisualProperties.PointSize = i + 3;
|
---|
259 | }
|
---|
260 | for (var i = 0; i < classValues.Length; i++) {
|
---|
261 | dataRowNames[GetContourName(classValues[i], min, max, contours)].Add(i);
|
---|
262 | }
|
---|
263 | }
|
---|
264 | } else {
|
---|
265 | dataRowNames.Add("Training", problemData.TrainingIndices.ToList());
|
---|
266 | dataRowNames.Add("Test", problemData.TestIndices.ToList());
|
---|
267 | }
|
---|
268 |
|
---|
269 | //Set up and run TSNE
|
---|
270 | if (SetSeedRandomly) SeedParameter.Value.Value = new System.Random().Next();
|
---|
271 | var random = new MersenneTwister(Seed);
|
---|
272 | tsne = new TSNE<RealVector>(Distance, random, Results, MaxIterations, StopLyingIteration, MomentumSwitchIteration, InitialMomentum, FinalMomentum, Eta, dataRowNames, rows);
|
---|
273 | var dataset = problemData.Dataset;
|
---|
274 | var allowedInputVariables = problemData.AllowedInputVariables.ToArray();
|
---|
275 | var data = new RealVector[dataset.Rows];
|
---|
276 | for (var row = 0; row < dataset.Rows; row++) data[row] = new RealVector(allowedInputVariables.Select(col => dataset.GetDoubleValue(col, row)).ToArray());
|
---|
277 | if (Normalization) data = NormalizeData(data);
|
---|
278 | tsne.Run(data, NewDimensions, Perplexity, Theta);
|
---|
279 | }
|
---|
280 |
|
---|
281 | private static RealVector[] NormalizeData(IReadOnlyList<RealVector> data) {
|
---|
282 | var n = data[0].Length;
|
---|
283 | var mean = new double[n];
|
---|
284 | var sd = new double[n];
|
---|
285 | var nData = new RealVector[data.Count];
|
---|
286 | for (var i = 0; i < n; i++) {
|
---|
287 | var i1 = i;
|
---|
288 | sd[i] = Enumerable.Range(0, data.Count).Select(x => data[x][i1]).StandardDeviation();
|
---|
289 | mean[i] = Enumerable.Range(0, data.Count).Select(x => data[x][i1]).Average();
|
---|
290 | }
|
---|
291 | for (var i = 0; i < data.Count; i++) {
|
---|
292 | nData[i] = new RealVector(n);
|
---|
293 | for (var j = 0; j < n; j++) nData[i][j] = (data[i][j] - mean[j]) / sd[j];
|
---|
294 | }
|
---|
295 | return nData;
|
---|
296 | }
|
---|
297 | private static Color GetHeatMapColor(int contourNr, int noContours) {
|
---|
298 | var q = (double)contourNr / noContours; // q in [0,1]
|
---|
299 | var c = q < 0.5 ? Color.FromArgb((int)(q * 2 * 255), 255, 0) : Color.FromArgb(255, (int)((1 - q) * 2 * 255), 0);
|
---|
300 | return c;
|
---|
301 | }
|
---|
302 | private static string GetContourName(double value, double min, double max, int noContours) {
|
---|
303 | var size = (max - min) / noContours;
|
---|
304 | var contourNr = (int)((value - min) / size);
|
---|
305 | return GetContourName(contourNr, min, max, noContours);
|
---|
306 | }
|
---|
307 | private static string GetContourName(int i, double min, double max, int noContours) {
|
---|
308 | var size = (max - min) / noContours;
|
---|
309 | return "[" + (min + i * size) + ";" + (min + (i + 1) * size) + ")";
|
---|
310 | }
|
---|
311 |
|
---|
312 | }
|
---|
313 | }
|
---|