Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/NearestNeighbour/NearestNeighbourModel.cs @ 6603

Last change on this file since 6603 was 6603, checked in by mkommend, 13 years ago

#1600: Added possibility to create regression solutions from regression models.

File size: 10.7 KB
RevLine 
[6583]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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
[6603]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
[6583]186    #region events
187    public event EventHandler Changed;
188    private void OnChanged(EventArgs e) {
189      var handlers = Changed;
190      if (handlers != null)
191        handlers(this, e);
192    }
193    #endregion
194
195    #region persistence
[6584]196    [Storable]
197    public double KDTreeApproxF {
198      get { return kdTree.approxf; }
199      set { kdTree.approxf = value; }
200    }
201    [Storable]
202    public double[] KDTreeBoxMax {
203      get { return kdTree.boxmax; }
204      set { kdTree.boxmax = value; }
205    }
206    [Storable]
207    public double[] KDTreeBoxMin {
208      get { return kdTree.boxmin; }
209      set { kdTree.boxmin = value; }
210    }
211    [Storable]
212    public double[] KDTreeBuf {
213      get { return kdTree.buf; }
214      set { kdTree.buf = value; }
215    }
216    [Storable]
217    public double[] KDTreeCurBoxMax {
218      get { return kdTree.curboxmax; }
219      set { kdTree.curboxmax = value; }
220    }
221    [Storable]
222    public double[] KDTreeCurBoxMin {
223      get { return kdTree.curboxmin; }
224      set { kdTree.curboxmin = value; }
225    }
226    [Storable]
227    public double KDTreeCurDist {
228      get { return kdTree.curdist; }
229      set { kdTree.curdist = value; }
230    }
231    [Storable]
232    public int KDTreeDebugCounter {
233      get { return kdTree.debugcounter; }
234      set { kdTree.debugcounter = value; }
235    }
236    [Storable]
237    public int KDTreeDistMatrixType {
238      get { return kdTree.distmatrixtype; }
239      set { kdTree.distmatrixtype = value; }
240    }
241    [Storable]
242    public int[] KDTreeIdx {
243      get { return kdTree.idx; }
244      set { kdTree.idx = value; }
245    }
246    [Storable]
247    public int KDTreeKCur {
248      get { return kdTree.kcur; }
249      set { kdTree.kcur = value; }
250    }
251    [Storable]
252    public int KDTreeKNeeded {
253      get { return kdTree.kneeded; }
254      set { kdTree.kneeded = value; }
255    }
256    [Storable]
257    public int KDTreeN {
258      get { return kdTree.n; }
259      set { kdTree.n = value; }
260    }
261    [Storable]
262    public int[] KDTreeNodes {
263      get { return kdTree.nodes; }
264      set { kdTree.nodes = value; }
265    }
266    [Storable]
267    public int KDTreeNormType {
268      get { return kdTree.normtype; }
269      set { kdTree.normtype = value; }
270    }
271    [Storable]
272    public int KDTreeNX {
273      get { return kdTree.nx; }
274      set { kdTree.nx = value; }
275    }
276    [Storable]
277    public int KDTreeNY {
278      get { return kdTree.ny; }
279      set { kdTree.ny = value; }
280    }
281    [Storable]
282    public double[] KDTreeR {
283      get { return kdTree.r; }
284      set { kdTree.r = value; }
285    }
286    [Storable]
287    public double KDTreeRNeeded {
288      get { return kdTree.rneeded; }
289      set { kdTree.rneeded = value; }
290    }
291    [Storable]
292    public bool KDTreeSelfMatch {
293      get { return kdTree.selfmatch; }
294      set { kdTree.selfmatch = value; }
295    }
296    [Storable]
297    public double[] KDTreeSplits {
298      get { return kdTree.splits; }
299      set { kdTree.splits = value; }
300    }
301    [Storable]
302    public int[] KDTreeTags {
303      get { return kdTree.tags; }
304      set { kdTree.tags = value; }
305    }
306    [Storable]
307    public double[] KDTreeX {
308      get { return kdTree.x; }
309      set { kdTree.x = value; }
310    }
311    [Storable]
312    public double[,] KDTreeXY {
313      get { return kdTree.xy; }
314      set { kdTree.xy = value; }
315    }
[6583]316    #endregion
317  }
318}
Note: See TracBrowser for help on using the repository browser.