Free cookie consent management tool by TermsFeed Policy Generator

source: branches/TSNE/HeuristicLab.Algorithms.DataAnalysis/3.4/TSNE/TSNEStatic.cs @ 14855

Last change on this file since 14855 was 14855, checked in by gkronber, 7 years ago

#2700: made some changes / bug-fixes while reviewing

File size: 28.4 KB
RevLine 
[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
21//Code is based on an implementation from Laurens van der Maaten
22
23/*
24*
25* Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology)
26* All rights reserved.
27*
28* Redistribution and use in source and binary forms, with or without
29* modification, are permitted provided that the following conditions are met:
30* 1. Redistributions of source code must retain the above copyright
31*    notice, this list of conditions and the following disclaimer.
32* 2. Redistributions in binary form must reproduce the above copyright
33*    notice, this list of conditions and the following disclaimer in the
34*    documentation and/or other materials provided with the distribution.
35* 3. All advertising materials mentioning features or use of this software
36*    must display the following acknowledgement:
37*    This product includes software developed by the Delft University of Technology.
38* 4. Neither the name of the Delft University of Technology nor the names of
39*    its contributors may be used to endorse or promote products derived from
40*    this software without specific prior written permission.
41*
42* THIS SOFTWARE IS PROVIDED BY LAURENS VAN DER MAATEN ''AS IS'' AND ANY EXPRESS
43* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
44* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
45* EVENT SHALL LAURENS VAN DER MAATEN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
46* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
47* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
48* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
49* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
50* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
51* OF SUCH DAMAGE.
52*
53*/
54#endregion
55
56using System;
57using System.Collections.Generic;
58using System.Linq;
[14785]59using HeuristicLab.Collections;
[14414]60using HeuristicLab.Common;
61using HeuristicLab.Core;
[14807]62using HeuristicLab.Optimization;
[14414]63using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
64using HeuristicLab.Random;
65
66namespace HeuristicLab.Algorithms.DataAnalysis {
67  [StorableClass]
[14807]68  public class TSNEStatic<T> {
[14414]69
[14788]70    [StorableClass]
71    public sealed class TSNEState : DeepCloneable {
72      // initialized once
[14806]73      [Storable]
[14788]74      public IDistance<T> distance;
[14806]75      [Storable]
[14788]76      public IRandom random;
[14806]77      [Storable]
[14788]78      public double perplexity;
[14806]79      [Storable]
[14788]80      public bool exact;
[14806]81      [Storable]
[14788]82      public int noDatapoints;
[14806]83      [Storable]
[14788]84      public double finalMomentum;
[14806]85      [Storable]
[14788]86      public int momSwitchIter;
[14806]87      [Storable]
[14788]88      public int stopLyingIter;
[14806]89      [Storable]
[14788]90      public double theta;
[14806]91      [Storable]
[14788]92      public double eta;
[14806]93      [Storable]
[14788]94      public int newDimensions;
[14414]95
[14788]96      // for approximate version: sparse representation of similarity/distance matrix
[14806]97      [Storable]
[14788]98      public double[] valP; // similarity/distance
[14806]99      [Storable]
[14788]100      public int[] rowP; // row index
[14806]101      [Storable]
[14788]102      public int[] colP; // col index
[14414]103
[14788]104      // for exact version: dense representation of distance/similarity matrix
[14806]105      [Storable]
[14788]106      public double[,] p;
[14512]107
[14788]108      // mapped data
[14806]109      [Storable]
[14788]110      public double[,] newData;
[14414]111
[14806]112      [Storable]
[14788]113      public int iter;
[14806]114      [Storable]
[14788]115      public double currentMomentum;
[14414]116
[14788]117      // helper variables (updated in each iteration)
[14806]118      [Storable]
[14788]119      public double[,] gains;
[14806]120      [Storable]
[14788]121      public double[,] uY;
[14806]122      [Storable]
[14788]123      public double[,] dY;
[14512]124
[14788]125      private TSNEState(TSNEState original, Cloner cloner) : base(original, cloner) {
[14806]126        this.distance = cloner.Clone(original.distance);
127        this.random = cloner.Clone(original.random);
128        this.perplexity = original.perplexity;
129        this.exact = original.exact;
130        this.noDatapoints = original.noDatapoints;
131        this.finalMomentum = original.finalMomentum;
132        this.momSwitchIter = original.momSwitchIter;
133        this.stopLyingIter = original.stopLyingIter;
134        this.theta = original.theta;
135        this.eta = original.eta;
136        this.newDimensions = original.newDimensions;
137        if(original.valP != null) {
138          this.valP = new double[original.valP.Length];
139          Array.Copy(original.valP, this.valP, this.valP.Length);
140        }
141        if(original.rowP != null) {
142          this.rowP = new int[original.rowP.Length];
143          Array.Copy(original.rowP, this.rowP, this.rowP.Length);
144        }
145        if(original.colP != null) {
146          this.colP = new int[original.colP.Length];
147          Array.Copy(original.colP, this.colP, this.colP.Length);
148        }
149        if(original.p != null) {
150          this.p = new double[original.p.GetLength(0), original.p.GetLength(1)];
151          Array.Copy(original.p, this.p, this.p.Length);
152        }
153        this.newData = new double[original.newData.GetLength(0), original.newData.GetLength(1)];
154        Array.Copy(original.newData, this.newData, this.newData.Length);
155        this.iter = original.iter;
156        this.currentMomentum = original.currentMomentum;
157        this.gains = new double[original.gains.GetLength(0), original.gains.GetLength(1)];
158        Array.Copy(original.gains, this.gains, this.gains.Length);
159        this.uY = new double[original.uY.GetLength(0), original.uY.GetLength(1)];
160        Array.Copy(original.uY, this.uY, this.uY.Length);
161        this.dY = new double[original.dY.GetLength(0), original.dY.GetLength(1)];
162        Array.Copy(original.dY, this.dY, this.dY.Length);
[14788]163      }
[14806]164
[14788]165      public override IDeepCloneable Clone(Cloner cloner) {
166        return new TSNEState(this, cloner);
167      }
[14414]168
[14807]169      [StorableConstructor]
[14837]170      public TSNEState(bool deserializing) { }
[14788]171      public TSNEState(T[] data, IDistance<T> distance, IRandom random, int newDimensions, double perplexity, double theta, int stopLyingIter, int momSwitchIter, double momentum, double finalMomentum, double eta) {
172        this.distance = distance;
173        this.random = random;
174        this.newDimensions = newDimensions;
175        this.perplexity = perplexity;
176        this.theta = theta;
177        this.stopLyingIter = stopLyingIter;
178        this.momSwitchIter = momSwitchIter;
179        this.currentMomentum = momentum;
180        this.finalMomentum = finalMomentum;
181        this.eta = eta;
[14414]182
183
[14788]184        // initialize
185        noDatapoints = data.Length;
[14806]186        if(noDatapoints - 1 < 3 * perplexity)
187          throw new ArgumentException("Perplexity too large for the number of data points!");
[14788]188
189        exact = Math.Abs(theta) < double.Epsilon;
190        newData = new double[noDatapoints, newDimensions];
191        dY = new double[noDatapoints, newDimensions];
192        uY = new double[noDatapoints, newDimensions];
193        gains = new double[noDatapoints, newDimensions];
[14806]194        for(var i = 0; i < noDatapoints; i++)
195          for(var j = 0; j < newDimensions; j++)
[14788]196            gains[i, j] = 1.0;
197
198        p = null;
199        rowP = null;
200        colP = null;
201        valP = null;
202
203        //Calculate Similarities
[14806]204        if(exact) p = CalculateExactSimilarites(data, distance, perplexity);
[14788]205        else CalculateApproximateSimilarities(data, distance, perplexity, out rowP, out colP, out valP);
206
[14837]207        // Lie about the P-values (factor is 4 in the MATLAB implementation)
[14806]208        if(exact) for(var i = 0; i < noDatapoints; i++) for(var j = 0; j < noDatapoints; j++) p[i, j] *= 12.0;
209        else for(var i = 0; i < rowP[noDatapoints]; i++) valP[i] *= 12.0;
[14788]210
211        // Initialize solution (randomly)
212        var rand = new NormalDistributedRandom(random, 0, 1);
[14806]213        for(var i = 0; i < noDatapoints; i++)
214          for(var j = 0; j < newDimensions; j++)
[14837]215            newData[i, j] = rand.NextDouble() * .0001;
[14414]216      }
217
[14788]218      public double EvaluateError() {
[14806]219        return exact ?
220          EvaluateErrorExact(p, newData, noDatapoints, newDimensions) :
221          EvaluateErrorApproximate(rowP, colP, valP, newData, theta);
[14788]222      }
[14512]223
[14788]224      private static void CalculateApproximateSimilarities(T[] data, IDistance<T> distance, double perplexity, out int[] rowP, out int[] colP, out double[] valP) {
225        // Compute asymmetric pairwise input similarities
[14837]226        ComputeGaussianPerplexity(data, distance, out rowP, out colP, out valP, perplexity, (int)(3 * perplexity));
[14788]227        // Symmetrize input similarities
228        int[] sRowP, symColP;
229        double[] sValP;
230        SymmetrizeMatrix(rowP, colP, valP, out sRowP, out symColP, out sValP);
231        rowP = sRowP;
232        colP = symColP;
233        valP = sValP;
234        var sumP = .0;
[14806]235        for(var i = 0; i < rowP[data.Length]; i++) sumP += valP[i];
236        for(var i = 0; i < rowP[data.Length]; i++) valP[i] /= sumP;
[14788]237      }
[14806]238
[14788]239      private static double[,] CalculateExactSimilarites(T[] data, IDistance<T> distance, double perplexity) {
240        // Compute similarities
241        var p = new double[data.Length, data.Length];
242        ComputeGaussianPerplexity(data, distance, p, perplexity);
243        // Symmetrize input similarities
[14806]244        for(var n = 0; n < data.Length; n++) {
245          for(var m = n + 1; m < data.Length; m++) {
[14788]246            p[n, m] += p[m, n];
247            p[m, n] = p[n, m];
248          }
249        }
250        var sumP = .0;
[14806]251        for(var i = 0; i < data.Length; i++) for(var j = 0; j < data.Length; j++) sumP += p[i, j];
252        for(var i = 0; i < data.Length; i++) for(var j = 0; j < data.Length; j++) p[i, j] /= sumP;
[14788]253        return p;
254      }
[14742]255
[14788]256      private static void ComputeGaussianPerplexity(IReadOnlyList<T> x, IDistance<T> distance, out int[] rowP, out int[] colP, out double[] valP, double perplexity, int k) {
[14806]257        if(perplexity > k) throw new ArgumentException("Perplexity should be lower than k!");
[14512]258
[14788]259        int n = x.Count;
260        // Allocate the memory we need
261        rowP = new int[n + 1];
262        colP = new int[n * k];
263        valP = new double[n * k];
264        var curP = new double[n - 1];
265        rowP[0] = 0;
[14806]266        for(var i = 0; i < n; i++) rowP[i + 1] = rowP[i] + k;
[14512]267
[14788]268        var objX = new List<IndexedItem<T>>();
[14806]269        for(var i = 0; i < n; i++) objX.Add(new IndexedItem<T>(i, x[i]));
[14512]270
[14788]271        // Build ball tree on data set
[14837]272        var tree = new VantagePointTree<IndexedItem<T>>(new IndexedItemDistance<T>(distance), objX);
[14742]273
[14788]274        // Loop over all points to find nearest neighbors
[14806]275        for(var i = 0; i < n; i++) {
[14788]276          IList<IndexedItem<T>> indices;
277          IList<double> distances;
[14742]278
[14788]279          // Find nearest neighbors
280          tree.Search(objX[i], k + 1, out indices, out distances);
[14512]281
[14788]282          // Initialize some variables for binary search
283          var found = false;
284          var beta = 1.0;
285          var minBeta = double.MinValue;
286          var maxBeta = double.MaxValue;
[14855]287          const double tol = 1e-5; 
[14512]288
[14788]289          // Iterate until we found a good perplexity
290          var iter = 0; double sumP = 0;
[14855]291          while(!found && iter < 200) { 
[14512]292
[14788]293            // Compute Gaussian kernel row
[14855]294            for(var m = 0; m < k; m++) curP[m] = Math.Exp(-beta * distances[m + 1]);
[14512]295
[14788]296            // Compute entropy of current row
297            sumP = double.Epsilon;
[14806]298            for(var m = 0; m < k; m++) sumP += curP[m];
[14788]299            var h = .0;
[14855]300            for(var m = 0; m < k; m++) h += beta * (distances[m + 1] * curP[m]);
[14788]301            h = h / sumP + Math.Log(sumP);
302
303            // Evaluate whether the entropy is within the tolerance level
304            var hdiff = h - Math.Log(perplexity);
[14806]305            if(hdiff < tol && -hdiff < tol) {
[14788]306              found = true;
307            } else {
[14806]308              if(hdiff > 0) {
[14788]309                minBeta = beta;
[14806]310                if(maxBeta.IsAlmost(double.MaxValue) || maxBeta.IsAlmost(double.MinValue))
[14788]311                  beta *= 2.0;
312                else
313                  beta = (beta + maxBeta) / 2.0;
314              } else {
315                maxBeta = beta;
[14806]316                if(minBeta.IsAlmost(double.MinValue) || minBeta.IsAlmost(double.MaxValue))
[14788]317                  beta /= 2.0;
318                else
319                  beta = (beta + minBeta) / 2.0;
320              }
321            }
322
323            // Update iteration counter
324            iter++;
325          }
326
327          // Row-normalize current row of P and store in matrix
[14806]328          for(var m = 0; m < k; m++) curP[m] /= sumP;
329          for(var m = 0; m < k; m++) {
[14788]330            colP[rowP[i] + m] = indices[m + 1].Index;
331            valP[rowP[i] + m] = curP[m];
332          }
[14512]333        }
334      }
[14788]335      private static void ComputeGaussianPerplexity(T[] x, IDistance<T> distance, double[,] p, double perplexity) {
336        // Compute the distance matrix
337        var dd = ComputeDistances(x, distance);
338
339        int n = x.Length;
340        // Compute the Gaussian kernel row by row
[14806]341        for(var i = 0; i < n; i++) {
[14788]342          // Initialize some variables
343          var found = false;
344          var beta = 1.0;
[14837]345          var minBeta = double.MinValue;
[14788]346          var maxBeta = double.MaxValue;
347          const double tol = 1e-5;
348          double sumP = 0;
349
350          // Iterate until we found a good perplexity
351          var iter = 0;
[14837]352          while(!found && iter < 200) {      // 200 iterations as in tSNE implementation by van der Maarten
[14788]353
354            // Compute Gaussian kernel row
[14806]355            for(var m = 0; m < n; m++) p[i, m] = Math.Exp(-beta * dd[i][m]);
[14788]356            p[i, i] = double.Epsilon;
357
358            // Compute entropy of current row
359            sumP = double.Epsilon;
[14806]360            for(var m = 0; m < n; m++) sumP += p[i, m];
[14788]361            var h = 0.0;
[14806]362            for(var m = 0; m < n; m++) h += beta * (dd[i][m] * p[i, m]);
[14788]363            h = h / sumP + Math.Log(sumP);
364
365            // Evaluate whether the entropy is within the tolerance level
366            var hdiff = h - Math.Log(perplexity);
[14806]367            if(hdiff < tol && -hdiff < tol) {
[14788]368              found = true;
369            } else {
[14806]370              if(hdiff > 0) {
[14788]371                minBeta = beta;
[14806]372                if(maxBeta.IsAlmost(double.MaxValue) || maxBeta.IsAlmost(double.MinValue))
[14788]373                  beta *= 2.0;
374                else
375                  beta = (beta + maxBeta) / 2.0;
376              } else {
377                maxBeta = beta;
[14806]378                if(minBeta.IsAlmost(double.MinValue) || minBeta.IsAlmost(double.MaxValue))
[14788]379                  beta /= 2.0;
380                else
381                  beta = (beta + minBeta) / 2.0;
382              }
383            }
384
385            // Update iteration counter
386            iter++;
387          }
388
389          // Row normalize P
[14806]390          for(var m = 0; m < n; m++) p[i, m] /= sumP;
[14512]391        }
392      }
393
[14788]394      private static double[][] ComputeDistances(T[] x, IDistance<T> distance) {
[14806]395        var res = new double[x.Length][];
396        for(int r = 0; r < x.Length; r++) {
397          var rowV = new double[x.Length];
398          // all distances must be symmetric
399          for(int c = 0; c < r; c++) {
400            rowV[c] = res[c][r];
401          }
402          rowV[r] = 0.0; // distance to self is zero for all distances
403          for(int c = r + 1; c < x.Length; c++) {
404            rowV[c] = distance.Get(x[r], x[c]);
405          }
406          res[r] = rowV;
407        }
408        return res;
409        // return x.Select(m => x.Select(n => distance.Get(m, n)).ToArray()).ToArray();
[14788]410      }
[14414]411
[14788]412      private static double EvaluateErrorExact(double[,] p, double[,] y, int n, int d) {
413        // Compute the squared Euclidean distance matrix
414        var dd = new double[n, n];
415        var q = new double[n, n];
[14837]416        ComputeSquaredEuclideanDistance(y, n, d, dd);
[14414]417
[14788]418        // Compute Q-matrix and normalization sum
419        var sumQ = double.Epsilon;
[14806]420        for(var n1 = 0; n1 < n; n1++) {
421          for(var m = 0; m < n; m++) {
422            if(n1 != m) {
[14788]423              q[n1, m] = 1 / (1 + dd[n1, m]);
424              sumQ += q[n1, m];
425            } else q[n1, m] = double.Epsilon;
426          }
427        }
[14806]428        for(var i = 0; i < n; i++) for(var j = 0; j < n; j++) q[i, j] /= sumQ;
[14414]429
[14788]430        // Sum t-SNE error
431        var c = .0;
[14806]432        for(var i = 0; i < n; i++)
433          for(var j = 0; j < n; j++) {
[14788]434            c += p[i, j] * Math.Log((p[i, j] + float.Epsilon) / (q[i, j] + float.Epsilon));
435          }
436        return c;
437      }
[14806]438
439      // TODO: there seems to be a bug in the error approximation.
440      // The mapping of the approximate tSNE looks good but the error curve never changes.
[14788]441      private static double EvaluateErrorApproximate(IReadOnlyList<int> rowP, IReadOnlyList<int> colP, IReadOnlyList<double> valP, double[,] y, double theta) {
442        // Get estimate of normalization term
443        var n = y.GetLength(0);
444        var d = y.GetLength(1);
445        var tree = new SpacePartitioningTree(y);
446        var buff = new double[d];
447        double sumQ = 0.0;
[14806]448        for(var i = 0; i < n; i++) tree.ComputeNonEdgeForces(i, theta, buff, ref sumQ);
[14414]449
[14788]450        // Loop over all edges to compute t-SNE error
451        var c = .0;
[14806]452        for(var k = 0; k < n; k++) {
453          for(var i = rowP[k]; i < rowP[k + 1]; i++) {
[14788]454            var q = .0;
[14806]455            for(var j = 0; j < d; j++) buff[j] = y[k, j];
456            for(var j = 0; j < d; j++) buff[j] -= y[colP[i], j];
[14837]457            for(var j = 0; j < d; j++) q += buff[j] * buff[j];
458            q = (1.0 / (1.0 + q)) / sumQ;
[14788]459            c += valP[i] * Math.Log((valP[i] + float.Epsilon) / (q + float.Epsilon));
460          }
461        }
462        return c;
463      }
464      private static void SymmetrizeMatrix(IReadOnlyList<int> rowP, IReadOnlyList<int> colP, IReadOnlyList<double> valP, out int[] symRowP, out int[] symColP, out double[] symValP) {
[14414]465
[14788]466        // Count number of elements and row counts of symmetric matrix
467        var n = rowP.Count - 1;
468        var rowCounts = new int[n];
[14806]469        for(var j = 0; j < n; j++) {
470          for(var i = rowP[j]; i < rowP[j + 1]; i++) {
[14414]471
[14788]472            // Check whether element (col_P[i], n) is present
473            var present = false;
[14806]474            for(var m = rowP[colP[i]]; m < rowP[colP[i] + 1]; m++) {
475              if(colP[m] == j) present = true;
[14788]476            }
[14806]477            if(present) rowCounts[j]++;
[14788]478            else {
479              rowCounts[j]++;
480              rowCounts[colP[i]]++;
481            }
482          }
483        }
484        var noElem = 0;
[14806]485        for(var i = 0; i < n; i++) noElem += rowCounts[i];
[14414]486
[14788]487        // Allocate memory for symmetrized matrix
488        symRowP = new int[n + 1];
489        symColP = new int[noElem];
490        symValP = new double[noElem];
[14414]491
[14788]492        // Construct new row indices for symmetric matrix
493        symRowP[0] = 0;
[14806]494        for(var i = 0; i < n; i++) symRowP[i + 1] = symRowP[i] + rowCounts[i];
[14788]495
496        // Fill the result matrix
497        var offset = new int[n];
[14806]498        for(var j = 0; j < n; j++) {
499          for(var i = rowP[j]; i < rowP[j + 1]; i++) {                                  // considering element(n, colP[i])
[14788]500
501            // Check whether element (col_P[i], n) is present
502            var present = false;
[14806]503            for(var m = rowP[colP[i]]; m < rowP[colP[i] + 1]; m++) {
504              if(colP[m] != j) continue;
[14788]505              present = true;
[14806]506              if(j > colP[i]) continue; // make sure we do not add elements twice
[14788]507              symColP[symRowP[j] + offset[j]] = colP[i];
508              symColP[symRowP[colP[i]] + offset[colP[i]]] = j;
509              symValP[symRowP[j] + offset[j]] = valP[i] + valP[m];
510              symValP[symRowP[colP[i]] + offset[colP[i]]] = valP[i] + valP[m];
[14414]511            }
[14788]512
513            // If (colP[i], n) is not present, there is no addition involved
[14806]514            if(!present) {
[14788]515              symColP[symRowP[j] + offset[j]] = colP[i];
516              symColP[symRowP[colP[i]] + offset[colP[i]]] = j;
517              symValP[symRowP[j] + offset[j]] = valP[i];
518              symValP[symRowP[colP[i]] + offset[colP[i]]] = valP[i];
519            }
520
521            // Update offsets
[14806]522            if(present && (j > colP[i])) continue;
[14788]523            offset[j]++;
[14806]524            if(colP[i] != j) offset[colP[i]]++;
[14414]525          }
526        }
527
[14806]528        for(var i = 0; i < noElem; i++) symValP[i] /= 2.0;
[14414]529      }
[14807]530    }
[14788]531
[14807]532    /// <summary>
533    /// Simple interface to tSNE
534    /// </summary>
535    /// <param name="data"></param>
536    /// <param name="distance">The distance function used to differentiate similar from non-similar points, e.g. Euclidean distance.</param>
537    /// <param name="random">Random number generator</param>
538    /// <param name="newDimensions">Dimensionality of projected space (usually 2 for easy visual analysis).</param>
539    /// <param name="perplexity">Perplexity parameter of tSNE. Comparable to k in a k-nearest neighbour algorithm. Recommended value is floor(number of points /3) or lower</param>
540    /// <param name="iterations">Maximum number of iterations for gradient descent.</param>
541    /// <param name="theta">Value describing how much appoximated gradients my differ from exact gradients. Set to 0 for exact calculation and in [0,1] otherwise. CAUTION: exact calculation of forces requires building a non-sparse N*N matrix where N is the number of data points. This may exceed memory limitations.</param>
542    /// <param name="stopLyingIter">Number of iterations after which p is no longer approximated.</param>
543    /// <param name="momSwitchIter">Number of iterations after which the momentum in the gradient descent is switched.</param>
544    /// <param name="momentum">The initial momentum in the gradient descent.</param>
545    /// <param name="finalMomentum">The final momentum in gradient descent (after momentum switch).</param>
546    /// <param name="eta">Gradient descent learning rate.</param>
547    /// <returns></returns>
548    public static double[,] Run(T[] data, IDistance<T> distance, IRandom random,
549      int newDimensions = 2, double perplexity = 25, int iterations = 1000,
550      double theta = 0,
551      int stopLyingIter = 250, int momSwitchIter = 250, double momentum = .5,
552      double finalMomentum = .8, double eta = 200.0
553      ) {
554      var state = CreateState(data, distance, random, newDimensions, perplexity,
555        theta, stopLyingIter, momSwitchIter, momentum, finalMomentum, eta);
556
557      for(int i = 0; i < iterations - 1; i++) {
558        Iterate(state);
559      }
560      return Iterate(state);
[14414]561    }
[14785]562
[14807]563    public static TSNEState CreateState(T[] data, IDistance<T> distance, IRandom random,
564      int newDimensions = 2, double perplexity = 25, double theta = 0,
565      int stopLyingIter = 250, int momSwitchIter = 250, double momentum = .5,
566      double finalMomentum = .8, double eta = 200.0
[14788]567      ) {
568      return new TSNEState(data, distance, random, newDimensions, perplexity, theta, stopLyingIter, momSwitchIter, momentum, finalMomentum, eta);
569    }
[14414]570
571
[14788]572    public static double[,] Iterate(TSNEState state) {
[14806]573      if(state.exact)
[14788]574        ComputeExactGradient(state.p, state.newData, state.noDatapoints, state.newDimensions, state.dY);
575      else
576        ComputeApproximateGradient(state.rowP, state.colP, state.valP, state.newData, state.noDatapoints, state.newDimensions, state.dY, state.theta);
[14414]577
[14788]578      // Update gains
[14806]579      for(var i = 0; i < state.noDatapoints; i++) {
580        for(var j = 0; j < state.newDimensions; j++) {
[14788]581          state.gains[i, j] = Math.Sign(state.dY[i, j]) != Math.Sign(state.uY[i, j])
[14837]582            ? state.gains[i, j] + .2  // +0.2 nd *0.8 are used in two separate implementations of tSNE -> seems to be correct
583            : state.gains[i, j] * .8;
[14414]584
[14837]585          if(state.gains[i, j] < .01) state.gains[i, j] = .01;
[14414]586        }
[14788]587      }
[14414]588
[14788]589
590      // Perform gradient update (with momentum and gains)
[14806]591      for(var i = 0; i < state.noDatapoints; i++)
592        for(var j = 0; j < state.newDimensions; j++)
[14788]593          state.uY[i, j] = state.currentMomentum * state.uY[i, j] - state.eta * state.gains[i, j] * state.dY[i, j];
594
[14806]595      for(var i = 0; i < state.noDatapoints; i++)
596        for(var j = 0; j < state.newDimensions; j++)
[14788]597          state.newData[i, j] = state.newData[i, j] + state.uY[i, j];
598
599      // Make solution zero-mean
600      ZeroMean(state.newData);
[14807]601
[14788]602      // Stop lying about the P-values after a while, and switch momentum
[14806]603      if(state.iter == state.stopLyingIter) {
604        if(state.exact)
[14807]605          for(var i = 0; i < state.noDatapoints; i++)
606            for(var j = 0; j < state.noDatapoints; j++)
[14837]607              state.p[i, j] /= 12.0;
[14788]608        else
[14807]609          for(var i = 0; i < state.rowP[state.noDatapoints]; i++)
[14837]610            state.valP[i] /= 12.0;
[14414]611      }
[14788]612
[14806]613      if(state.iter == state.momSwitchIter)
[14788]614        state.currentMomentum = state.finalMomentum;
615
616      state.iter++;
617      return state.newData;
[14414]618    }
[14785]619
[14788]620
621    private static void ComputeApproximateGradient(int[] rowP, int[] colP, double[] valP, double[,] y, int n, int d, double[,] dC, double theta) {
622      var tree = new SpacePartitioningTree(y);
623      double sumQ = 0.0;
624      var posF = new double[n, d];
625      var negF = new double[n, d];
626      tree.ComputeEdgeForces(rowP, colP, valP, n, posF);
627      var row = new double[d];
[14806]628      for(var n1 = 0; n1 < n; n1++) {
[14788]629        Buffer.BlockCopy(negF, (sizeof(double) * n1 * d), row, 0, d);
630        tree.ComputeNonEdgeForces(n1, theta, row, ref sumQ);
631      }
632
633      // Compute final t-SNE gradient
[14806]634      for(var i = 0; i < n; i++)
635        for(var j = 0; j < d; j++) {
[14788]636          dC[i, j] = posF[i, j] - negF[i, j] / sumQ;
637        }
[14414]638    }
[14785]639
[14414]640    private static void ComputeExactGradient(double[,] p, double[,] y, int n, int d, double[,] dC) {
641
642      // Make sure the current gradient contains zeros
[14806]643      for(var i = 0; i < n; i++) for(var j = 0; j < d; j++) dC[i, j] = 0.0;
[14414]644
645      // Compute the squared Euclidean distance matrix
646      var dd = new double[n, n];
[14837]647      ComputeSquaredEuclideanDistance(y, n, d, dd);
[14414]648
649      // Compute Q-matrix and normalization sum
650      var q = new double[n, n];
651      var sumQ = .0;
[14806]652      for(var n1 = 0; n1 < n; n1++) {
653        for(var m = 0; m < n; m++) {
654          if(n1 == m) continue;
[14414]655          q[n1, m] = 1 / (1 + dd[n1, m]);
656          sumQ += q[n1, m];
657        }
658      }
659
660      // Perform the computation of the gradient
[14806]661      for(var n1 = 0; n1 < n; n1++) {
662        for(var m = 0; m < n; m++) {
663          if(n1 == m) continue;
[14414]664          var mult = (p[n1, m] - q[n1, m] / sumQ) * q[n1, m];
[14806]665          for(var d1 = 0; d1 < d; d1++) {
[14414]666            dC[n1, d1] += (y[n1, d1] - y[m, d1]) * mult;
667          }
668        }
669      }
670    }
[14788]671
[14414]672    private static void ComputeSquaredEuclideanDistance(double[,] x, int n, int d, double[,] dd) {
673      var dataSums = new double[n];
[14806]674      for(var i = 0; i < n; i++) {
675        for(var j = 0; j < d; j++) {
[14414]676          dataSums[i] += x[i, j] * x[i, j];
677        }
678      }
[14806]679      for(var i = 0; i < n; i++) {
680        for(var m = 0; m < n; m++) {
[14414]681          dd[i, m] = dataSums[i] + dataSums[m];
682        }
683      }
[14806]684      for(var i = 0; i < n; i++) {
[14414]685        dd[i, i] = 0.0;
[14806]686        for(var m = i + 1; m < n; m++) {
[14414]687          dd[i, m] = 0.0;
[14806]688          for(var j = 0; j < d; j++) {
[14414]689            dd[i, m] += (x[i, j] - x[m, j]) * (x[i, j] - x[m, j]);
690          }
691          dd[m, i] = dd[i, m];
692        }
693      }
694    }
695
696    private static void ZeroMean(double[,] x) {
697      // Compute data mean
698      var n = x.GetLength(0);
699      var d = x.GetLength(1);
700      var mean = new double[d];
[14806]701      for(var i = 0; i < n; i++) {
702        for(var j = 0; j < d; j++) {
[14414]703          mean[j] += x[i, j];
704        }
705      }
[14806]706      for(var i = 0; i < d; i++) {
[14414]707        mean[i] /= n;
708      }
709      // Subtract data mean
[14806]710      for(var i = 0; i < n; i++) {
711        for(var j = 0; j < d; j++) {
[14414]712          x[i, j] -= mean[j];
713        }
714      }
715    }
716  }
717}
Note: See TracBrowser for help on using the repository browser.