source: branches/symbreg-factors-2650/HeuristicLab.Algorithms.DataAnalysis/3.4/NearestNeighbour/NearestNeighbourModel.cs @ 14239

Last change on this file since 14239 was 14239, checked in by gkronber, 3 years ago

#2650: merged r14234:14236 from trunk to branch

File size: 15.1 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#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28using HeuristicLab.Problems.DataAnalysis;
29
30namespace HeuristicLab.Algorithms.DataAnalysis {
31  /// <summary>
32  /// Represents a nearest neighbour model for regression and classification
33  /// </summary>
34  [StorableClass]
35  [Item("NearestNeighbourModel", "Represents a nearest neighbour model for regression and classification.")]
36  public sealed class NearestNeighbourModel : ClassificationModel, INearestNeighbourModel {
37
38    private alglib.nearestneighbor.kdtree kdTree;
39    public alglib.nearestneighbor.kdtree KDTree {
40      get { return kdTree; }
41      set {
42        if (value != kdTree) {
43          if (value == null) throw new ArgumentNullException();
44          kdTree = value;
45          OnChanged(EventArgs.Empty);
46        }
47      }
48    }
49
50    public override IEnumerable<string> VariablesUsedForPrediction {
51      get { return allowedInputVariables; }
52    }
53
54    [Storable]
55    private string[] allowedInputVariables;
56    [Storable]
57    private double[] classValues;
58    [Storable]
59    private int k;
60    [Storable(DefaultValue = null)]
61    private double[] weights; // not set for old versions loaded from disk
62    [Storable(DefaultValue = null)]
63    private double[] offsets; // not set for old versions loaded from disk
64
65    [StorableConstructor]
66    private NearestNeighbourModel(bool deserializing)
67      : base(deserializing) {
68      if (deserializing)
69        kdTree = new alglib.nearestneighbor.kdtree();
70    }
71    private NearestNeighbourModel(NearestNeighbourModel original, Cloner cloner)
72      : base(original, cloner) {
73      kdTree = new alglib.nearestneighbor.kdtree();
74      kdTree.approxf = original.kdTree.approxf;
75      kdTree.boxmax = (double[])original.kdTree.boxmax.Clone();
76      kdTree.boxmin = (double[])original.kdTree.boxmin.Clone();
77      kdTree.buf = (double[])original.kdTree.buf.Clone();
78      kdTree.curboxmax = (double[])original.kdTree.curboxmax.Clone();
79      kdTree.curboxmin = (double[])original.kdTree.curboxmin.Clone();
80      kdTree.curdist = original.kdTree.curdist;
81      kdTree.debugcounter = original.kdTree.debugcounter;
82      kdTree.idx = (int[])original.kdTree.idx.Clone();
83      kdTree.kcur = original.kdTree.kcur;
84      kdTree.kneeded = original.kdTree.kneeded;
85      kdTree.n = original.kdTree.n;
86      kdTree.nodes = (int[])original.kdTree.nodes.Clone();
87      kdTree.normtype = original.kdTree.normtype;
88      kdTree.nx = original.kdTree.nx;
89      kdTree.ny = original.kdTree.ny;
90      kdTree.r = (double[])original.kdTree.r.Clone();
91      kdTree.rneeded = original.kdTree.rneeded;
92      kdTree.selfmatch = original.kdTree.selfmatch;
93      kdTree.splits = (double[])original.kdTree.splits.Clone();
94      kdTree.tags = (int[])original.kdTree.tags.Clone();
95      kdTree.x = (double[])original.kdTree.x.Clone();
96      kdTree.xy = (double[,])original.kdTree.xy.Clone();
97
98      k = original.k;
99      isCompatibilityLoaded = original.IsCompatibilityLoaded;
100      if (!IsCompatibilityLoaded) {
101        weights = new double[original.weights.Length];
102        Array.Copy(original.weights, weights, weights.Length);
103        offsets = new double[original.offsets.Length];
104        Array.Copy(original.offsets, this.offsets, this.offsets.Length);
105      }
106      allowedInputVariables = (string[])original.allowedInputVariables.Clone();
107      if (original.classValues != null)
108        this.classValues = (double[])original.classValues.Clone();
109    }
110    public NearestNeighbourModel(IDataset dataset, IEnumerable<int> rows, int k, string targetVariable, IEnumerable<string> allowedInputVariables, IEnumerable<double> weights = null, double[] classValues = null)
111      : base(targetVariable) {
112      Name = ItemName;
113      Description = ItemDescription;
114      this.k = k;
115      this.allowedInputVariables = allowedInputVariables.ToArray();
116      double[,] inputMatrix;
117      if (IsCompatibilityLoaded) {
118        // no scaling
119        inputMatrix = AlglibUtil.PrepareInputMatrix(dataset,
120          this.allowedInputVariables.Concat(new string[] { targetVariable }),
121          rows);
122      } else {
123        this.offsets = this.allowedInputVariables
124          .Select(name => dataset.GetDoubleValues(name, rows).Average() * -1)
125          .Concat(new double[] { 0 }) // no offset for target variable
126          .ToArray();
127        if (weights == null) {
128          // automatic determination of weights (all features should have variance = 1)
129          this.weights = this.allowedInputVariables
130            .Select(name => 1.0 / dataset.GetDoubleValues(name, rows).StandardDeviationPop())
131            .Concat(new double[] { 1.0 }) // no scaling for target variable
132            .ToArray();
133        } else {
134          // user specified weights (+ 1 for target)
135          this.weights = weights.Concat(new double[] { 1.0 }).ToArray();
136          if (this.weights.Length - 1 != this.allowedInputVariables.Length)
137            throw new ArgumentException("The number of elements in the weight vector must match the number of input variables");
138        }
139        inputMatrix = CreateScaledData(dataset, this.allowedInputVariables.Concat(new string[] { targetVariable }), rows, this.offsets, this.weights);
140      }
141
142      if (inputMatrix.Cast<double>().Any(x => double.IsNaN(x) || double.IsInfinity(x)))
143        throw new NotSupportedException(
144          "Nearest neighbour classification does not support NaN or infinity values in the input dataset.");
145
146      this.kdTree = new alglib.nearestneighbor.kdtree();
147
148      var nRows = inputMatrix.GetLength(0);
149      var nFeatures = inputMatrix.GetLength(1) - 1;
150
151      if (classValues != null) {
152        this.classValues = (double[])classValues.Clone();
153        int nClasses = classValues.Length;
154        // map original class values to values [0..nClasses-1]
155        var classIndices = new Dictionary<double, double>();
156        for (int i = 0; i < nClasses; i++)
157          classIndices[classValues[i]] = i;
158
159        for (int row = 0; row < nRows; row++) {
160          inputMatrix[row, nFeatures] = classIndices[inputMatrix[row, nFeatures]];
161        }
162      }
163      alglib.nearestneighbor.kdtreebuild(inputMatrix, nRows, inputMatrix.GetLength(1) - 1, 1, 2, kdTree);
164    }
165
166    private static double[,] CreateScaledData(IDataset dataset, IEnumerable<string> variables, IEnumerable<int> rows, double[] offsets, double[] factors) {
167      var x = new double[rows.Count(), variables.Count()];
168      var colIdx = 0;
169      foreach (var variableName in variables) {
170        var rowIdx = 0;
171        foreach (var val in dataset.GetDoubleValues(variableName, rows)) {
172          x[rowIdx, colIdx] = (val + offsets[colIdx]) * factors[colIdx];
173          rowIdx++;
174        }
175        colIdx++;
176      }
177      return x;
178    }
179
180    public override IDeepCloneable Clone(Cloner cloner) {
181      return new NearestNeighbourModel(this, cloner);
182    }
183
184    public IEnumerable<double> GetEstimatedValues(IDataset dataset, IEnumerable<int> rows) {
185      double[,] inputData;
186      if (IsCompatibilityLoaded) {
187        inputData = AlglibUtil.PrepareInputMatrix(dataset, allowedInputVariables, rows);
188      } else {
189        inputData = CreateScaledData(dataset, allowedInputVariables, rows, offsets, weights);
190      }
191
192      int n = inputData.GetLength(0);
193      int columns = inputData.GetLength(1);
194      double[] x = new double[columns];
195      double[] dists = new double[k];
196      double[,] neighbours = new double[k, columns + 1];
197
198      for (int row = 0; row < n; row++) {
199        for (int column = 0; column < columns; column++) {
200          x[column] = inputData[row, column];
201        }
202        int numNeighbours;
203        lock (kdTree) { // gkronber: the following calls change the kdTree data structure
204          numNeighbours = alglib.nearestneighbor.kdtreequeryknn(kdTree, x, k, false);
205          alglib.nearestneighbor.kdtreequeryresultsdistances(kdTree, ref dists);
206          alglib.nearestneighbor.kdtreequeryresultsxy(kdTree, ref neighbours);
207        }
208
209        double distanceWeightedValue = 0.0;
210        double distsSum = 0.0;
211        for (int i = 0; i < numNeighbours; i++) {
212          distanceWeightedValue += neighbours[i, columns] / dists[i];
213          distsSum += 1.0 / dists[i];
214        }
215        yield return distanceWeightedValue / distsSum;
216      }
217    }
218
219    public override IEnumerable<double> GetEstimatedClassValues(IDataset dataset, IEnumerable<int> rows) {
220      if (classValues == null) throw new InvalidOperationException("No class values are defined.");
221      double[,] inputData;
222      if (IsCompatibilityLoaded) {
223        inputData = AlglibUtil.PrepareInputMatrix(dataset, allowedInputVariables, rows);
224      } else {
225        inputData = CreateScaledData(dataset, allowedInputVariables, rows, offsets, weights);
226      }
227      int n = inputData.GetLength(0);
228      int columns = inputData.GetLength(1);
229      double[] x = new double[columns];
230      int[] y = new int[classValues.Length];
231      double[] dists = new double[k];
232      double[,] neighbours = new double[k, columns + 1];
233
234      for (int row = 0; row < n; row++) {
235        for (int column = 0; column < columns; column++) {
236          x[column] = inputData[row, column];
237        }
238        int numNeighbours;
239        lock (kdTree) {
240          // gkronber: the following calls change the kdTree data structure
241          numNeighbours = alglib.nearestneighbor.kdtreequeryknn(kdTree, x, k, false);
242          alglib.nearestneighbor.kdtreequeryresultsdistances(kdTree, ref dists);
243          alglib.nearestneighbor.kdtreequeryresultsxy(kdTree, ref neighbours);
244        }
245        Array.Clear(y, 0, y.Length);
246        for (int i = 0; i < numNeighbours; i++) {
247          int classValue = (int)Math.Round(neighbours[i, columns]);
248          y[classValue]++;
249        }
250
251        // find class for with the largest probability value
252        int maxProbClassIndex = 0;
253        double maxProb = y[0];
254        for (int i = 1; i < y.Length; i++) {
255          if (maxProb < y[i]) {
256            maxProb = y[i];
257            maxProbClassIndex = i;
258          }
259        }
260        yield return classValues[maxProbClassIndex];
261      }
262    }
263
264
265    IRegressionSolution IRegressionModel.CreateRegressionSolution(IRegressionProblemData problemData) {
266      return new NearestNeighbourRegressionSolution(this, new RegressionProblemData(problemData));
267    }
268    public override IClassificationSolution CreateClassificationSolution(IClassificationProblemData problemData) {
269      return new NearestNeighbourClassificationSolution(this, new ClassificationProblemData(problemData));
270    }
271
272    #region events
273    public event EventHandler Changed;
274    private void OnChanged(EventArgs e) {
275      var handlers = Changed;
276      if (handlers != null)
277        handlers(this, e);
278    }
279    #endregion
280
281
282    // BackwardsCompatibility3.3
283    #region Backwards compatible code, remove with 3.4
284
285    private bool isCompatibilityLoaded = false; // new kNN models have the value false, kNN models loaded from disc have the value true
286    [Storable(DefaultValue = true)]
287    public bool IsCompatibilityLoaded {
288      get { return isCompatibilityLoaded; }
289      set { isCompatibilityLoaded = value; }
290    }
291    #endregion
292    #region persistence
293    [Storable]
294    public double KDTreeApproxF {
295      get { return kdTree.approxf; }
296      set { kdTree.approxf = value; }
297    }
298    [Storable]
299    public double[] KDTreeBoxMax {
300      get { return kdTree.boxmax; }
301      set { kdTree.boxmax = value; }
302    }
303    [Storable]
304    public double[] KDTreeBoxMin {
305      get { return kdTree.boxmin; }
306      set { kdTree.boxmin = value; }
307    }
308    [Storable]
309    public double[] KDTreeBuf {
310      get { return kdTree.buf; }
311      set { kdTree.buf = value; }
312    }
313    [Storable]
314    public double[] KDTreeCurBoxMax {
315      get { return kdTree.curboxmax; }
316      set { kdTree.curboxmax = value; }
317    }
318    [Storable]
319    public double[] KDTreeCurBoxMin {
320      get { return kdTree.curboxmin; }
321      set { kdTree.curboxmin = value; }
322    }
323    [Storable]
324    public double KDTreeCurDist {
325      get { return kdTree.curdist; }
326      set { kdTree.curdist = value; }
327    }
328    [Storable]
329    public int KDTreeDebugCounter {
330      get { return kdTree.debugcounter; }
331      set { kdTree.debugcounter = value; }
332    }
333    [Storable]
334    public int[] KDTreeIdx {
335      get { return kdTree.idx; }
336      set { kdTree.idx = value; }
337    }
338    [Storable]
339    public int KDTreeKCur {
340      get { return kdTree.kcur; }
341      set { kdTree.kcur = value; }
342    }
343    [Storable]
344    public int KDTreeKNeeded {
345      get { return kdTree.kneeded; }
346      set { kdTree.kneeded = value; }
347    }
348    [Storable]
349    public int KDTreeN {
350      get { return kdTree.n; }
351      set { kdTree.n = value; }
352    }
353    [Storable]
354    public int[] KDTreeNodes {
355      get { return kdTree.nodes; }
356      set { kdTree.nodes = value; }
357    }
358    [Storable]
359    public int KDTreeNormType {
360      get { return kdTree.normtype; }
361      set { kdTree.normtype = value; }
362    }
363    [Storable]
364    public int KDTreeNX {
365      get { return kdTree.nx; }
366      set { kdTree.nx = value; }
367    }
368    [Storable]
369    public int KDTreeNY {
370      get { return kdTree.ny; }
371      set { kdTree.ny = value; }
372    }
373    [Storable]
374    public double[] KDTreeR {
375      get { return kdTree.r; }
376      set { kdTree.r = value; }
377    }
378    [Storable]
379    public double KDTreeRNeeded {
380      get { return kdTree.rneeded; }
381      set { kdTree.rneeded = value; }
382    }
383    [Storable]
384    public bool KDTreeSelfMatch {
385      get { return kdTree.selfmatch; }
386      set { kdTree.selfmatch = value; }
387    }
388    [Storable]
389    public double[] KDTreeSplits {
390      get { return kdTree.splits; }
391      set { kdTree.splits = value; }
392    }
393    [Storable]
394    public int[] KDTreeTags {
395      get { return kdTree.tags; }
396      set { kdTree.tags = value; }
397    }
398    [Storable]
399    public double[] KDTreeX {
400      get { return kdTree.x; }
401      set { kdTree.x = value; }
402    }
403    [Storable]
404    public double[,] KDTreeXY {
405      get { return kdTree.xy; }
406      set { kdTree.xy = value; }
407    }
408    #endregion
409  }
410}
Note: See TracBrowser for help on using the repository browser.