Free cookie consent management tool by TermsFeed Policy Generator

source: branches/symbreg-factors-2650/HeuristicLab.Algorithms.DataAnalysis/3.4/BaselineClassifiers/OneR.cs @ 14242

Last change on this file since 14242 was 14242, checked in by gkronber, 8 years ago

#2650: added support for factor variables to OneR algorithm

File size: 10.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Data;
28using HeuristicLab.Optimization;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Problems.DataAnalysis;
32
33namespace HeuristicLab.Algorithms.DataAnalysis {
34  /// <summary>
35  /// 1R classification algorithm.
36  /// </summary>
37  [Item("OneR Classification", "A simple classification algorithm the searches the best single-variable split (does not support categorical features correctly). See R.C. Holte (1993). Very simple classification rules perform well on most commonly used datasets. Machine Learning. 11:63-91.")]
38  [StorableClass]
39  public sealed class OneR : FixedDataAnalysisAlgorithm<IClassificationProblem> {
40
41    public IValueParameter<IntValue> MinBucketSizeParameter {
42      get { return (IValueParameter<IntValue>)Parameters["MinBucketSize"]; }
43    }
44
45    [StorableConstructor]
46    private OneR(bool deserializing) : base(deserializing) { }
47
48    private OneR(OneR original, Cloner cloner)
49      : base(original, cloner) { }
50
51    public OneR()
52      : base() {
53      Parameters.Add(new ValueParameter<IntValue>("MinBucketSize", "Minimum size of a bucket for numerical values. (Except for the rightmost bucket)", new IntValue(6)));
54      Problem = new ClassificationProblem();
55    }
56
57    public override IDeepCloneable Clone(Cloner cloner) {
58      return new OneR(this, cloner);
59    }
60
61    protected override void Run() {
62      var solution = CreateOneRSolution(Problem.ProblemData, MinBucketSizeParameter.Value.Value);
63      Results.Add(new Result("OneR solution", "The 1R classifier.", solution));
64    }
65
66    public static IClassificationSolution CreateOneRSolution(IClassificationProblemData problemData, int minBucketSize = 6) {
67      var classValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
68      var model1 = FindBestDoubleVariableModel(problemData, minBucketSize);
69      var model2 = FindBestFactorModel(problemData);
70
71      if (model1 == null && model2 == null) throw new InvalidProgramException("Could not create OneR solution");
72      else if (model1 == null) return new OneFactorClassificationSolution(model2, (IClassificationProblemData)problemData.Clone());
73      else if (model2 == null) return new OneRClassificationSolution(model1, (IClassificationProblemData)problemData.Clone());
74      else {
75        var model1EstimatedValues = model1.GetEstimatedClassValues(problemData.Dataset, problemData.TrainingIndices);
76        var model1NumCorrect = classValues.Zip(model1EstimatedValues, (a, b) => a.IsAlmost(b)).Count(e => e);
77
78        var model2EstimatedValues = model2.GetEstimatedClassValues(problemData.Dataset, problemData.TrainingIndices);
79        var model2NumCorrect = classValues.Zip(model2EstimatedValues, (a, b) => a.IsAlmost(b)).Count(e => e);
80
81        if (model1NumCorrect > model2NumCorrect) {
82          return new OneRClassificationSolution(model1, (IClassificationProblemData)problemData.Clone());
83        } else {
84          return new OneFactorClassificationSolution(model2, (IClassificationProblemData)problemData.Clone());
85        }
86      }
87    }
88
89    private static OneRClassificationModel FindBestDoubleVariableModel(IClassificationProblemData problemData, int minBucketSize = 6) {
90      var bestClassified = 0;
91      List<Split> bestSplits = null;
92      string bestVariable = string.Empty;
93      double bestMissingValuesClass = double.NaN;
94      var classValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
95
96      var allowedInputVariables = problemData.AllowedInputVariables.Where(problemData.Dataset.VariableHasType<double>);
97
98      if (!allowedInputVariables.Any()) return null;
99
100      foreach (var variable in allowedInputVariables) {
101        var inputValues = problemData.Dataset.GetDoubleValues(variable, problemData.TrainingIndices);
102        var samples = inputValues.Zip(classValues, (i, v) => new Sample(i, v)).OrderBy(s => s.inputValue);
103
104        var missingValuesDistribution = samples
105          .Where(s => double.IsNaN(s.inputValue)).GroupBy(s => s.classValue)
106          .ToDictionary(s => s.Key, s => s.Count())
107          .MaxItems(s => s.Value)
108          .FirstOrDefault();
109
110        //calculate class distributions for all distinct inputValues
111        List<Dictionary<double, int>> classDistributions = new List<Dictionary<double, int>>();
112        List<double> thresholds = new List<double>();
113        double lastValue = double.NaN;
114        foreach (var sample in samples.Where(s => !double.IsNaN(s.inputValue))) {
115          if (sample.inputValue > lastValue || double.IsNaN(lastValue)) {
116            if (!double.IsNaN(lastValue)) thresholds.Add((lastValue + sample.inputValue) / 2);
117            lastValue = sample.inputValue;
118            classDistributions.Add(new Dictionary<double, int>());
119            foreach (var classValue in problemData.ClassValues)
120              classDistributions[classDistributions.Count - 1][classValue] = 0;
121
122          }
123          classDistributions[classDistributions.Count - 1][sample.classValue]++;
124        }
125        thresholds.Add(double.PositiveInfinity);
126
127        var distribution = classDistributions[0];
128        var threshold = thresholds[0];
129        var splits = new List<Split>();
130
131        for (int i = 1; i < classDistributions.Count; i++) {
132          var samplesInSplit = distribution.Max(d => d.Value);
133          //join splits if there are too few samples in the split or the distributions has the same maximum class value as the current split
134          if (samplesInSplit < minBucketSize ||
135            classDistributions[i].MaxItems(d => d.Value).Select(d => d.Key).Contains(
136              distribution.MaxItems(d => d.Value).Select(d => d.Key).First())) {
137            foreach (var classValue in classDistributions[i])
138              distribution[classValue.Key] += classValue.Value;
139            threshold = thresholds[i];
140          } else {
141            splits.Add(new Split(threshold, distribution.MaxItems(d => d.Value).Select(d => d.Key).First()));
142            distribution = classDistributions[i];
143            threshold = thresholds[i];
144          }
145        }
146        splits.Add(new Split(double.PositiveInfinity, distribution.MaxItems(d => d.Value).Select(d => d.Key).First()));
147
148        int correctClassified = 0;
149        int splitIndex = 0;
150        foreach (var sample in samples.Where(s => !double.IsNaN(s.inputValue))) {
151          while (sample.inputValue >= splits[splitIndex].thresholdValue)
152            splitIndex++;
153          correctClassified += sample.classValue.IsAlmost(splits[splitIndex].classValue) ? 1 : 0;
154        }
155        correctClassified += missingValuesDistribution.Value;
156
157        if (correctClassified > bestClassified) {
158          bestClassified = correctClassified;
159          bestSplits = splits;
160          bestVariable = variable;
161          bestMissingValuesClass = missingValuesDistribution.Value == 0 ? double.NaN : missingValuesDistribution.Key;
162        }
163      }
164
165      //remove neighboring splits with the same class value
166      for (int i = 0; i < bestSplits.Count - 1; i++) {
167        if (bestSplits[i].classValue.IsAlmost(bestSplits[i + 1].classValue)) {
168          bestSplits.Remove(bestSplits[i]);
169          i--;
170        }
171      }
172
173      var model = new OneRClassificationModel(problemData.TargetVariable, bestVariable,
174        bestSplits.Select(s => s.thresholdValue).ToArray(),
175        bestSplits.Select(s => s.classValue).ToArray(), bestMissingValuesClass);
176
177      return model;
178    }
179    private static OneFactorClassificationModel FindBestFactorModel(IClassificationProblemData problemData) {
180      var classValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
181      var defaultClass = FindMostFrequentClassValue(classValues);
182      // only select string variables
183      var allowedInputVariables = problemData.AllowedInputVariables.Where(problemData.Dataset.VariableHasType<string>);
184
185      if (!allowedInputVariables.Any()) return null;
186
187      OneFactorClassificationModel bestModel = null;
188      var bestModelNumCorrect = 0;
189
190      foreach (var variable in allowedInputVariables) {
191        var variableValues = problemData.Dataset.GetStringValues(variable, problemData.TrainingIndices);
192        var groupedClassValues = variableValues
193          .Zip(classValues, (v, c) => new KeyValuePair<string, double>(v, c))
194          .GroupBy(kvp => kvp.Key)
195          .ToDictionary(g => g.Key, g => FindMostFrequentClassValue(g.Select(kvp => kvp.Value)));
196
197        var model = new OneFactorClassificationModel(problemData.TargetVariable, variable,
198          groupedClassValues.Select(kvp => kvp.Key).ToArray(), groupedClassValues.Select(kvp => kvp.Value).ToArray(), defaultClass);
199
200        var modelEstimatedValues = model.GetEstimatedClassValues(problemData.Dataset, problemData.TrainingIndices);
201        var modelNumCorrect = classValues.Zip(modelEstimatedValues, (a, b) => a.IsAlmost(b)).Count(e => e);
202        if (modelNumCorrect > bestModelNumCorrect) {
203          bestModelNumCorrect = modelNumCorrect;
204          bestModel = model;
205        }
206      }
207
208      return bestModel;
209    }
210
211    private static double FindMostFrequentClassValue(IEnumerable<double> classValues) {
212      return classValues.GroupBy(c => c).OrderByDescending(g => g.Count()).Select(g => g.Key).First();
213    }
214
215    #region helper classes
216    private class Split {
217      public double thresholdValue;
218      public double classValue;
219
220      public Split(double thresholdValue, double classValue) {
221        this.thresholdValue = thresholdValue;
222        this.classValue = classValue;
223      }
224    }
225
226    private class Sample {
227      public double inputValue;
228      public double classValue;
229
230      public Sample(double inputValue, double classValue) {
231        this.inputValue = inputValue;
232        this.classValue = classValue;
233      }
234    }
235    #endregion
236  }
237}
Note: See TracBrowser for help on using the repository browser.