Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/Nca/NcaGradientCalculator.cs @ 9270

Last change on this file since 9270 was 9270, checked in by abeham, 11 years ago

#1913: Changed NCA to use LM-BFGS optimization algorithm, added model/solution creators, added operator for gradient calculation

File size: 7.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.RealVectorEncoding;
29using HeuristicLab.Operators;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.DataAnalysis;
33
34namespace HeuristicLab.Algorithms.DataAnalysis {
35  [Item("NcaGradientCalculator", "Calculates the quality and gradient of a certain NCA matrix.")]
36  [StorableClass]
37  public class NcaGradientCalculator : SingleSuccessorOperator {
38
39    #region Parameter Properties
40    public ILookupParameter<IntValue> DimensionsParameter {
41      get { return (ILookupParameter<IntValue>)Parameters["Dimensions"]; }
42    }
43
44    public ILookupParameter<IntValue> NeighborSamplesParameter {
45      get { return (ILookupParameter<IntValue>)Parameters["NeighborSamples"]; }
46    }
47
48    public ILookupParameter<DoubleValue> RegularizationParameter {
49      get { return (ILookupParameter<DoubleValue>)Parameters["Regularization"]; }
50    }
51
52    public ILookupParameter<RealVector> NcaMatrixParameter {
53      get { return (ILookupParameter<RealVector>)Parameters["NcaMatrix"]; }
54    }
55
56    public ILookupParameter<RealVector> NcaMatrixGradientsParameter {
57      get { return (ILookupParameter<RealVector>)Parameters["NcaMatrixGradients"]; }
58    }
59
60    public ILookupParameter<DoubleValue> QualityParameter {
61      get { return (ILookupParameter<DoubleValue>)Parameters["Quality"]; }
62    }
63
64    public ILookupParameter<IClassificationProblemData> ProblemDataParameter {
65      get { return (ILookupParameter<IClassificationProblemData>)Parameters["ProblemData"]; }
66    }
67
68    public ILookupParameter<Scaling> ScalingParameter {
69      get { return (ILookupParameter<Scaling>)Parameters["Scaling"]; }
70    }
71    #endregion
72
73    [StorableConstructor]
74    protected NcaGradientCalculator(bool deserializing) : base(deserializing) { }
75    protected NcaGradientCalculator(NcaGradientCalculator original, Cloner cloner) : base(original, cloner) { }
76    public NcaGradientCalculator()
77      : base() {
78      Parameters.Add(new LookupParameter<IntValue>("Dimensions", "The dimensions to which the feature space should be reduced to."));
79      Parameters.Add(new LookupParameter<IntValue>("NeighborSamples", "The number of neighbors that should be taken into account at maximum."));
80      Parameters.Add(new LookupParameter<DoubleValue>("Regularization", "The regularization term that constrains the expansion of the projected space."));
81      Parameters.Add(new LookupParameter<RealVector>("NcaMatrix", "The optimized matrix."));
82      Parameters.Add(new LookupParameter<RealVector>("NcaMatrixGradients", "The gradients from the matrix that is being optimized."));
83      Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality of the current matrix."));
84      Parameters.Add(new LookupParameter<IClassificationProblemData>("ProblemData", "The classification problem data."));
85      Parameters.Add(new LookupParameter<Scaling>("Scaling", "The scaling of the dataset."));
86    }
87
88    public override IDeepCloneable Clone(Cloner cloner) {
89      return new NcaGradientCalculator(this, cloner);
90    }
91
92    public override IOperation Apply() {
93      var problemData = ProblemDataParameter.ActualValue;
94      var scaling = ScalingParameter.ActualValue;
95      var dimensions = DimensionsParameter.ActualValue.Value;
96      var neighborSamples = NeighborSamplesParameter.ActualValue.Value;
97      var regularization = RegularizationParameter.ActualValue.Value;
98
99      var vector = NcaMatrixParameter.ActualValue;
100      var gradients = NcaMatrixGradientsParameter.ActualValue;
101      if (gradients == null) {
102        gradients = new RealVector(vector.Length);
103        NcaMatrixGradientsParameter.ActualValue = gradients;
104      }
105
106      var data = AlglibUtil.PrepareAndScaleInputMatrix(problemData.Dataset, problemData.AllowedInputVariables,
107                                                       problemData.TrainingIndices, scaling);
108      var classes = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();
109
110      var quality = Gradient(vector, gradients, data, classes, dimensions, neighborSamples, regularization);
111      QualityParameter.ActualValue = new DoubleValue(quality);
112
113      return base.Apply();
114    }
115
116    private static double Gradient(RealVector A, RealVector grad, double[,] data, double[] classes, int dimensions, int neighborSamples, double regularization) {
117      var instances = data.GetLength(0);
118      var attributes = data.GetLength(1);
119
120      var AMatrix = new Matrix(A, A.Length / dimensions, dimensions);
121
122      alglib.sparsematrix probabilities;
123      alglib.sparsecreate(instances, instances, out probabilities);
124      var transformedDistances = new Dictionary<int, double>(instances);
125      for (int i = 0; i < instances; i++) {
126        var iVector = new Matrix(GetRow(data, i), data.GetLength(1));
127        for (int k = 0; k < instances; k++) {
128          if (k == i) {
129            transformedDistances.Remove(k);
130            continue;
131          }
132          var kVector = new Matrix(GetRow(data, k));
133          transformedDistances[k] = Math.Exp(-iVector.Multiply(AMatrix).Subtract(kVector.Multiply(AMatrix)).SumOfSquares());
134        }
135        var normalization = transformedDistances.Sum(x => x.Value);
136        if (normalization <= 0) continue;
137        foreach (var s in transformedDistances.Where(x => x.Value > 0).OrderByDescending(x => x.Value).Take(neighborSamples)) {
138          alglib.sparseset(probabilities, i, s.Key, s.Value / normalization);
139        }
140      }
141      alglib.sparseconverttocrs(probabilities); // needed to enumerate in order (top-down and left-right)
142
143      int t0 = 0, t1 = 0, r, c;
144      double val;
145      var pi = new double[instances];
146      while (alglib.sparseenumerate(probabilities, ref t0, ref t1, out r, out c, out val)) {
147        if (classes[r].IsAlmost(classes[c])) {
148          pi[r] += val;
149        }
150      }
151
152      var innerSum = new double[attributes, attributes];
153      while (alglib.sparseenumerate(probabilities, ref t0, ref t1, out r, out c, out val)) {
154        var vector = new Matrix(GetRow(data, r)).Subtract(new Matrix(GetRow(data, c)));
155        vector.OuterProduct(vector).Multiply(val * pi[r]).AddTo(innerSum);
156
157        if (classes[r].IsAlmost(classes[c])) {
158          vector.OuterProduct(vector).Multiply(-val).AddTo(innerSum);
159        }
160      }
161
162      var func = -pi.Sum() + regularization * AMatrix.SumOfSquares();
163
164      r = 0;
165      var newGrad = AMatrix.Multiply(-2.0).Transpose().Multiply(new Matrix(innerSum)).Transpose();
166      foreach (var g in newGrad) {
167        grad[r] = g + regularization * 2 * A[r];
168        r++;
169      }
170
171      return func;
172    }
173
174    private static IEnumerable<double> GetRow(double[,] data, int row) {
175      for (int i = 0; i < data.GetLength(1); i++)
176        yield return data[row, i];
177    }
178  }
179}
Note: See TracBrowser for help on using the repository browser.