Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 16123 was 15786, checked in by fholzing, 7 years ago

#2902: Renamed ContainsNanInf to ContainsNanOrInfinity

File size: 5.5 KB
RevLine 
[6567]1#region License Information
2/* HeuristicLab
[15583]3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[6567]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;
[14523]25using System.Threading;
[6567]26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Optimization;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Problems.DataAnalysis;
32
33namespace HeuristicLab.Algorithms.DataAnalysis {
34  /// <summary>
35  /// Multinomial logit regression data analysis algorithm.
36  /// </summary>
[13238]37  [Item("Multinomial Logit Classification (MNL)", "Multinomial logit classification data analysis algorithm (wrapper for ALGLIB).")]
[12622]38  [Creatable(CreatableAttribute.Categories.DataAnalysisClassification, Priority = 180)]
[6567]39  [StorableClass]
40  public sealed class MultiNomialLogitClassification : FixedDataAnalysisAlgorithm<IClassificationProblem> {
41    private const string LogitClassificationModelResultName = "Logit classification solution";
42
43    [StorableConstructor]
44    private MultiNomialLogitClassification(bool deserializing) : base(deserializing) { }
45    private MultiNomialLogitClassification(MultiNomialLogitClassification original, Cloner cloner)
46      : base(original, cloner) {
47    }
48    public MultiNomialLogitClassification()
49      : base() {
50      Problem = new ClassificationProblem();
51    }
52    [StorableHook(HookType.AfterDeserialization)]
53    private void AfterDeserialization() { }
54
55    public override IDeepCloneable Clone(Cloner cloner) {
56      return new MultiNomialLogitClassification(this, cloner);
57    }
58
[6633]59    #region logit classification
[14523]60    protected override void Run(CancellationToken cancellationToken) {
[6567]61      double rmsError, relClassError;
62      var solution = CreateLogitClassificationSolution(Problem.ProblemData, out rmsError, out relClassError);
[6633]63      Results.Add(new Result(LogitClassificationModelResultName, "The logit classification solution.", solution));
64      Results.Add(new Result("Root mean squared error", "The root of the mean of squared errors of the logit regression solution on the training set.", new DoubleValue(rmsError)));
[6567]65      Results.Add(new Result("Relative classification error", "Relative classification error on the training set (percentage of misclassified cases).", new PercentValue(relClassError)));
66    }
67
68    public static IClassificationSolution CreateLogitClassificationSolution(IClassificationProblemData problemData, out double rmsError, out double relClassError) {
[12509]69      var dataset = problemData.Dataset;
[6567]70      string targetVariable = problemData.TargetVariable;
[14826]71      var doubleVariableNames = problemData.AllowedInputVariables.Where(dataset.VariableHasType<double>);
72      var factorVariableNames = problemData.AllowedInputVariables.Where(dataset.VariableHasType<string>);
[8139]73      IEnumerable<int> rows = problemData.TrainingIndices;
[14843]74      double[,] inputMatrix = dataset.ToArray(doubleVariableNames.Concat(new string[] { targetVariable }), rows);
[14826]75
[14843]76      var factorVariableValues = dataset.GetFactorVariableValues(factorVariableNames, rows);
77      var factorMatrix = dataset.ToArray(factorVariableValues, rows);
[14826]78      inputMatrix = factorMatrix.HorzCat(inputMatrix);
79
[15786]80      if (inputMatrix.ContainsNanOrInfinity())
[6567]81        throw new NotSupportedException("Multinomial logit classification does not support NaN or infinity values in the input dataset.");
82
[12817]83      alglib.logitmodel lm = new alglib.logitmodel();
84      alglib.mnlreport rep = new alglib.mnlreport();
[6567]85      int nRows = inputMatrix.GetLength(0);
86      int nFeatures = inputMatrix.GetLength(1) - 1;
[6740]87      double[] classValues = dataset.GetDoubleValues(targetVariable).Distinct().OrderBy(x => x).ToArray();
[6567]88      int nClasses = classValues.Count();
89      // map original class values to values [0..nClasses-1]
[8139]90      Dictionary<double, double> classIndices = new Dictionary<double, double>();
[6567]91      for (int i = 0; i < nClasses; i++) {
[8139]92        classIndices[classValues[i]] = i;
[6567]93      }
94      for (int row = 0; row < nRows; row++) {
[8139]95        inputMatrix[row, nFeatures] = classIndices[inputMatrix[row, nFeatures]];
[6567]96      }
97      int info;
98      alglib.mnltrainh(inputMatrix, nRows, nFeatures, nClasses, out info, out lm, out rep);
99      if (info != 1) throw new ArgumentException("Error in calculation of logit classification solution");
100
101      rmsError = alglib.mnlrmserror(lm, inputMatrix, nRows);
102      relClassError = alglib.mnlrelclserror(lm, inputMatrix, nRows);
103
[14826]104      MultinomialLogitClassificationSolution solution = new MultinomialLogitClassificationSolution(new MultinomialLogitModel(lm, targetVariable, doubleVariableNames, factorVariableValues, classValues), (IClassificationProblemData)problemData.Clone());
[6567]105      return solution;
106    }
107    #endregion
108  }
109}
Note: See TracBrowser for help on using the repository browser.