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 | /// 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.")]
|
---|
45 | [Creatable(CreatableAttribute.Categories.DataAnalysis, Priority = 100)]
|
---|
46 | [StorableClass]
|
---|
47 | public sealed class TSNEAlgorithm : BasicAlgorithm {
|
---|
48 | public override bool SupportsPause {
|
---|
49 | get { return false; }
|
---|
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 DistanceParameterName = "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 ClassesParameterName = "ClassNames";
|
---|
73 | private const string NormalizationParameterName = "Normalization";
|
---|
74 | #endregion
|
---|
75 |
|
---|
76 | #region parameter properties
|
---|
77 | public IFixedValueParameter<DoubleValue> PerplexityParameter {
|
---|
78 | get { return Parameters[PerplexityParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
79 | }
|
---|
80 | public IFixedValueParameter<DoubleValue> ThetaParameter {
|
---|
81 | get { return Parameters[ThetaParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
82 | }
|
---|
83 | public IFixedValueParameter<IntValue> NewDimensionsParameter {
|
---|
84 | get { return Parameters[NewDimensionsParameterName] as IFixedValueParameter<IntValue>; }
|
---|
85 | }
|
---|
86 | public IValueParameter<IDistance<double[]>> DistanceParameter {
|
---|
87 | get { return Parameters[DistanceParameterName] as IValueParameter<IDistance<double[]>>; }
|
---|
88 | }
|
---|
89 | public IFixedValueParameter<IntValue> MaxIterationsParameter {
|
---|
90 | get { return Parameters[MaxIterationsParameterName] as IFixedValueParameter<IntValue>; }
|
---|
91 | }
|
---|
92 | public IFixedValueParameter<IntValue> StopLyingIterationParameter {
|
---|
93 | get { return Parameters[StopLyingIterationParameterName] as IFixedValueParameter<IntValue>; }
|
---|
94 | }
|
---|
95 | public IFixedValueParameter<IntValue> MomentumSwitchIterationParameter {
|
---|
96 | get { return Parameters[MomentumSwitchIterationParameterName] as IFixedValueParameter<IntValue>; }
|
---|
97 | }
|
---|
98 | public IFixedValueParameter<DoubleValue> InitialMomentumParameter {
|
---|
99 | get { return Parameters[InitialMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
100 | }
|
---|
101 | public IFixedValueParameter<DoubleValue> FinalMomentumParameter {
|
---|
102 | get { return Parameters[FinalMomentumParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
103 | }
|
---|
104 | public IFixedValueParameter<DoubleValue> EtaParameter {
|
---|
105 | get { return Parameters[EtaParameterName] as IFixedValueParameter<DoubleValue>; }
|
---|
106 | }
|
---|
107 | public IFixedValueParameter<BoolValue> SetSeedRandomlyParameter {
|
---|
108 | get { return Parameters[SetSeedRandomlyParameterName] as IFixedValueParameter<BoolValue>; }
|
---|
109 | }
|
---|
110 | public IFixedValueParameter<IntValue> SeedParameter {
|
---|
111 | get { return Parameters[SeedParameterName] as IFixedValueParameter<IntValue>; }
|
---|
112 | }
|
---|
113 | public IFixedValueParameter<StringValue> ClassesParameter {
|
---|
114 | get { return Parameters[ClassesParameterName] as IFixedValueParameter<StringValue>; }
|
---|
115 | }
|
---|
116 | public IFixedValueParameter<BoolValue> NormalizationParameter {
|
---|
117 | get { return Parameters[NormalizationParameterName] as IFixedValueParameter<BoolValue>; }
|
---|
118 | }
|
---|
119 | #endregion
|
---|
120 |
|
---|
121 | #region Properties
|
---|
122 | public IDistance<double[]> Distance {
|
---|
123 | get { return DistanceParameter.Value; }
|
---|
124 | }
|
---|
125 | public double Perplexity {
|
---|
126 | get { return PerplexityParameter.Value.Value; }
|
---|
127 | set { PerplexityParameter.Value.Value = value; }
|
---|
128 | }
|
---|
129 | public double Theta {
|
---|
130 | get { return ThetaParameter.Value.Value; }
|
---|
131 | set { ThetaParameter.Value.Value = value; }
|
---|
132 | }
|
---|
133 | public int NewDimensions {
|
---|
134 | get { return NewDimensionsParameter.Value.Value; }
|
---|
135 | set { NewDimensionsParameter.Value.Value = value; }
|
---|
136 | }
|
---|
137 | public int MaxIterations {
|
---|
138 | get { return MaxIterationsParameter.Value.Value; }
|
---|
139 | set { MaxIterationsParameter.Value.Value = value; }
|
---|
140 | }
|
---|
141 | public int StopLyingIteration {
|
---|
142 | get { return StopLyingIterationParameter.Value.Value; }
|
---|
143 | set { StopLyingIterationParameter.Value.Value = value; }
|
---|
144 | }
|
---|
145 | public int MomentumSwitchIteration {
|
---|
146 | get { return MomentumSwitchIterationParameter.Value.Value; }
|
---|
147 | set { MomentumSwitchIterationParameter.Value.Value = value; }
|
---|
148 | }
|
---|
149 | public double InitialMomentum {
|
---|
150 | get { return InitialMomentumParameter.Value.Value; }
|
---|
151 | set { InitialMomentumParameter.Value.Value = value; }
|
---|
152 | }
|
---|
153 | public double FinalMomentum {
|
---|
154 | get { return FinalMomentumParameter.Value.Value; }
|
---|
155 | set { FinalMomentumParameter.Value.Value = value; }
|
---|
156 | }
|
---|
157 | public double Eta {
|
---|
158 | get { return EtaParameter.Value.Value; }
|
---|
159 | set { EtaParameter.Value.Value = value; }
|
---|
160 | }
|
---|
161 | public bool SetSeedRandomly {
|
---|
162 | get { return SetSeedRandomlyParameter.Value.Value; }
|
---|
163 | set { SetSeedRandomlyParameter.Value.Value = value; }
|
---|
164 | }
|
---|
165 | public int Seed {
|
---|
166 | get { return SeedParameter.Value.Value; }
|
---|
167 | set { SeedParameter.Value.Value = value; }
|
---|
168 | }
|
---|
169 | public string Classes {
|
---|
170 | get { return ClassesParameter.Value.Value; }
|
---|
171 | set { ClassesParameter.Value.Value = value; }
|
---|
172 | }
|
---|
173 | public bool Normalization {
|
---|
174 | get { return NormalizationParameter.Value.Value; }
|
---|
175 | set { NormalizationParameter.Value.Value = value; }
|
---|
176 | }
|
---|
177 | [Storable]
|
---|
178 | public TSNE<double[]> tsne;
|
---|
179 | #endregion
|
---|
180 |
|
---|
181 | #region Constructors & Cloning
|
---|
182 | [StorableConstructor]
|
---|
183 | private TSNEAlgorithm(bool deserializing) : base(deserializing) { }
|
---|
184 | private TSNEAlgorithm(TSNEAlgorithm original, Cloner cloner) : base(original, cloner) { }
|
---|
185 | public override IDeepCloneable Clone(Cloner cloner) { return new TSNEAlgorithm(this, cloner); }
|
---|
186 | public TSNEAlgorithm() {
|
---|
187 | Problem = new RegressionProblem();
|
---|
188 | Parameters.Add(new ValueParameter<IDistance<double[]>>(DistanceParameterName, "The distance function used to differentiate similar from non-similar points", new EuclideanDistance()));
|
---|
189 | 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)));
|
---|
190 | Parameters.Add(new FixedValueParameter<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)));
|
---|
191 | Parameters.Add(new FixedValueParameter<IntValue>(NewDimensionsParameterName, "Dimensionality of projected space (usually 2 for easy visual analysis)", new IntValue(2)));
|
---|
192 | Parameters.Add(new FixedValueParameter<IntValue>(MaxIterationsParameterName, "Maximum number of iterations for gradient descent", new IntValue(1000)));
|
---|
193 | Parameters.Add(new FixedValueParameter<IntValue>(StopLyingIterationParameterName, "Number of iterations after which p is no longer approximated", new IntValue(0)));
|
---|
194 | Parameters.Add(new FixedValueParameter<IntValue>(MomentumSwitchIterationParameterName, "Number of iterations after which the momentum in the gradient descent is switched", new IntValue(0)));
|
---|
195 | Parameters.Add(new FixedValueParameter<DoubleValue>(InitialMomentumParameterName, "The initial momentum in the gradient descent", new DoubleValue(0.5)));
|
---|
196 | Parameters.Add(new FixedValueParameter<DoubleValue>(FinalMomentumParameterName, "The final momentum", new DoubleValue(0.8)));
|
---|
197 | Parameters.Add(new FixedValueParameter<DoubleValue>(EtaParameterName, "Gradient descent learning rate", new DoubleValue(200)));
|
---|
198 | Parameters.Add(new FixedValueParameter<BoolValue>(SetSeedRandomlyParameterName, "If the seed should be random", new BoolValue(true)));
|
---|
199 | Parameters.Add(new FixedValueParameter<IntValue>(SeedParameterName, "The seed used if it should not be random", new IntValue(0)));
|
---|
200 | 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")));
|
---|
201 | 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)));
|
---|
202 |
|
---|
203 | MomentumSwitchIterationParameter.Hidden = true;
|
---|
204 | InitialMomentumParameter.Hidden = true;
|
---|
205 | FinalMomentumParameter.Hidden = true;
|
---|
206 | StopLyingIterationParameter.Hidden = true;
|
---|
207 | EtaParameter.Hidden = true;
|
---|
208 | }
|
---|
209 | #endregion
|
---|
210 |
|
---|
211 | public override void Stop() {
|
---|
212 | base.Stop();
|
---|
213 | if (tsne != null) tsne.Running = false;
|
---|
214 | }
|
---|
215 |
|
---|
216 | protected override void Run(CancellationToken cancellationToken) {
|
---|
217 | var dataRowNames = new Dictionary<string, List<int>>();
|
---|
218 | var rows = new Dictionary<string, ScatterPlotDataRow>();
|
---|
219 | var problemData = Problem.ProblemData;
|
---|
220 |
|
---|
221 | //color datapoints acording to classes variable (be it double or string)
|
---|
222 | if (problemData.Dataset.VariableNames.Contains(Classes)) {
|
---|
223 | if ((problemData.Dataset as Dataset).VariableHasType<string>(Classes)) {
|
---|
224 | var classes = problemData.Dataset.GetStringValues(Classes).ToArray();
|
---|
225 | for (var i = 0; i < classes.Length; i++) {
|
---|
226 | if (!dataRowNames.ContainsKey(classes[i])) dataRowNames.Add(classes[i], new List<int>());
|
---|
227 | dataRowNames[classes[i]].Add(i);
|
---|
228 | }
|
---|
229 | } else if ((problemData.Dataset as Dataset).VariableHasType<double>(Classes)) {
|
---|
230 | var classValues = problemData.Dataset.GetDoubleValues(Classes).ToArray();
|
---|
231 | var max = classValues.Max() + 0.1; // TODO consts
|
---|
232 | var min = classValues.Min() - 0.1;
|
---|
233 | const int contours = 8;
|
---|
234 | for (var i = 0; i < contours; i++) {
|
---|
235 | var contourname = GetContourName(i, min, max, contours);
|
---|
236 | dataRowNames.Add(contourname, new List<int>());
|
---|
237 | rows.Add(contourname, new ScatterPlotDataRow(contourname, "", new List<Point2D<double>>()));
|
---|
238 | rows[contourname].VisualProperties.Color = GetHeatMapColor(i, contours);
|
---|
239 | rows[contourname].VisualProperties.PointSize = i + 3;
|
---|
240 | }
|
---|
241 | for (var i = 0; i < classValues.Length; i++) {
|
---|
242 | dataRowNames[GetContourName(classValues[i], min, max, contours)].Add(i);
|
---|
243 | }
|
---|
244 | }
|
---|
245 | } else {
|
---|
246 | dataRowNames.Add("Training", problemData.TrainingIndices.ToList());
|
---|
247 | dataRowNames.Add("Test", problemData.TestIndices.ToList());
|
---|
248 | }
|
---|
249 |
|
---|
250 | // set up and run tSNE
|
---|
251 | if (SetSeedRandomly) Seed = new System.Random().Next();
|
---|
252 | var random = new MersenneTwister((uint)Seed);
|
---|
253 | tsne = new TSNE<double[]>(Distance, random, Results, MaxIterations, StopLyingIteration, MomentumSwitchIteration, InitialMomentum, FinalMomentum, Eta, dataRowNames, rows);
|
---|
254 | var dataset = problemData.Dataset;
|
---|
255 | var allowedInputVariables = problemData.AllowedInputVariables.ToArray();
|
---|
256 | var data = new double[dataset.Rows][];
|
---|
257 | for (var row = 0; row < dataset.Rows; row++) data[row] = allowedInputVariables.Select(col => dataset.GetDoubleValue(col, row)).ToArray();
|
---|
258 | if (Normalization) data = NormalizeData(data);
|
---|
259 | tsne.Run(data, NewDimensions, Perplexity, Theta);
|
---|
260 | }
|
---|
261 |
|
---|
262 | private static double[][] NormalizeData(IReadOnlyList<double[]> data) {
|
---|
263 | var n = data[0].Length;
|
---|
264 | var mean = new double[n];
|
---|
265 | var sd = new double[n];
|
---|
266 | var nData = new double[data.Count][];
|
---|
267 | for (var i = 0; i < n; i++) {
|
---|
268 | var i1 = i;
|
---|
269 | sd[i] = Enumerable.Range(0, data.Count).Select(x => data[x][i1]).StandardDeviation();
|
---|
270 | mean[i] = Enumerable.Range(0, data.Count).Select(x => data[x][i1]).Average();
|
---|
271 | }
|
---|
272 | for (var i = 0; i < data.Count; i++) {
|
---|
273 | nData[i] = new double[n];
|
---|
274 | for (var j = 0; j < n; j++) nData[i][j] = (data[i][j] - mean[j]) / sd[j];
|
---|
275 | }
|
---|
276 | return nData;
|
---|
277 | }
|
---|
278 | private static Color GetHeatMapColor(int contourNr, int noContours) {
|
---|
279 | var q = (double)contourNr / noContours; // q in [0,1]
|
---|
280 | var c = q < 0.5 ? Color.FromArgb((int)(q * 2 * 255), 255, 0) : Color.FromArgb(255, (int)((1 - q) * 2 * 255), 0);
|
---|
281 | return c;
|
---|
282 | }
|
---|
283 | private static string GetContourName(double value, double min, double max, int noContours) {
|
---|
284 | var size = (max - min) / noContours;
|
---|
285 | var contourNr = (int)((value - min) / size);
|
---|
286 | return GetContourName(contourNr, min, max, noContours);
|
---|
287 | }
|
---|
288 | private static string GetContourName(int i, double min, double max, int noContours) {
|
---|
289 | var size = (max - min) / noContours;
|
---|
290 | return "[" + (min + i * size) + ";" + (min + (i + 1) * size) + ")";
|
---|
291 | }
|
---|
292 | }
|
---|
293 | }
|
---|