Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Algorithms.DataAnalysis.DecisionTrees/3.4/Utilities/PrincipleComponentTransformation.cs @ 17159

Last change on this file since 17159 was 16847, checked in by gkronber, 6 years ago

#2847: made some minor changes while reviewing

File size: 8.5 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.Collections;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Problems.DataAnalysis;
27using HEAL.Attic;
28
29namespace HeuristicLab.Algorithms.DataAnalysis {
30  [StorableType("A2DDC528-BAA7-445F-98E1-5F895CE2FD5C")]
31  public class PrincipleComponentTransformation : IDeepCloneable {
32    #region Properties
33    [Storable]
34    private double[,] Matrix { get; set; }
35    [Storable]
36    public double[] Variances { get; private set; }
37    [Storable]
38    public string[] VariableNames { get; private set; }
39    [Storable]
40    private double[] Deviations { get; set; }
41    [Storable]
42    private double[] Means { get; set; }
43    public string[] ComponentNames {
44      get { return VariableNames.Select((_, x) => "pc" + x).ToArray(); }
45    }
46    #endregion
47
48    #region HLConstructors
49    [StorableConstructor]
50    protected PrincipleComponentTransformation(StorableConstructorFlag _) { }
51    protected PrincipleComponentTransformation(PrincipleComponentTransformation original, Cloner cloner) {
52      if (original.Variances != null) Variances = original.Variances.ToArray();
53      if (original.VariableNames != null) VariableNames = original.VariableNames.ToArray();
54      if (original.Deviations != null) Deviations = original.Deviations.ToArray();
55      if (original.Means != null) Means = original.Means.ToArray();
56      if (original.Matrix == null) return;
57      Matrix = new double[original.Matrix.GetLength(0), original.Matrix.GetLength(1)];
58      for (var i = 0; i < original.Matrix.GetLength(0); i++)
59      for (var j = 0; j < original.Matrix.GetLength(1); j++)
60        Matrix[i, j] = original.Matrix[i, j];
61    }
62    private PrincipleComponentTransformation() { }
63    public IDeepCloneable Clone(Cloner cloner) {
64      return new PrincipleComponentTransformation(this, cloner);
65    }
66    public object Clone() {
67      return new Cloner().Clone(this);
68    }
69    #endregion
70
71    #region Static Interface
72    public static PrincipleComponentTransformation CreateProjection(IDataset dataset, IEnumerable<int> rows, IEnumerable<string> variables, bool normalize = false) {
73      var res = new PrincipleComponentTransformation();
74      res.BuildPca(dataset, rows, variables, normalize);
75      return res;
76    }
77    #endregion
78
79    #region Projection
80    public IRegressionProblemData TransformProblemData(IRegressionProblemData pd) {
81      return CreateProblemData(pd, TransformDataset(pd.Dataset), ComponentNames);
82    }
83
84    public IDataset TransformDataset(IDataset data) {
85      return CreateDataset(data, TransformData(data, Enumerable.Range(0, data.Rows)));
86    }
87
88    public double[,] TransformData(IDataset dataset, IEnumerable<int> rows) {
89      var instances = rows.ToArray();
90      var result = new double[instances.Length, VariableNames.Length];
91      for (var r = 0; r < instances.Length; r++)
92      for (var i = 0; i < VariableNames.Length; i++) {
93        var val = (dataset.GetDoubleValue(VariableNames[i], instances[r]) - Means[i]) / Deviations[i];
94        for (var j = 0; j < VariableNames.Length; j++)
95          result[r, j] += val * Matrix[i, j];
96      }
97      return result;
98    }
99    #endregion
100
101    #region Reversion
102    public IRegressionProblemData RevertProblemData(IRegressionProblemData pd) {
103      return CreateProblemData(pd, RevertDataset(pd.Dataset), VariableNames);
104    }
105
106    public IDataset RevertDataset(IDataset data) {
107      return CreateRevertedDataset(data, RevertData(data, Enumerable.Range(0, data.Rows)));
108    }
109
110    public double[,] RevertData(IDataset dataset, IEnumerable<int> rows) {
111      var instances = rows.ToArray();
112      var components = ComponentNames;
113      var result = new double[instances.Length, VariableNames.Length];
114      for (var r = 0; r < instances.Length; r++)
115      for (var i = 0; i < components.Length; i++) {
116        var val = dataset.GetDoubleValue(components[i], instances[r]);
117        for (var j = 0; j < VariableNames.Length; j++)
118          result[r, j] += val * Matrix[j, i];
119      }
120      for (var r = 0; r < instances.Length; r++) {
121        for (var j = 0; j < VariableNames.Length; j++) {
122          result[r, j] *= Deviations[j];
123          result[r, j] += Means[j];
124        }
125      }
126
127      return result;
128    }
129    #endregion
130
131    #region Helpers
132    private static IRegressionProblemData CreateProblemData(IRegressionProblemData pd, IDataset data, IReadOnlyList<string> allowedNames) {
133      var res = new RegressionProblemData(data, allowedNames, pd.TargetVariable);
134      res.TestPartition.Start = pd.TestPartition.Start;
135      res.TestPartition.End = pd.TestPartition.End;
136      res.TrainingPartition.Start = pd.TrainingPartition.Start;
137      res.TrainingPartition.End = pd.TrainingPartition.End;
138      res.Name = pd.Name;
139      return res;
140    }
141
142    private IDataset CreateDataset(IDataset data, double[,] pcs) {
143      var n = ComponentNames;
144      var nDouble = data.DoubleVariables.Where(x => !VariableNames.Contains(x)).ToArray();
145      var nDateTime = data.DateTimeVariables.ToArray();
146      var nString = data.StringVariables.ToArray();
147
148      IEnumerable<IList> nData = n.Select((_, x) => Enumerable.Range(0, pcs.GetLength(0)).Select(r => pcs[r, x]).ToList());
149      IEnumerable<IList> nDoubleData = nDouble.Select(x => data.GetDoubleValues(x).ToList());
150      IEnumerable<IList> nDateTimeData = nDateTime.Select(x => data.GetDateTimeValues(x).ToList());
151      IEnumerable<IList> nStringData = nString.Select(x => data.GetStringValues(x).ToList());
152
153      return new Dataset(n.Concat(nDouble).Concat(nDateTime).Concat(nString), nData.Concat(nDoubleData).Concat(nDateTimeData).Concat(nStringData).ToArray());
154    }
155
156    private IDataset CreateRevertedDataset(IDataset data, double[,] pcs) {
157      var n = VariableNames;
158      var nDouble = data.DoubleVariables.Where(x => !ComponentNames.Contains(x)).ToArray();
159      var nDateTime = data.DateTimeVariables.ToArray();
160      var nString = data.StringVariables.ToArray();
161
162      IEnumerable<IList> nData = n.Select((_, x) => Enumerable.Range(0, pcs.GetLength(0)).Select(r => pcs[r, x]).ToList());
163      IEnumerable<IList> nDoubleData = nDouble.Select(x => data.GetDoubleValues(x).ToList());
164      IEnumerable<IList> nDateTimeData = nDateTime.Select(x => data.GetDateTimeValues(x).ToList());
165      IEnumerable<IList> nStringData = nString.Select(x => data.GetStringValues(x).ToList());
166
167      return new Dataset(n.Concat(nDouble).Concat(nDateTime).Concat(nString), nData.Concat(nDoubleData).Concat(nDateTimeData).Concat(nStringData).ToArray());
168    }
169
170    private void BuildPca(IDataset dataset, IEnumerable<int> rows, IEnumerable<string> variables, bool normalize) {
171      var instances = rows.ToArray();
172      var attributes = variables.ToArray();
173      Means = normalize
174        ? attributes.Select(v => dataset.GetDoubleValues(v, instances).Average()).ToArray()
175        : attributes.Select(x => 0.0).ToArray();
176      Deviations = normalize
177        ? attributes.Select(v => dataset.GetDoubleValues(v, instances).StandardDeviationPop()).Select(x => x.IsAlmost(0.0) ? 1 : x).ToArray()
178        : attributes.Select(x => 1.0).ToArray();
179
180      var data = new double[instances.Length, attributes.Length];
181
182      for (var j = 0; j < attributes.Length; j++) {
183        var i = 0;
184        foreach (var v in dataset.GetDoubleValues(attributes[j], instances)) {
185          data[i, j] = (v - Means[j]) / Deviations[j];
186          i++;
187        }
188      }
189
190      int info;
191      double[] variances;
192      double[,] matrix;
193      alglib.pcabuildbasis(data, instances.Length, attributes.Length, out info, out variances, out matrix);
194      Matrix = matrix;
195      Variances = variances;
196      VariableNames = attributes;
197    }
198    #endregion
199  }
200}
Note: See TracBrowser for help on using the repository browser.