Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Weighted TSNE/3.4/TSNE/TSNEStatic.cs @ 15455

Last change on this file since 15455 was 15455, checked in by bwerth, 6 years ago

#2847 added WeightedEuclideanDistance && fixed minor bug in scatterPlot colloring

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