1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
4 | *
|
---|
5 | * This file is part of HeuristicLab.
|
---|
6 | *
|
---|
7 | * HeuristicLab is free software: you can redistribute it and/or modify
|
---|
8 | * it under the terms of the GNU General Public License as published by
|
---|
9 | * the Free Software Foundation, either version 3 of the License, or
|
---|
10 | * (at your option) any later version.
|
---|
11 | *
|
---|
12 | * HeuristicLab is distributed in the hope that it will be useful,
|
---|
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
15 | * GNU General Public License for more details.
|
---|
16 | *
|
---|
17 | * You should have received a copy of the GNU General Public License
|
---|
18 | * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
|
---|
19 | */
|
---|
20 | #endregion
|
---|
21 |
|
---|
22 | using System;
|
---|
23 | using System.Collections.Generic;
|
---|
24 | using System.Linq;
|
---|
25 | using HeuristicLab.Algorithms.DataAnalysis;
|
---|
26 | using HeuristicLab.Analysis;
|
---|
27 | using HeuristicLab.Common;
|
---|
28 | using HeuristicLab.Core;
|
---|
29 | using HeuristicLab.Data;
|
---|
30 | using HeuristicLab.Optimization;
|
---|
31 | using HeuristicLab.Parameters;
|
---|
32 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
33 | using HeuristicLab.PluginInfrastructure;
|
---|
34 | using HeuristicLab.Problems.DataAnalysis;
|
---|
35 |
|
---|
36 | namespace HeuristicLab.Algorithms.NCA {
|
---|
37 | public delegate void Reporter(double quality, double[] coefficients);
|
---|
38 | /// <summary>
|
---|
39 | /// Neighborhood Components Analysis
|
---|
40 | /// </summary>
|
---|
41 | [Item("Neighborhood Components Analysis", "NCA is described in J. Goldberger, S. Roweis, G. Hinton, R. Salakhutdinov. 2005. Neighbourhood Component Analysis. Advances in Neural Information Processing Systems, 17. pp. 513-520.")]
|
---|
42 | [Creatable("Data Analysis")]
|
---|
43 | [StorableClass]
|
---|
44 | public sealed class NeighborhoodComponentsAnalysis : FixedDataAnalysisAlgorithm<IClassificationProblem> {
|
---|
45 | #region Parameter Properties
|
---|
46 | public IValueLookupParameter<IntValue> KParameter {
|
---|
47 | get { return (IValueLookupParameter<IntValue>)Parameters["k"]; }
|
---|
48 | }
|
---|
49 | public IValueLookupParameter<IntValue> ReduceDimensionsParameter {
|
---|
50 | get { return (IValueLookupParameter<IntValue>)Parameters["ReduceDimensions"]; }
|
---|
51 | }
|
---|
52 | private IConstrainedValueParameter<INCAInitializer> InitializationParameter {
|
---|
53 | get { return (IConstrainedValueParameter<INCAInitializer>)Parameters["Initialization"]; }
|
---|
54 | }
|
---|
55 | #endregion
|
---|
56 |
|
---|
57 | #region Properties
|
---|
58 | public IntValue K {
|
---|
59 | get { return KParameter.Value; }
|
---|
60 | }
|
---|
61 | public IntValue ReduceDimensions {
|
---|
62 | get { return ReduceDimensionsParameter.Value; }
|
---|
63 | }
|
---|
64 | #endregion
|
---|
65 |
|
---|
66 | [StorableConstructor]
|
---|
67 | private NeighborhoodComponentsAnalysis(bool deserializing) : base(deserializing) { }
|
---|
68 | private NeighborhoodComponentsAnalysis(NeighborhoodComponentsAnalysis original, Cloner cloner) : base(original, cloner) { }
|
---|
69 | public NeighborhoodComponentsAnalysis()
|
---|
70 | : base() {
|
---|
71 | Parameters.Add(new ValueLookupParameter<IntValue>("k", "The k for the nearest neighbor.", new IntValue(1)));
|
---|
72 | Parameters.Add(new ValueLookupParameter<IntValue>("ReduceDimensions", "The number of dimensions that NCA should reduce the data to.", new IntValue(2)));
|
---|
73 | Parameters.Add(new ConstrainedValueParameter<INCAInitializer>("Initialization", "Which method should be used to initialize the matrix. Typically LDA (linear discriminant analysis) should provide a good estimate."));
|
---|
74 |
|
---|
75 | INCAInitializer defaultInitializer = null;
|
---|
76 | foreach (var initializer in ApplicationManager.Manager.GetInstances<INCAInitializer>().OrderBy(x => x.ItemName)) {
|
---|
77 | if (initializer is LDAInitializer) defaultInitializer = initializer;
|
---|
78 | InitializationParameter.ValidValues.Add(initializer);
|
---|
79 | }
|
---|
80 | if (defaultInitializer != null) InitializationParameter.Value = defaultInitializer;
|
---|
81 |
|
---|
82 | Problem = new ClassificationProblem();
|
---|
83 | }
|
---|
84 |
|
---|
85 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
86 | return new NeighborhoodComponentsAnalysis(this, cloner);
|
---|
87 | }
|
---|
88 |
|
---|
89 | public override void Prepare() {
|
---|
90 | if (Problem != null) base.Prepare();
|
---|
91 | }
|
---|
92 |
|
---|
93 | protected override void Run() {
|
---|
94 | var k = K.Value;
|
---|
95 | var dimensions = ReduceDimensions.Value;
|
---|
96 | var initializer = InitializationParameter.Value;
|
---|
97 |
|
---|
98 | var clonedProblem = (IClassificationProblemData)Problem.ProblemData.Clone();
|
---|
99 | var model = Train(clonedProblem, k, dimensions, initializer, ReportQuality);
|
---|
100 | var classification = new NCAClassificationSolution(clonedProblem, model);
|
---|
101 | Results.Add(new Result("ClassificationSolution", "The classification solution.", classification));
|
---|
102 | }
|
---|
103 |
|
---|
104 | private void ReportQuality(double func, double[] coefficients) {
|
---|
105 | var instances = Problem.ProblemData.TrainingIndices.Count();
|
---|
106 | DataTable qualities;
|
---|
107 | if (!Results.ContainsKey("Optimization")) {
|
---|
108 | qualities = new DataTable("Optimization");
|
---|
109 | qualities.Rows.Add(new DataRow("Quality", string.Empty));
|
---|
110 | Results.Add(new Result("Optimization", qualities));
|
---|
111 | } else qualities = (DataTable)Results["Optimization"].Value;
|
---|
112 | qualities.Rows["Quality"].Values.Add(-func / instances);
|
---|
113 |
|
---|
114 | if (!Results.ContainsKey("Quality")) {
|
---|
115 | Results.Add(new Result("Quality", new DoubleValue(-func / instances)));
|
---|
116 | } else ((DoubleValue)Results["Quality"].Value).Value = -func / instances;
|
---|
117 | }
|
---|
118 |
|
---|
119 | public static INCAModel Train(IClassificationProblemData data, int k, int dimensions, INCAInitializer initializer, Reporter reporter = null) {
|
---|
120 | var instances = data.TrainingIndices.Count();
|
---|
121 | var attributes = data.AllowedInputVariables.Count();
|
---|
122 |
|
---|
123 | double[] matrix = initializer.Initialize(data, dimensions);
|
---|
124 |
|
---|
125 | var info = new OptimizationInfo(data, dimensions, reporter);
|
---|
126 | alglib.mincgstate state;
|
---|
127 | alglib.mincgreport rep;
|
---|
128 |
|
---|
129 | alglib.mincgcreate(matrix, out state);
|
---|
130 | alglib.mincgsetcond(state, 0, 1e-05, 0, 20);
|
---|
131 | alglib.mincgsetxrep(state, true);
|
---|
132 | alglib.mincgoptimize(state, Gradient, Report, info);
|
---|
133 | alglib.mincgresults(state, out matrix, out rep);
|
---|
134 |
|
---|
135 | var transformationMatrix = new double[attributes, dimensions];
|
---|
136 | var counter = 0;
|
---|
137 | for (var i = 0; i < attributes; i++)
|
---|
138 | for (var j = 0; j < dimensions; j++)
|
---|
139 | transformationMatrix[i, j] = matrix[counter++];
|
---|
140 |
|
---|
141 | var transformedTrainingset = new double[instances, dimensions];
|
---|
142 | var rowCount = 0;
|
---|
143 | foreach (var r in data.TrainingIndices) {
|
---|
144 | var i = 0;
|
---|
145 | foreach (var v in data.AllowedInputVariables) {
|
---|
146 | var val = data.Dataset.GetDoubleValue(v, r);
|
---|
147 | for (var j = 0; j < dimensions; j++)
|
---|
148 | transformedTrainingset[rowCount, j] += val * transformationMatrix[i, j];
|
---|
149 | i++;
|
---|
150 | }
|
---|
151 | rowCount++;
|
---|
152 | }
|
---|
153 |
|
---|
154 | var ds = data.Dataset;
|
---|
155 | var targetVariable = data.TargetVariable;
|
---|
156 | return new NCAModel(transformedTrainingset, info.Scaling, transformationMatrix, k, data.TargetVariable, data.AllowedInputVariables,
|
---|
157 | data.TrainingIndices.Select(i => ds.GetDoubleValue(targetVariable, i)).ToArray());
|
---|
158 | }
|
---|
159 |
|
---|
160 | private static void Report(double[] A, double func, object obj) {
|
---|
161 | var info = (OptimizationInfo)obj;
|
---|
162 | if (info.Reporter != null) info.Reporter(func, A);
|
---|
163 | }
|
---|
164 |
|
---|
165 | private static void Gradient(double[] A, ref double func, double[] grad, object obj) {
|
---|
166 | var info = (OptimizationInfo)obj;
|
---|
167 | var data = info.Data;
|
---|
168 | var classes = info.TargetValues;
|
---|
169 | var instances = info.Instances;
|
---|
170 | var attributes = info.Attributes;
|
---|
171 |
|
---|
172 | var AMatrix = new Matrix(A, A.Length / info.ReduceDimensions, info.ReduceDimensions);
|
---|
173 |
|
---|
174 | alglib.sparsematrix probabilities;
|
---|
175 | alglib.sparsecreate(instances, instances, out probabilities);
|
---|
176 | var transformedDistances = new double[instances];
|
---|
177 | for (int i = 0; i < instances - 1; i++) {
|
---|
178 | var iVector = new Matrix(GetRow(data, i), data.GetLength(1));
|
---|
179 | var denom = 0.0;
|
---|
180 | for (int k = 0; k < instances; k++) {
|
---|
181 | if (k == i) continue;
|
---|
182 | var kVector = new Matrix(GetRow(data, k));
|
---|
183 | transformedDistances[k] = Math.Exp(-iVector.Multiply(AMatrix).Subtract(kVector.Multiply(AMatrix)).SquaredVectorLength());
|
---|
184 | denom += transformedDistances[k];
|
---|
185 | }
|
---|
186 | if (denom > 1e-05) {
|
---|
187 | for (int j = i + 1; j < instances; j++) {
|
---|
188 | if (i == j) continue;
|
---|
189 | var v = transformedDistances[j] / denom;
|
---|
190 | alglib.sparseset(probabilities, i, j, v);
|
---|
191 | }
|
---|
192 | }
|
---|
193 | }
|
---|
194 | alglib.sparseconverttocrs(probabilities); // needed to enumerate in order (top-down and left-right)
|
---|
195 |
|
---|
196 | int t0 = 0, t1 = 0, r, c;
|
---|
197 | double val;
|
---|
198 | var pi = new double[instances];
|
---|
199 | while (alglib.sparseenumerate(probabilities, ref t0, ref t1, out r, out c, out val)) {
|
---|
200 | if (classes[r].IsAlmost(classes[c])) {
|
---|
201 | pi[r] += val;
|
---|
202 | }
|
---|
203 | }
|
---|
204 |
|
---|
205 | var innerSum = new double[attributes, attributes];
|
---|
206 | while (alglib.sparseenumerate(probabilities, ref t0, ref t1, out r, out c, out val)) {
|
---|
207 | var vector = new Matrix(GetRow(data, r)).Subtract(new Matrix(GetRow(data, c)));
|
---|
208 | vector.OuterProduct(vector).Multiply(2.0 * val * pi[r]).AddTo(innerSum);
|
---|
209 |
|
---|
210 | if (classes[r].IsAlmost(classes[c])) {
|
---|
211 | vector.OuterProduct(vector).Multiply(-2.0 * val).AddTo(innerSum);
|
---|
212 | }
|
---|
213 | }
|
---|
214 |
|
---|
215 | func = -2.0 * pi.Sum();
|
---|
216 |
|
---|
217 | r = 0;
|
---|
218 | var newGrad = AMatrix.Multiply(-2.0).Transpose().Multiply(new Matrix(innerSum)).Transpose();
|
---|
219 | foreach (var g in newGrad) {
|
---|
220 | grad[r++] = g;
|
---|
221 | }
|
---|
222 | }
|
---|
223 |
|
---|
224 | #region Helpers
|
---|
225 | private static IEnumerable<double> GetRow(double[,] data, int row) {
|
---|
226 | for (int i = 0; i < data.GetLength(1); i++)
|
---|
227 | yield return data[row, i];
|
---|
228 | }
|
---|
229 |
|
---|
230 | private class OptimizationInfo {
|
---|
231 | public Scaling Scaling { get; private set; }
|
---|
232 | public double[,] Data { get; private set; }
|
---|
233 | public double[] TargetValues { get; private set; }
|
---|
234 | public int ReduceDimensions { get; private set; }
|
---|
235 | public int Instances { get; private set; }
|
---|
236 | public int Attributes { get; private set; }
|
---|
237 | public Reporter Reporter { get; private set; }
|
---|
238 |
|
---|
239 | public OptimizationInfo(IClassificationProblemData data, int reduceDimensions, Reporter reporter) {
|
---|
240 | this.Scaling = new Scaling(data.Dataset, data.AllowedInputVariables, data.TrainingIndices);
|
---|
241 | this.Data = AlglibUtil.PrepareAndScaleInputMatrix(data.Dataset, data.AllowedInputVariables, data.TrainingIndices, Scaling);
|
---|
242 | this.TargetValues = data.Dataset.GetDoubleValues(data.TargetVariable, data.TrainingIndices).ToArray();
|
---|
243 | this.ReduceDimensions = reduceDimensions;
|
---|
244 | this.Instances = data.TrainingIndices.Count();
|
---|
245 | this.Attributes = data.AllowedInputVariables.Count();
|
---|
246 | this.Reporter = reporter;
|
---|
247 | }
|
---|
248 | }
|
---|
249 | #endregion
|
---|
250 | }
|
---|
251 | }
|
---|