Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.TimeSeries/HeuristicLab.Algorithms.DataAnalysis/3.4/NearestNeighbour/NearestNeighbourModel.cs @ 7403

Last change on this file since 7403 was 7268, checked in by gkronber, 13 years ago

#1081: merged r7214:7266 from trunk into time series branch.

File size: 11.1 KB
Line 
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
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 neural network for regression and classification.")]
36  public sealed class NearestNeighbourModel : NamedItem, 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    [Storable]
51    private string targetVariable;
52    [Storable]
53    private string[] allowedInputVariables;
54    [Storable]
55    private double[] classValues;
56    [Storable]
57    private int k;
58    [StorableConstructor]
59    private NearestNeighbourModel(bool deserializing)
60      : base(deserializing) {
61      if (deserializing)
62        kdTree = new alglib.nearestneighbor.kdtree();
63    }
64    private NearestNeighbourModel(NearestNeighbourModel original, Cloner cloner)
65      : base(original, cloner) {
66      kdTree = new alglib.nearestneighbor.kdtree();
67      kdTree.approxf = original.kdTree.approxf;
68      kdTree.boxmax = (double[])original.kdTree.boxmax.Clone();
69      kdTree.boxmin = (double[])original.kdTree.boxmin.Clone();
70      kdTree.buf = (double[])original.kdTree.buf.Clone();
71      kdTree.curboxmax = (double[])original.kdTree.curboxmax.Clone();
72      kdTree.curboxmin = (double[])original.kdTree.curboxmin.Clone();
73      kdTree.curdist = original.kdTree.curdist;
74      kdTree.debugcounter = original.kdTree.debugcounter;
75      kdTree.distmatrixtype = original.kdTree.distmatrixtype;
76      kdTree.idx = (int[])original.kdTree.idx.Clone();
77      kdTree.kcur = original.kdTree.kcur;
78      kdTree.kneeded = original.kdTree.kneeded;
79      kdTree.n = original.kdTree.n;
80      kdTree.nodes = (int[])original.kdTree.nodes.Clone();
81      kdTree.normtype = original.kdTree.normtype;
82      kdTree.nx = original.kdTree.nx;
83      kdTree.ny = original.kdTree.ny;
84      kdTree.r = (double[])original.kdTree.r.Clone();
85      kdTree.rneeded = original.kdTree.rneeded;
86      kdTree.selfmatch = original.kdTree.selfmatch;
87      kdTree.splits = (double[])original.kdTree.splits.Clone();
88      kdTree.tags = (int[])original.kdTree.tags.Clone();
89      kdTree.x = (double[])original.kdTree.x.Clone();
90      kdTree.xy = (double[,])original.kdTree.xy.Clone();
91
92      k = original.k;
93      targetVariable = original.targetVariable;
94      allowedInputVariables = (string[])original.allowedInputVariables.Clone();
95      if (original.classValues != null)
96        this.classValues = (double[])original.classValues.Clone();
97    }
98    public NearestNeighbourModel(alglib.nearestneighbor.kdtree kdTree, int k, string targetVariable, IEnumerable<string> allowedInputVariables, double[] classValues = null)
99      : base() {
100      this.name = ItemName;
101      this.description = ItemDescription;
102      this.kdTree = kdTree;
103      this.k = k;
104      this.targetVariable = targetVariable;
105      this.allowedInputVariables = allowedInputVariables.ToArray();
106      if (classValues != null)
107        this.classValues = (double[])classValues.Clone();
108    }
109
110    public override IDeepCloneable Clone(Cloner cloner) {
111      return new NearestNeighbourModel(this, cloner);
112    }
113
114    public IEnumerable<double> GetEstimatedValues(Dataset dataset, IEnumerable<int> rows) {
115      double[,] inputData = AlglibUtil.PrepareInputMatrix(dataset, allowedInputVariables, rows);
116
117      int n = inputData.GetLength(0);
118      int columns = inputData.GetLength(1);
119      double[] x = new double[columns];
120      double[] y = new double[1];
121      double[] dists = new double[k];
122      double[,] neighbours = new double[k, columns + 1];
123
124      for (int row = 0; row < n; row++) {
125        for (int column = 0; column < columns; column++) {
126          x[column] = inputData[row, column];
127        }
128        int actNeighbours = alglib.nearestneighbor.kdtreequeryknn(kdTree, x, k, false);
129        alglib.nearestneighbor.kdtreequeryresultsdistances(kdTree, ref dists);
130        alglib.nearestneighbor.kdtreequeryresultsxy(kdTree, ref neighbours);
131
132        double distanceWeightedValue = 0.0;
133        double distsSum = 0.0;
134        for (int i = 0; i < actNeighbours; i++) {
135          distanceWeightedValue += neighbours[i, columns] / dists[i];
136          distsSum += 1.0 / dists[i];
137        }
138        yield return distanceWeightedValue / distsSum;
139      }
140    }
141
142    public IEnumerable<double> GetEstimatedClassValues(Dataset dataset, IEnumerable<int> rows) {
143      double[,] inputData = AlglibUtil.PrepareInputMatrix(dataset, allowedInputVariables, rows);
144
145      int n = inputData.GetLength(0);
146      int columns = inputData.GetLength(1);
147      double[] x = new double[columns];
148      int[] y = new int[classValues.Length];
149      double[] dists = new double[k];
150      double[,] neighbours = new double[k, columns + 1];
151
152      for (int row = 0; row < n; row++) {
153        for (int column = 0; column < columns; column++) {
154          x[column] = inputData[row, column];
155        }
156        int actNeighbours = alglib.nearestneighbor.kdtreequeryknn(kdTree, x, k, false);
157        alglib.nearestneighbor.kdtreequeryresultsdistances(kdTree, ref dists);
158        alglib.nearestneighbor.kdtreequeryresultsxy(kdTree, ref neighbours);
159
160        Array.Clear(y, 0, y.Length);
161        for (int i = 0; i < actNeighbours; i++) {
162          int classValue = (int)Math.Round(neighbours[i, columns]);
163          y[classValue]++;
164        }
165
166        // find class for with the largest probability value
167        int maxProbClassIndex = 0;
168        double maxProb = y[0];
169        for (int i = 1; i < y.Length; i++) {
170          if (maxProb < y[i]) {
171            maxProb = y[i];
172            maxProbClassIndex = i;
173          }
174        }
175        yield return classValues[maxProbClassIndex];
176      }
177    }
178
179    public INearestNeighbourRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData) {
180      return new NearestNeighbourRegressionSolution(problemData, this);
181    }
182    IRegressionSolution IRegressionModel.CreateRegressionSolution(IRegressionProblemData problemData) {
183      return CreateRegressionSolution(problemData);
184    }
185    public INearestNeighbourClassificationSolution CreateClassificationSolution(IClassificationProblemData problemData) {
186      return new NearestNeighbourClassificationSolution(problemData, this);
187    }
188    IClassificationSolution IClassificationModel.CreateClassificationSolution(IClassificationProblemData problemData) {
189      return CreateClassificationSolution(problemData);
190    }
191
192    #region events
193    public event EventHandler Changed;
194    private void OnChanged(EventArgs e) {
195      var handlers = Changed;
196      if (handlers != null)
197        handlers(this, e);
198    }
199    #endregion
200
201    #region persistence
202    [Storable]
203    public double KDTreeApproxF {
204      get { return kdTree.approxf; }
205      set { kdTree.approxf = value; }
206    }
207    [Storable]
208    public double[] KDTreeBoxMax {
209      get { return kdTree.boxmax; }
210      set { kdTree.boxmax = value; }
211    }
212    [Storable]
213    public double[] KDTreeBoxMin {
214      get { return kdTree.boxmin; }
215      set { kdTree.boxmin = value; }
216    }
217    [Storable]
218    public double[] KDTreeBuf {
219      get { return kdTree.buf; }
220      set { kdTree.buf = value; }
221    }
222    [Storable]
223    public double[] KDTreeCurBoxMax {
224      get { return kdTree.curboxmax; }
225      set { kdTree.curboxmax = value; }
226    }
227    [Storable]
228    public double[] KDTreeCurBoxMin {
229      get { return kdTree.curboxmin; }
230      set { kdTree.curboxmin = value; }
231    }
232    [Storable]
233    public double KDTreeCurDist {
234      get { return kdTree.curdist; }
235      set { kdTree.curdist = value; }
236    }
237    [Storable]
238    public int KDTreeDebugCounter {
239      get { return kdTree.debugcounter; }
240      set { kdTree.debugcounter = value; }
241    }
242    [Storable]
243    public int KDTreeDistMatrixType {
244      get { return kdTree.distmatrixtype; }
245      set { kdTree.distmatrixtype = value; }
246    }
247    [Storable]
248    public int[] KDTreeIdx {
249      get { return kdTree.idx; }
250      set { kdTree.idx = value; }
251    }
252    [Storable]
253    public int KDTreeKCur {
254      get { return kdTree.kcur; }
255      set { kdTree.kcur = value; }
256    }
257    [Storable]
258    public int KDTreeKNeeded {
259      get { return kdTree.kneeded; }
260      set { kdTree.kneeded = value; }
261    }
262    [Storable]
263    public int KDTreeN {
264      get { return kdTree.n; }
265      set { kdTree.n = value; }
266    }
267    [Storable]
268    public int[] KDTreeNodes {
269      get { return kdTree.nodes; }
270      set { kdTree.nodes = value; }
271    }
272    [Storable]
273    public int KDTreeNormType {
274      get { return kdTree.normtype; }
275      set { kdTree.normtype = value; }
276    }
277    [Storable]
278    public int KDTreeNX {
279      get { return kdTree.nx; }
280      set { kdTree.nx = value; }
281    }
282    [Storable]
283    public int KDTreeNY {
284      get { return kdTree.ny; }
285      set { kdTree.ny = value; }
286    }
287    [Storable]
288    public double[] KDTreeR {
289      get { return kdTree.r; }
290      set { kdTree.r = value; }
291    }
292    [Storable]
293    public double KDTreeRNeeded {
294      get { return kdTree.rneeded; }
295      set { kdTree.rneeded = value; }
296    }
297    [Storable]
298    public bool KDTreeSelfMatch {
299      get { return kdTree.selfmatch; }
300      set { kdTree.selfmatch = value; }
301    }
302    [Storable]
303    public double[] KDTreeSplits {
304      get { return kdTree.splits; }
305      set { kdTree.splits = value; }
306    }
307    [Storable]
308    public int[] KDTreeTags {
309      get { return kdTree.tags; }
310      set { kdTree.tags = value; }
311    }
312    [Storable]
313    public double[] KDTreeX {
314      get { return kdTree.x; }
315      set { kdTree.x = value; }
316    }
317    [Storable]
318    public double[,] KDTreeXY {
319      get { return kdTree.xy; }
320      set { kdTree.xy = value; }
321    }
322    #endregion
323  }
324}
Note: See TracBrowser for help on using the repository browser.