Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/DiscriminantFunctionClassificationModel.cs @ 18131

Last change on this file since 18131 was 17866, checked in by gkronber, 4 years ago

#3054: merged r17422:17423 from trunk to stable

File size: 6.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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 HEAL.Attic;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28
29namespace HeuristicLab.Problems.DataAnalysis {
30  /// <summary>
31  /// Represents discriminant function classification data analysis models.
32  /// </summary>
33  [StorableType("E7A8648D-C938-499F-A712-185542095708")]
34  [Item("DiscriminantFunctionClassificationModel", "Represents a classification model that uses a discriminant function and classification thresholds.")]
35  public class DiscriminantFunctionClassificationModel : ClassificationModel, IDiscriminantFunctionClassificationModel {
36    public override IEnumerable<string> VariablesUsedForPrediction {
37      get { return model.VariablesUsedForPrediction; }
38    }
39
40    [Storable]
41    private IRegressionModel model;
42    public IRegressionModel Model {
43      get { return model; }
44      private set { model = value; }
45    }
46
47    [Storable]
48    private double[] classValues;
49    public IEnumerable<double> ClassValues {
50      get { return (double[])classValues.Clone(); }
51      private set { classValues = value.ToArray(); }
52    }
53
54    [Storable]
55    private double[] thresholds;
56    public IEnumerable<double> Thresholds {
57      get { return (IEnumerable<double>)thresholds.Clone(); }
58      private set { thresholds = value.ToArray(); }
59    }
60
61    private IDiscriminantFunctionThresholdCalculator thresholdCalculator;
62    [Storable]
63    public IDiscriminantFunctionThresholdCalculator ThresholdCalculator {
64      get { return thresholdCalculator; }
65      private set { thresholdCalculator = value; }
66    }
67
68
69    [StorableConstructor]
70    protected DiscriminantFunctionClassificationModel(StorableConstructorFlag _) : base(_) { }
71    protected DiscriminantFunctionClassificationModel(DiscriminantFunctionClassificationModel original, Cloner cloner)
72      : base(original, cloner) {
73      model = cloner.Clone(original.model);
74      classValues = (double[])original.classValues.Clone();
75      thresholds = (double[])original.thresholds.Clone();
76      thresholdCalculator = (IDiscriminantFunctionThresholdCalculator)original.thresholdCalculator.Clone();
77    }
78
79    public DiscriminantFunctionClassificationModel(IRegressionModel model, IDiscriminantFunctionThresholdCalculator thresholdCalculator)
80      : base(model.TargetVariable) {
81      this.name = ItemName;
82      this.description = ItemDescription;
83
84      this.model = model;
85      this.classValues = new double[0];
86      this.thresholds = new double[0];
87      this.thresholdCalculator = thresholdCalculator;
88    }
89
90    [StorableHook(HookType.AfterDeserialization)]
91    private void AfterDeserialization() {
92      if (ThresholdCalculator == null) ThresholdCalculator = new AccuracyMaximizationThresholdCalculator();
93    }
94
95    public override IDeepCloneable Clone(Cloner cloner) {
96      return new DiscriminantFunctionClassificationModel(this, cloner);
97    }
98
99    public void SetThresholdsAndClassValues(IEnumerable<double> thresholds, IEnumerable<double> classValues) {
100      var classValuesArr = classValues.ToArray();
101      var thresholdsArr = thresholds.ToArray();
102      if (thresholdsArr.Length != classValuesArr.Length) throw new ArgumentException();
103
104      this.classValues = classValuesArr;
105      this.thresholds = thresholdsArr;
106      OnThresholdsChanged(EventArgs.Empty);
107    }
108
109    public virtual void RecalculateModelParameters(IClassificationProblemData problemData, IEnumerable<int> rows) {
110      double[] classValues;
111      double[] thresholds;
112      var targetClassValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
113      var estimatedTrainingValues = GetEstimatedValues(problemData.Dataset, rows);
114      thresholdCalculator.Calculate(problemData, estimatedTrainingValues, targetClassValues, out classValues, out thresholds);
115      SetThresholdsAndClassValues(thresholds, classValues);
116    }
117
118
119    public IEnumerable<double> GetEstimatedValues(IDataset dataset, IEnumerable<int> rows) {
120      return model.GetEstimatedValues(dataset, rows);
121    }
122
123    public override IEnumerable<double> GetEstimatedClassValues(IDataset dataset, IEnumerable<int> rows) {
124      var estimatedValues = GetEstimatedValues(dataset, rows);
125      return GetEstimatedClassValues(estimatedValues);
126    }
127
128    public virtual IEnumerable<double> GetEstimatedClassValues(IEnumerable<double> estimatedValues) {
129      if (!Thresholds.Any() && !ClassValues.Any()) throw new ArgumentException("No thresholds and class values were set for the current classification model.");
130      foreach (var x in estimatedValues) {
131        int classIndex = 0;
132        // find first threshold value which is larger than x => class index = threshold index + 1
133        for (int i = 0; i < thresholds.Length; i++) {
134          if (x > thresholds[i]) classIndex++;
135          else break;
136        }
137        yield return classValues.ElementAt(classIndex - 1);
138      }
139    }
140
141    #region events
142    public event EventHandler ThresholdsChanged;
143    protected virtual void OnThresholdsChanged(EventArgs e) {
144      var listener = ThresholdsChanged;
145      if (listener != null) listener(this, e);
146    }
147    #endregion
148
149    public override IClassificationSolution CreateClassificationSolution(IClassificationProblemData problemData) {
150      return CreateDiscriminantFunctionClassificationSolution(problemData);
151    }
152    public virtual IDiscriminantFunctionClassificationSolution CreateDiscriminantFunctionClassificationSolution(
153      IClassificationProblemData problemData) {
154      return new DiscriminantFunctionClassificationSolution(this, new ClassificationProblemData(problemData));
155    }
156  }
157}
Note: See TracBrowser for help on using the repository browser.