Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/NearestNeighbour/NearestNeighbourClassification.cs @ 14778

Last change on this file since 14778 was 14523, checked in by mkommend, 8 years ago

#2524:

  • Renamed pausable to SupportsPause
  • Changed SupportsPause field to abstract property that has to be implemented
  • Stored initialization flag in BasicAlgorithm
  • Changed CancellationToken access to use the according property
  • Adapted HillClimber to new pausing mechanism
  • Disable pause for PPP, because it does not work correctly
  • Derived FixedDataAnalysisAlgorithm from BasicAlgorithm
  • Changed base class of all data analysis algorithm from BasicAlgorithm to FixedDataAnalysisAlgorithm
File size: 5.2 KB
RevLine 
[6577]1#region License Information
2/* HeuristicLab
[14185]3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[6577]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.Linq;
[14523]24using System.Threading;
[6577]25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Optimization;
[8465]29using HeuristicLab.Parameters;
[6577]30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Problems.DataAnalysis;
32
33namespace HeuristicLab.Algorithms.DataAnalysis {
34  /// <summary>
[6583]35  /// Nearest neighbour classification data analysis algorithm.
[6577]36  /// </summary>
[13238]37  [Item("Nearest Neighbour Classification (kNN)", "Nearest neighbour classification data analysis algorithm (wrapper for ALGLIB).")]
[12504]38  [Creatable(CreatableAttribute.Categories.DataAnalysisClassification, Priority = 150)]
[6577]39  [StorableClass]
[6583]40  public sealed class NearestNeighbourClassification : FixedDataAnalysisAlgorithm<IClassificationProblem> {
41    private const string KParameterName = "K";
42    private const string NearestNeighbourClassificationModelResultName = "Nearest neighbour classification solution";
[14235]43    private const string WeightsParameterName = "Weights";
[6578]44
[14235]45
[6578]46    #region parameter properties
[6583]47    public IFixedValueParameter<IntValue> KParameter {
48      get { return (IFixedValueParameter<IntValue>)Parameters[KParameterName]; }
[6578]49    }
[14235]50    public IValueParameter<DoubleArray> WeightsParameter {
51      get { return (IValueParameter<DoubleArray>)Parameters[WeightsParameterName]; }
52    }
[6578]53    #endregion
54    #region properties
[6583]55    public int K {
56      get { return KParameter.Value.Value; }
[6578]57      set {
[6583]58        if (value <= 0) throw new ArgumentException("K must be larger than zero.", "K");
59        else KParameter.Value.Value = value;
[6578]60      }
61    }
[14235]62    public DoubleArray Weights {
63      get { return WeightsParameter.Value; }
64      set { WeightsParameter.Value = value; }
65    }
[6578]66    #endregion
67
[6577]68    [StorableConstructor]
[6583]69    private NearestNeighbourClassification(bool deserializing) : base(deserializing) { }
70    private NearestNeighbourClassification(NearestNeighbourClassification original, Cloner cloner)
[6577]71      : base(original, cloner) {
72    }
[6583]73    public NearestNeighbourClassification()
[6577]74      : base() {
[6583]75      Parameters.Add(new FixedValueParameter<IntValue>(KParameterName, "The number of nearest neighbours to consider for regression.", new IntValue(3)));
[14235]76      Parameters.Add(new OptionalValueParameter<DoubleArray>(WeightsParameterName, "Optional: use weights to specify individual scaling values for all features. If not set the weights are calculated automatically (each feature is scaled to unit variance)"));
[6583]77      Problem = new ClassificationProblem();
[6577]78    }
79    [StorableHook(HookType.AfterDeserialization)]
[14235]80    private void AfterDeserialization() {
81      // BackwardsCompatibility3.3
82      #region Backwards compatible code, remove with 3.4
83      if (!Parameters.ContainsKey(WeightsParameterName)) {
84        Parameters.Add(new OptionalValueParameter<DoubleArray>(WeightsParameterName, "Optional: use weights to specify individual scaling values for all features. If not set the weights are calculated automatically (each feature is scaled to unit variance)"));
85      }
86      #endregion
87    }
[6577]88
89    public override IDeepCloneable Clone(Cloner cloner) {
[6583]90      return new NearestNeighbourClassification(this, cloner);
[6577]91    }
92
[6583]93    #region nearest neighbour
[14523]94    protected override void Run(CancellationToken cancellationToken) {
[14235]95      double[] weights = null;
96      if (Weights != null) weights = Weights.CloneAsArray();
97      var solution = CreateNearestNeighbourClassificationSolution(Problem.ProblemData, K, weights);
[6583]98      Results.Add(new Result(NearestNeighbourClassificationModelResultName, "The nearest neighbour classification solution.", solution));
[6577]99    }
100
[14235]101    public static IClassificationSolution CreateNearestNeighbourClassificationSolution(IClassificationProblemData problemData, int k, double[] weights = null) {
[8465]102      var problemDataClone = (IClassificationProblemData)problemData.Clone();
[14235]103      return new NearestNeighbourClassificationSolution(Train(problemDataClone, k, weights), problemDataClone);
[8465]104    }
[6577]105
[14235]106    public static INearestNeighbourModel Train(IClassificationProblemData problemData, int k, double[] weights = null) {
[8465]107      return new NearestNeighbourModel(problemData.Dataset,
108        problemData.TrainingIndices,
109        k,
110        problemData.TargetVariable,
111        problemData.AllowedInputVariables,
[14235]112        weights,
[8465]113        problemData.ClassValues.ToArray());
[6577]114    }
115    #endregion
116  }
117}
Note: See TracBrowser for help on using the repository browser.