1  #region License Information


2  /* HeuristicLab


3  * Copyright (C) 20022012 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 


22  using System;


23  using System.Collections.Generic;


24  using System.Linq;


25  using HeuristicLab.Common;


26  using HeuristicLab.Core;


27  using HeuristicLab.Data;


28  using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;


29  using HeuristicLab.Optimization;


30  using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;


31  using HeuristicLab.Problems.DataAnalysis;


32  using HeuristicLab.Problems.DataAnalysis.Symbolic;


33  using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;


34  using HeuristicLab.Parameters;


35 


36  namespace HeuristicLab.Algorithms.DataAnalysis {


37  /// <summary>


38  /// Nearest neighbour classification data analysis algorithm.


39  /// </summary>


40  [Item("Nearest Neighbour Classification", "Nearest neighbour classification data analysis algorithm (wrapper for ALGLIB).")]


41  [Creatable("Data Analysis")]


42  [StorableClass]


43  public sealed class NearestNeighbourClassification : FixedDataAnalysisAlgorithm<IClassificationProblem> {


44  private const string KParameterName = "K";


45  private const string NearestNeighbourClassificationModelResultName = "Nearest neighbour classification solution";


46 


47  #region parameter properties


48  public IFixedValueParameter<IntValue> KParameter {


49  get { return (IFixedValueParameter<IntValue>)Parameters[KParameterName]; }


50  }


51  #endregion


52  #region properties


53  public int K {


54  get { return KParameter.Value.Value; }


55  set {


56  if (value <= 0) throw new ArgumentException("K must be larger than zero.", "K");


57  else KParameter.Value.Value = value;


58  }


59  }


60  #endregion


61 


62  [StorableConstructor]


63  private NearestNeighbourClassification(bool deserializing) : base(deserializing) { }


64  private NearestNeighbourClassification(NearestNeighbourClassification original, Cloner cloner)


65  : base(original, cloner) {


66  }


67  public NearestNeighbourClassification()


68  : base() {


69  Parameters.Add(new FixedValueParameter<IntValue>(KParameterName, "The number of nearest neighbours to consider for regression.", new IntValue(3)));


70  Problem = new ClassificationProblem();


71  }


72  [StorableHook(HookType.AfterDeserialization)]


73  private void AfterDeserialization() { }


74 


75  public override IDeepCloneable Clone(Cloner cloner) {


76  return new NearestNeighbourClassification(this, cloner);


77  }


78 


79  #region nearest neighbour


80  protected override void Run() {


81  var solution = CreateNearestNeighbourClassificationSolution(Problem.ProblemData, K);


82  Results.Add(new Result(NearestNeighbourClassificationModelResultName, "The nearest neighbour classification solution.", solution));


83  }


84 


85  public static IClassificationSolution CreateNearestNeighbourClassificationSolution(IClassificationProblemData problemData, int k) {


86  Dataset dataset = problemData.Dataset;


87  string targetVariable = problemData.TargetVariable;


88  IEnumerable<string> allowedInputVariables = problemData.AllowedInputVariables;


89  IEnumerable<int> rows = problemData.TrainingIndices;


90  double[,] inputMatrix = AlglibUtil.PrepareInputMatrix(dataset, allowedInputVariables.Concat(new string[] { targetVariable }), rows);


91  if (inputMatrix.Cast<double>().Any(x => double.IsNaN(x)  double.IsInfinity(x)))


92  throw new NotSupportedException("Nearest neighbour classification does not support NaN or infinity values in the input dataset.");


93 


94  alglib.nearestneighbor.kdtree kdtree = new alglib.nearestneighbor.kdtree();


95 


96  int nRows = inputMatrix.GetLength(0);


97  int nFeatures = inputMatrix.GetLength(1)  1;


98  double[] classValues = dataset.GetDoubleValues(targetVariable).Distinct().OrderBy(x => x).ToArray();


99  int nClasses = classValues.Count();


100  // map original class values to values [0..nClasses1]


101  Dictionary<double, double> classIndices = new Dictionary<double, double>();


102  for (int i = 0; i < nClasses; i++) {


103  classIndices[classValues[i]] = i;


104  }


105  for (int row = 0; row < nRows; row++) {


106  inputMatrix[row, nFeatures] = classIndices[inputMatrix[row, nFeatures]];


107  }


108  alglib.nearestneighbor.kdtreebuild(inputMatrix, nRows, inputMatrix.GetLength(1)  1, 1, 2, kdtree);


109  var problemDataClone = (IClassificationProblemData) problemData.Clone();


110  return new NearestNeighbourClassificationSolution(problemDataClone, new NearestNeighbourModel(kdtree, k, targetVariable, allowedInputVariables, problemDataClone.ClassValues.ToArray()));


111  }


112  #endregion


113  }


114  }

