Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2972_PDPRowSelect/HeuristicLab.Algorithms.DataAnalysis/3.4/NearestNeighbour/NearestNeighbourClassification.cs @ 16518

Last change on this file since 16518 was 16518, checked in by pfleck, 5 years ago

#2972 merged trunk into branch

File size: 6.0 KB
RevLine 
[16518]1#region License Information
[6577]2/* HeuristicLab
[15583]3 * Copyright (C) 2002-2018 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";
[16518]44    private const string SelfMatchParameterName = "SelfMatch";
[6578]45
46    #region parameter properties
[6583]47    public IFixedValueParameter<IntValue> KParameter {
48      get { return (IFixedValueParameter<IntValue>)Parameters[KParameterName]; }
[6578]49    }
[16518]50    public IFixedValueParameter<BoolValue> SelfMatchParameter {
51      get { return (IFixedValueParameter<BoolValue>)Parameters[SelfMatchParameterName]; }
52    }
[14235]53    public IValueParameter<DoubleArray> WeightsParameter {
54      get { return (IValueParameter<DoubleArray>)Parameters[WeightsParameterName]; }
55    }
[6578]56    #endregion
57    #region properties
[16518]58    public bool SelfMatch {
59      get { return SelfMatchParameter.Value.Value; }
60      set { SelfMatchParameter.Value.Value = value; }
61    }
[6583]62    public int K {
63      get { return KParameter.Value.Value; }
[6578]64      set {
[6583]65        if (value <= 0) throw new ArgumentException("K must be larger than zero.", "K");
66        else KParameter.Value.Value = value;
[6578]67      }
68    }
[14235]69    public DoubleArray Weights {
70      get { return WeightsParameter.Value; }
71      set { WeightsParameter.Value = value; }
72    }
[6578]73    #endregion
74
[6577]75    [StorableConstructor]
[6583]76    private NearestNeighbourClassification(bool deserializing) : base(deserializing) { }
77    private NearestNeighbourClassification(NearestNeighbourClassification original, Cloner cloner)
[6577]78      : base(original, cloner) {
79    }
[6583]80    public NearestNeighbourClassification()
[6577]81      : base() {
[16518]82      Parameters.Add(new FixedValueParameter<BoolValue>(SelfMatchParameterName, "Should we use equal points for classification?", new BoolValue(false)));
[6583]83      Parameters.Add(new FixedValueParameter<IntValue>(KParameterName, "The number of nearest neighbours to consider for regression.", new IntValue(3)));
[14235]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)"));
[6583]85      Problem = new ClassificationProblem();
[6577]86    }
87    [StorableHook(HookType.AfterDeserialization)]
[14235]88    private void AfterDeserialization() {
89      // BackwardsCompatibility3.3
90      #region Backwards compatible code, remove with 3.4
91      if (!Parameters.ContainsKey(WeightsParameterName)) {
92        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)"));
93      }
[16518]94      if (!Parameters.ContainsKey(SelfMatchParameterName)) {
95        Parameters.Add(new FixedValueParameter<BoolValue>(SelfMatchParameterName, "Should we use equal points for classification?", new BoolValue(false)));
96      }
[14235]97      #endregion
98    }
[6577]99
100    public override IDeepCloneable Clone(Cloner cloner) {
[6583]101      return new NearestNeighbourClassification(this, cloner);
[6577]102    }
103
[6583]104    #region nearest neighbour
[14523]105    protected override void Run(CancellationToken cancellationToken) {
[14235]106      double[] weights = null;
107      if (Weights != null) weights = Weights.CloneAsArray();
[16518]108      var solution = CreateNearestNeighbourClassificationSolution(Problem.ProblemData, K, SelfMatch, weights);
[6583]109      Results.Add(new Result(NearestNeighbourClassificationModelResultName, "The nearest neighbour classification solution.", solution));
[6577]110    }
111
[16518]112    public static IClassificationSolution CreateNearestNeighbourClassificationSolution(IClassificationProblemData problemData, int k, bool selfMatch = false, double[] weights = null) {
[8465]113      var problemDataClone = (IClassificationProblemData)problemData.Clone();
[16518]114      return new NearestNeighbourClassificationSolution(Train(problemDataClone, k, selfMatch, weights), problemDataClone);
[8465]115    }
[6577]116
[16518]117    public static INearestNeighbourModel Train(IClassificationProblemData problemData, int k, bool selfMatch = false, double[] weights = null) {
[8465]118      return new NearestNeighbourModel(problemData.Dataset,
119        problemData.TrainingIndices,
120        k,
[16518]121        selfMatch,
[8465]122        problemData.TargetVariable,
123        problemData.AllowedInputVariables,
[14235]124        weights,
[8465]125        problemData.ClassValues.ToArray());
[6577]126    }
127    #endregion
128  }
129}
Note: See TracBrowser for help on using the repository browser.