Free cookie consent management tool by TermsFeed Policy Generator

source: branches/M5Regression/HeuristicLab.Algorithms.DataAnalysis/3.4/M5Regression/MetaModels/M5RuleModel.cs @ 15430

Last change on this file since 15430 was 15430, checked in by bwerth, 6 years ago

#2847 first implementation of M5'-regression

File size: 7.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2017 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 System.Text;
26using System.Threading;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.Problems.DataAnalysis;
31
32namespace HeuristicLab.Algorithms.DataAnalysis {
33  [StorableClass]
34  internal class M5RuleModel : RegressionModel, IM5MetaModel {
35    internal const string NoCurrentLeafesResultName = "Number of current Leafs";
36
37    #region Properties
38    [Storable]
39    internal string[] SplitAtts { get; private set; }
40    [Storable]
41    private double[] SplitVals { get; set; }
42    [Storable]
43    private RelOp[] RelOps { get; set; }
44    [Storable]
45    protected IRegressionModel RuleModel { get; set; }
46    [Storable]
47    private IReadOnlyList<string> Variables { get; set; }
48    #endregion
49
50    #region HLConstructors
51    [StorableConstructor]
52    protected M5RuleModel(bool deserializing) : base(deserializing) { }
53    protected M5RuleModel(M5RuleModel original, Cloner cloner) : base(original, cloner) {
54      if (original.SplitAtts != null) SplitAtts = original.SplitAtts.ToArray();
55      if (original.SplitVals != null) SplitVals = original.SplitVals.ToArray();
56      if (original.RelOps != null) RelOps = original.RelOps.ToArray();
57      RuleModel = cloner.Clone(original.RuleModel);
58      if (original.Variables != null) Variables = original.Variables.ToList();
59    }
60    private M5RuleModel(string target) : base(target) { }
61    public override IDeepCloneable Clone(Cloner cloner) {
62      return new M5RuleModel(this, cloner);
63    }
64    #endregion
65
66    internal static M5RuleModel CreateRuleModel(string target, M5CreationParameters m5CreationParams) {
67      return m5CreationParams.LeafType is ILeafType<IConfidenceRegressionModel> ? new ConfidenceM5RuleModel(target) : new M5RuleModel(target);
68    }
69
70    #region IRegressionModel
71    public override IEnumerable<string> VariablesUsedForPrediction {
72      get { return Variables; }
73    }
74
75    public override IEnumerable<double> GetEstimatedValues(IDataset dataset, IEnumerable<int> rows) {
76      if (RuleModel == null) throw new NotSupportedException("M5P has not been built correctly");
77      return RuleModel.GetEstimatedValues(dataset, rows);
78    }
79
80    public override IRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData) {
81      return new RegressionSolution(this, problemData);
82    }
83    #endregion
84
85    #region IM5Component
86    public void BuildClassifier(IReadOnlyList<int> trainingRows, IReadOnlyList<int> holdoutRows, M5CreationParameters m5CreationParams, CancellationToken cancellation) {
87      Variables = m5CreationParams.AllowedInputVariables.ToList();
88      var tree = M5TreeModel.CreateTreeModel(m5CreationParams.TargetVariable, m5CreationParams);
89      ((IM5MetaModel) tree).BuildClassifier(trainingRows, holdoutRows, m5CreationParams, cancellation);
90      var nodeModel = tree.Root.EnumerateNodes().Where(x => x.IsLeaf).MaxItems(x => x.NumSamples).First();
91
92      var satts = new List<string>();
93      var svals = new List<double>();
94      var reops = new List<RelOp>();
95
96      //extract Splits
97      for (var temp = nodeModel; temp.Parent != null; temp = temp.Parent) {
98        satts.Add(temp.Parent.SplitAttr);
99        svals.Add(temp.Parent.SplitValue);
100        reops.Add(temp.Parent.Left == temp ? RelOp.Lessequal : RelOp.Greater);
101      }
102      nodeModel.ToRuleNode();
103      RuleModel = nodeModel.NodeModel;
104      RelOps = reops.ToArray();
105      SplitAtts = satts.ToArray();
106      SplitVals = svals.ToArray();
107    }
108
109    public void UpdateModel(IReadOnlyList<int> rows, M5UpdateParameters m5UpdateParameters, CancellationToken cancellation) {
110      BuildModel(rows, m5UpdateParameters.Random, m5UpdateParameters.Data, m5UpdateParameters.LeafType, cancellation);
111    }
112    #endregion
113
114    public bool Covers(IDataset dataset, int row) {
115      return !SplitAtts.Where((t, i) => !RelOps[i].Compare(dataset.GetDoubleValue(t, row), SplitVals[i])).Any();
116    }
117
118    public string ToCompactString() {
119      var mins = new Dictionary<string, double>();
120      var maxs = new Dictionary<string, double>();
121      for (var i = 0; i < SplitAtts.Length; i++) {
122        var n = SplitAtts[i];
123        var v = SplitVals[i];
124        if (!mins.ContainsKey(n)) mins.Add(n, double.NegativeInfinity);
125        if (!maxs.ContainsKey(n)) maxs.Add(n, double.PositiveInfinity);
126        if (RelOps[i] == RelOp.Lessequal) maxs[n] = Math.Min(maxs[n], v);
127        else mins[n] = Math.Max(mins[n], v);
128      }
129      if (maxs.Count == 0) return "";
130      var s = new StringBuilder();
131      foreach (var key in maxs.Keys)
132        s.Append(string.Format("{0} ∈ [{1:e2}; {2:e2}] && ", key, mins[key], maxs[key]));
133      s.Remove(s.Length - 4, 4);
134      return s.ToString();
135    }
136
137    #region Helpers
138    private void BuildModel(IReadOnlyList<int> rows, IRandom random, IDataset data, ILeafType<IRegressionModel> leafType, CancellationToken cancellation) {
139      var reducedData = new Dataset(VariablesUsedForPrediction.Concat(new[] {TargetVariable}), VariablesUsedForPrediction.Concat(new[] {TargetVariable}).Select(x => data.GetDoubleValues(x, rows).ToList()));
140      var pd = new RegressionProblemData(reducedData, VariablesUsedForPrediction, TargetVariable);
141      pd.TrainingPartition.Start = 0;
142      pd.TrainingPartition.End = pd.TestPartition.Start = pd.TestPartition.End = reducedData.Rows;
143
144      int noparams;
145      RuleModel = leafType.BuildModel(pd, random, cancellation, out noparams);
146      cancellation.ThrowIfCancellationRequested();
147    }
148    #endregion
149
150    [StorableClass]
151    private sealed class ConfidenceM5RuleModel : M5RuleModel, IConfidenceRegressionModel {
152      #region HLConstructors
153      [StorableConstructor]
154      private ConfidenceM5RuleModel(bool deserializing) : base(deserializing) { }
155      private ConfidenceM5RuleModel(ConfidenceM5RuleModel original, Cloner cloner) : base(original, cloner) { }
156      public ConfidenceM5RuleModel(string targetAttr) : base(targetAttr) { }
157      public override IDeepCloneable Clone(Cloner cloner) {
158        return new ConfidenceM5RuleModel(this, cloner);
159      }
160      #endregion
161
162      public IEnumerable<double> GetEstimatedVariances(IDataset dataset, IEnumerable<int> rows) {
163        return ((IConfidenceRegressionModel) RuleModel).GetEstimatedVariances(dataset, rows);
164      }
165
166      public override IRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData) {
167        return new ConfidenceRegressionSolution(this, problemData);
168      }
169    }
170  }
171
172  internal enum RelOp {
173    Lessequal,
174    Greater
175  }
176
177  internal static class RelOpExtentions {
178    public static bool Compare(this RelOp op, double x, double y) {
179      switch (op) {
180        case RelOp.Greater:
181          return x > y;
182        case RelOp.Lessequal:
183          return x <= y;
184        default:
185          throw new ArgumentOutOfRangeException(op.ToString(), op, null);
186      }
187    }
188  }
189}
Note: See TracBrowser for help on using the repository browser.