Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceReintegration/HeuristicLab.Algorithms.DataAnalysis/3.4/NearestNeighbour/NearestNeighbourModel.cs @ 15802

Last change on this file since 15802 was 15018, checked in by gkronber, 8 years ago

#2520 introduced StorableConstructorFlag type for StorableConstructors

File size: 15.0 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;
28using HeuristicLab.Problems.DataAnalysis;
29
30namespace HeuristicLab.Algorithms.DataAnalysis {
31  /// <summary>
32  /// Represents a nearest neighbour model for regression and classification
33  /// </summary>
34  [StorableType("da958292-162f-4292-8d09-66e9838a24ed")]
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 = new alglib.nearestneighbor.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(StorableConstructorFlag deserializing)
69      : base(deserializing) {
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 = dataset.ToArray(
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 model 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 transforms =
168        variables.Select(
169          (_, colIdx) =>
170            new LinearTransformation(variables) { Addend = offsets[colIdx] * factors[colIdx], Multiplier = factors[colIdx] });
171      return dataset.ToArray(variables, transforms, rows);
172    }
173
174    public override IDeepCloneable Clone(Cloner cloner) {
175      return new NearestNeighbourModel(this, cloner);
176    }
177
178    public IEnumerable<double> GetEstimatedValues(IDataset dataset, IEnumerable<int> rows) {
179      double[,] inputData;
180      if (IsCompatibilityLoaded) {
181        inputData = dataset.ToArray(allowedInputVariables, rows);
182      } else {
183        inputData = CreateScaledData(dataset, allowedInputVariables, rows, offsets, weights);
184      }
185
186      int n = inputData.GetLength(0);
187      int columns = inputData.GetLength(1);
188      double[] x = new double[columns];
189      double[] dists = new double[k];
190      double[,] neighbours = new double[k, columns + 1];
191
192      for (int row = 0; row < n; row++) {
193        for (int column = 0; column < columns; column++) {
194          x[column] = inputData[row, column];
195        }
196        int numNeighbours;
197        lock (kdTreeLockObject) { // gkronber: the following calls change the kdTree data structure
198          numNeighbours = alglib.nearestneighbor.kdtreequeryknn(kdTree, x, k, false);
199          alglib.nearestneighbor.kdtreequeryresultsdistances(kdTree, ref dists);
200          alglib.nearestneighbor.kdtreequeryresultsxy(kdTree, ref neighbours);
201        }
202
203        double distanceWeightedValue = 0.0;
204        double distsSum = 0.0;
205        for (int i = 0; i < numNeighbours; i++) {
206          distanceWeightedValue += neighbours[i, columns] / dists[i];
207          distsSum += 1.0 / dists[i];
208        }
209        yield return distanceWeightedValue / distsSum;
210      }
211    }
212
213    public override IEnumerable<double> GetEstimatedClassValues(IDataset dataset, IEnumerable<int> rows) {
214      if (classValues == null) throw new InvalidOperationException("No class values are defined.");
215      double[,] inputData;
216      if (IsCompatibilityLoaded) {
217        inputData = dataset.ToArray(allowedInputVariables, rows);
218      } else {
219        inputData = CreateScaledData(dataset, allowedInputVariables, rows, offsets, weights);
220      }
221      int n = inputData.GetLength(0);
222      int columns = inputData.GetLength(1);
223      double[] x = new double[columns];
224      int[] y = new int[classValues.Length];
225      double[] dists = new double[k];
226      double[,] neighbours = new double[k, columns + 1];
227
228      for (int row = 0; row < n; row++) {
229        for (int column = 0; column < columns; column++) {
230          x[column] = inputData[row, column];
231        }
232        int numNeighbours;
233        lock (kdTreeLockObject) {
234          // gkronber: the following calls change the kdTree data structure
235          numNeighbours = alglib.nearestneighbor.kdtreequeryknn(kdTree, x, k, false);
236          alglib.nearestneighbor.kdtreequeryresultsdistances(kdTree, ref dists);
237          alglib.nearestneighbor.kdtreequeryresultsxy(kdTree, ref neighbours);
238        }
239        Array.Clear(y, 0, y.Length);
240        for (int i = 0; i < numNeighbours; i++) {
241          int classValue = (int)Math.Round(neighbours[i, columns]);
242          y[classValue]++;
243        }
244
245        // find class for with the largest probability value
246        int maxProbClassIndex = 0;
247        double maxProb = y[0];
248        for (int i = 1; i < y.Length; i++) {
249          if (maxProb < y[i]) {
250            maxProb = y[i];
251            maxProbClassIndex = i;
252          }
253        }
254        yield return classValues[maxProbClassIndex];
255      }
256    }
257
258
259    IRegressionSolution IRegressionModel.CreateRegressionSolution(IRegressionProblemData problemData) {
260      return new NearestNeighbourRegressionSolution(this, new RegressionProblemData(problemData));
261    }
262    public override IClassificationSolution CreateClassificationSolution(IClassificationProblemData problemData) {
263      return new NearestNeighbourClassificationSolution(this, new ClassificationProblemData(problemData));
264    }
265
266    #region events
267    public event EventHandler Changed;
268    private void OnChanged(EventArgs e) {
269      var handlers = Changed;
270      if (handlers != null)
271        handlers(this, e);
272    }
273    #endregion
274
275
276    // BackwardsCompatibility3.3
277    #region Backwards compatible code, remove with 3.4
278
279    private bool isCompatibilityLoaded = false; // new kNN models have the value false, kNN models loaded from disc have the value true
280    [Storable(DefaultValue = true)]
281    public bool IsCompatibilityLoaded {
282      get { return isCompatibilityLoaded; }
283      set { isCompatibilityLoaded = value; }
284    }
285    #endregion
286    #region persistence
287    [Storable]
288    public double KDTreeApproxF {
289      get { return kdTree.approxf; }
290      set { kdTree.approxf = value; }
291    }
292    [Storable]
293    public double[] KDTreeBoxMax {
294      get { return kdTree.boxmax; }
295      set { kdTree.boxmax = value; }
296    }
297    [Storable]
298    public double[] KDTreeBoxMin {
299      get { return kdTree.boxmin; }
300      set { kdTree.boxmin = value; }
301    }
302    [Storable]
303    public double[] KDTreeBuf {
304      get { return kdTree.buf; }
305      set { kdTree.buf = value; }
306    }
307    [Storable]
308    public double[] KDTreeCurBoxMax {
309      get { return kdTree.curboxmax; }
310      set { kdTree.curboxmax = value; }
311    }
312    [Storable]
313    public double[] KDTreeCurBoxMin {
314      get { return kdTree.curboxmin; }
315      set { kdTree.curboxmin = value; }
316    }
317    [Storable]
318    public double KDTreeCurDist {
319      get { return kdTree.curdist; }
320      set { kdTree.curdist = value; }
321    }
322    [Storable]
323    public int KDTreeDebugCounter {
324      get { return kdTree.debugcounter; }
325      set { kdTree.debugcounter = value; }
326    }
327    [Storable]
328    public int[] KDTreeIdx {
329      get { return kdTree.idx; }
330      set { kdTree.idx = value; }
331    }
332    [Storable]
333    public int KDTreeKCur {
334      get { return kdTree.kcur; }
335      set { kdTree.kcur = value; }
336    }
337    [Storable]
338    public int KDTreeKNeeded {
339      get { return kdTree.kneeded; }
340      set { kdTree.kneeded = value; }
341    }
342    [Storable]
343    public int KDTreeN {
344      get { return kdTree.n; }
345      set { kdTree.n = value; }
346    }
347    [Storable]
348    public int[] KDTreeNodes {
349      get { return kdTree.nodes; }
350      set { kdTree.nodes = value; }
351    }
352    [Storable]
353    public int KDTreeNormType {
354      get { return kdTree.normtype; }
355      set { kdTree.normtype = value; }
356    }
357    [Storable]
358    public int KDTreeNX {
359      get { return kdTree.nx; }
360      set { kdTree.nx = value; }
361    }
362    [Storable]
363    public int KDTreeNY {
364      get { return kdTree.ny; }
365      set { kdTree.ny = value; }
366    }
367    [Storable]
368    public double[] KDTreeR {
369      get { return kdTree.r; }
370      set { kdTree.r = value; }
371    }
372    [Storable]
373    public double KDTreeRNeeded {
374      get { return kdTree.rneeded; }
375      set { kdTree.rneeded = value; }
376    }
377    [Storable]
378    public bool KDTreeSelfMatch {
379      get { return kdTree.selfmatch; }
380      set { kdTree.selfmatch = value; }
381    }
382    [Storable]
383    public double[] KDTreeSplits {
384      get { return kdTree.splits; }
385      set { kdTree.splits = value; }
386    }
387    [Storable]
388    public int[] KDTreeTags {
389      get { return kdTree.tags; }
390      set { kdTree.tags = value; }
391    }
392    [Storable]
393    public double[] KDTreeX {
394      get { return kdTree.x; }
395      set { kdTree.x = value; }
396    }
397    [Storable]
398    public double[,] KDTreeXY {
399      get { return kdTree.xy; }
400      set { kdTree.xy = value; }
401    }
402    #endregion
403  }
404}
Note: See TracBrowser for help on using the repository browser.