Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Algorithms.DataAnalysis/3.4/NearestNeighbour/NearestNeighbourModel.cs @ 15804

Last change on this file since 15804 was 15788, checked in by gkronber, 7 years ago

#2902 merged r15783 and r15786 from trunk to stable

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