Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Algorithms.DataAnalysis/3.4/Linear/LinearDiscriminantAnalysis.cs @ 13956

Last change on this file since 13956 was 6760, checked in by epitzer, 13 years ago

#1530 integrate changes from trunk

File size: 5.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Optimization;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.Problems.DataAnalysis;
31using HeuristicLab.Problems.DataAnalysis.Symbolic;
32using HeuristicLab.Problems.DataAnalysis.Symbolic.Classification;
33
34namespace HeuristicLab.Algorithms.DataAnalysis {
35  /// <summary>
36  /// Linear discriminant analysis classification algorithm.
37  /// </summary>
38  [Item("Linear Discriminant Analysis", "Linear discriminant analysis classification algorithm (wrapper for ALGLIB).")]
39  [Creatable("Data Analysis")]
40  [StorableClass]
41  public sealed class LinearDiscriminantAnalysis : FixedDataAnalysisAlgorithm<IClassificationProblem> {
42    private const string LinearDiscriminantAnalysisSolutionResultName = "Linear discriminant analysis solution";
43
44    [StorableConstructor]
45    private LinearDiscriminantAnalysis(bool deserializing) : base(deserializing) { }
46    private LinearDiscriminantAnalysis(LinearDiscriminantAnalysis original, Cloner cloner)
47      : base(original, cloner) {
48    }
49    public LinearDiscriminantAnalysis()
50      : base() {
51      Problem = new ClassificationProblem();
52    }
53
54    public override IDeepCloneable Clone(Cloner cloner) {
55      return new LinearDiscriminantAnalysis(this, cloner);
56    }
57
58    #region Fisher LDA
59    protected override void Run() {
60      var solution = CreateLinearDiscriminantAnalysisSolution(Problem.ProblemData);
61      Results.Add(new Result(LinearDiscriminantAnalysisSolutionResultName, "The linear discriminant analysis.", solution));
62    }
63
64    public static IClassificationSolution CreateLinearDiscriminantAnalysisSolution(IClassificationProblemData problemData) {
65      Dataset dataset = problemData.Dataset;
66      string targetVariable = problemData.TargetVariable;
67      IEnumerable<string> allowedInputVariables = problemData.AllowedInputVariables;
68      IEnumerable<int> rows = problemData.TrainingIndizes;
69      int nClasses = problemData.ClassNames.Count();
70      double[,] inputMatrix = AlglibUtil.PrepareInputMatrix(dataset, allowedInputVariables.Concat(new string[] { targetVariable }), rows);
71      if (inputMatrix.Cast<double>().Any(x => double.IsNaN(x) || double.IsInfinity(x)))
72        throw new NotSupportedException("Linear discriminant analysis does not support NaN or infinity values in the input dataset.");
73
74      // change class values into class index
75      int targetVariableColumn = inputMatrix.GetLength(1) - 1;
76      List<double> classValues = problemData.ClassValues.OrderBy(x => x).ToList();
77      for (int row = 0; row < inputMatrix.GetLength(0); row++) {
78        inputMatrix[row, targetVariableColumn] = classValues.IndexOf(inputMatrix[row, targetVariableColumn]);
79      }
80      int info;
81      double[] w;
82      alglib.fisherlda(inputMatrix, inputMatrix.GetLength(0), allowedInputVariables.Count(), nClasses, out info, out w);
83      if (info < 1) throw new ArgumentException("Error in calculation of linear discriminant analysis solution");
84
85      ISymbolicExpressionTree tree = new SymbolicExpressionTree(new ProgramRootSymbol().CreateTreeNode());
86      ISymbolicExpressionTreeNode startNode = new StartSymbol().CreateTreeNode();
87      tree.Root.AddSubtree(startNode);
88      ISymbolicExpressionTreeNode addition = new Addition().CreateTreeNode();
89      startNode.AddSubtree(addition);
90
91      int col = 0;
92      foreach (string column in allowedInputVariables) {
93        VariableTreeNode vNode = (VariableTreeNode)new HeuristicLab.Problems.DataAnalysis.Symbolic.Variable().CreateTreeNode();
94        vNode.VariableName = column;
95        vNode.Weight = w[col];
96        addition.AddSubtree(vNode);
97        col++;
98      }
99
100      ConstantTreeNode cNode = (ConstantTreeNode)new Constant().CreateTreeNode();
101      cNode.Value = w[w.Length - 1];
102      addition.AddSubtree(cNode);
103
104
105      var model = LinearDiscriminantAnalysis.CreateDiscriminantFunctionModel(tree, new SymbolicDataAnalysisExpressionTreeInterpreter(), problemData, rows);
106      SymbolicDiscriminantFunctionClassificationSolution solution = new SymbolicDiscriminantFunctionClassificationSolution(model, (IClassificationProblemData)problemData.Clone());
107
108      return solution;
109    }
110    #endregion
111
112    private static SymbolicDiscriminantFunctionClassificationModel CreateDiscriminantFunctionModel(ISymbolicExpressionTree tree,
113      ISymbolicDataAnalysisExpressionTreeInterpreter interpreter,
114      IClassificationProblemData problemData,
115      IEnumerable<int> rows) {
116      return new SymbolicDiscriminantFunctionClassificationModel(tree, interpreter);
117    }
118  }
119}
Note: See TracBrowser for help on using the repository browser.