Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2850 worked on weighted tSNE

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