Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis/3.4/Linear/MultinomialLogitClassification.cs @ 6567

Last change on this file since 6567 was 6567, checked in by gkronber, 13 years ago

#1475: added first implementation of wrapper classes for the ALGLIB implementation of multinomial logit classification.

File size: 5.2 KB
RevLine 
[6567]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.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Optimization;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Problems.DataAnalysis;
32using HeuristicLab.Problems.DataAnalysis.Symbolic;
33using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
34
35namespace HeuristicLab.Algorithms.DataAnalysis {
36  /// <summary>
37  /// Multinomial logit regression data analysis algorithm.
38  /// </summary>
39  [Item("Multinomial logit classification", "Multinomial logit classification data analysis algorithm (wrapper for ALGLIB).")]
40  [Creatable("Data Analysis")]
41  [StorableClass]
42  public sealed class MultiNomialLogitClassification : FixedDataAnalysisAlgorithm<IClassificationProblem> {
43    private const string LogitClassificationModelResultName = "Logit classification solution";
44
45    [StorableConstructor]
46    private MultiNomialLogitClassification(bool deserializing) : base(deserializing) { }
47    private MultiNomialLogitClassification(MultiNomialLogitClassification original, Cloner cloner)
48      : base(original, cloner) {
49    }
50    public MultiNomialLogitClassification()
51      : base() {
52      Problem = new ClassificationProblem();
53    }
54    [StorableHook(HookType.AfterDeserialization)]
55    private void AfterDeserialization() { }
56
57    public override IDeepCloneable Clone(Cloner cloner) {
58      return new MultiNomialLogitClassification(this, cloner);
59    }
60
61    #region logit regression
62    protected override void Run() {
63      double rmsError, relClassError;
64      var solution = CreateLogitClassificationSolution(Problem.ProblemData, out rmsError, out relClassError);
65      Results.Add(new Result(LogitClassificationModelResultName, "The linear regression solution.", solution));
66      Results.Add(new Result("Root mean square error", "The root of the mean of squared errors of the logit regression solution on the training set.", new DoubleValue(rmsError)));
67      Results.Add(new Result("Relative classification error", "Relative classification error on the training set (percentage of misclassified cases).", new PercentValue(relClassError)));
68    }
69
70    public static IClassificationSolution CreateLogitClassificationSolution(IClassificationProblemData problemData, out double rmsError, out double relClassError) {
71      Dataset dataset = problemData.Dataset;
72      string targetVariable = problemData.TargetVariable;
73      IEnumerable<string> allowedInputVariables = problemData.AllowedInputVariables;
74      IEnumerable<int> rows = problemData.TrainingIndizes;
75      double[,] inputMatrix = AlglibUtil.PrepareInputMatrix(dataset, allowedInputVariables.Concat(new string[] { targetVariable }), rows);
76      if (inputMatrix.Cast<double>().Any(x => double.IsNaN(x) || double.IsInfinity(x)))
77        throw new NotSupportedException("Multinomial logit classification does not support NaN or infinity values in the input dataset.");
78
79      alglib.logitmodel lm = new alglib.logitmodel();
80      alglib.mnlreport rep = new alglib.mnlreport();
81      int nRows = inputMatrix.GetLength(0);
82      int nFeatures = inputMatrix.GetLength(1) - 1;
83      double[] classValues = dataset.GetVariableValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
84      int nClasses = classValues.Count();
85      // map original class values to values [0..nClasses-1]
86      Dictionary<double, double> classIndizes = new Dictionary<double, double>();
87      for (int i = 0; i < nClasses; i++) {
88        classIndizes[classValues[i]] = i;
89      }
90      for (int row = 0; row < nRows; row++) {
91        inputMatrix[row, nFeatures] = classIndizes[inputMatrix[row, nFeatures]];
92      }
93      int info;
94      alglib.mnltrainh(inputMatrix, nRows, nFeatures, nClasses, out info, out lm, out rep);
95      if (info != 1) throw new ArgumentException("Error in calculation of logit classification solution");
96
97      rmsError = alglib.mnlrmserror(lm, inputMatrix, nRows);
98      relClassError = alglib.mnlrelclserror(lm, inputMatrix, nRows);
99
100      LogitClassificationSolution solution = new LogitClassificationSolution(problemData, new LogitModel(lm, targetVariable, allowedInputVariables, classValues));
101      return solution;
102    }
103    #endregion
104  }
105}
Note: See TracBrowser for help on using the repository browser.