source: trunk/sources/HeuristicLab.Problems.Instances.DataAnalysis/3.3/Regression/VariableNetworks/VariableNetwork.cs @ 14271

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

#2660: slightly refactored VariableNetwork instance and added calculation of variable relevance

File size: 11.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Globalization;
25using System.Linq;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Random;
29
30namespace HeuristicLab.Problems.Instances.DataAnalysis {
31  public class VariableNetwork : ArtificialRegressionDataDescriptor {
32    private int nTrainingSamples;
33    private int nTestSamples;
34
35    private int numberOfFeatures;
36    private double noiseRatio;
37    private IRandom random;
38
39    public override string Name { get { return string.Format("VariableNetwork-{0:0%} ({1} dim)", noiseRatio, numberOfFeatures); } }
40    private string networkDefinition;
41    public string NetworkDefinition { get { return networkDefinition; } }
42    public override string Description {
43      get {
44        return "The data are generated specifically to test methods for variable network analysis.";
45      }
46    }
47
48    public VariableNetwork(int numberOfFeatures, double noiseRatio,
49      IRandom rand)
50      : this(250, 250, numberOfFeatures, noiseRatio, rand) { }
51
52    public VariableNetwork(int nTrainingSamples, int nTestSamples,
53      int numberOfFeatures, double noiseRatio, IRandom rand) {
54      this.nTrainingSamples = nTrainingSamples;
55      this.nTestSamples = nTestSamples;
56      this.noiseRatio = noiseRatio;
57      this.random = rand;
58      this.numberOfFeatures = numberOfFeatures;
59      // default variable names
60      variableNames = Enumerable.Range(1, numberOfFeatures)
61        .Select(i => string.Format("X{0:000}", i))
62        .ToArray();
63
64      variableRelevances = new Dictionary<string, IEnumerable<KeyValuePair<string, double>>>();
65    }
66
67    private string[] variableNames;
68    protected override string[] VariableNames {
69      get {
70        return variableNames;
71      }
72    }
73
74    // there is no specific target variable in variable network analysis but we still need to specify one
75    protected override string TargetVariable { get { return VariableNames.Last(); } }
76
77    protected override string[] AllowedInputVariables {
78      get {
79        return VariableNames.Take(numberOfFeatures - 1).ToArray();
80      }
81    }
82
83    protected override int TrainingPartitionStart { get { return 0; } }
84    protected override int TrainingPartitionEnd { get { return nTrainingSamples; } }
85    protected override int TestPartitionStart { get { return nTrainingSamples; } }
86    protected override int TestPartitionEnd { get { return nTrainingSamples + nTestSamples; } }
87
88    private Dictionary<string, IEnumerable<KeyValuePair<string, double>>> variableRelevances;
89    public IEnumerable<KeyValuePair<string, double>> GetVariableRelevance(string targetVar) {
90      return variableRelevances[targetVar];
91    }
92
93    protected override List<List<double>> GenerateValues() {
94      // variable names are shuffled in the beginning (and sorted at the end)
95      variableNames = variableNames.Shuffle(random).ToArray();
96
97      // a third of all variables are independent vars
98      List<List<double>> lvl0 = new List<List<double>>();
99      int numLvl0 = (int)Math.Ceiling(numberOfFeatures * 0.33);
100
101      List<string> description = new List<string>(); // store information how the variable is actually produced
102      List<string[]> inputVarNames = new List<string[]>(); // store information to produce graphviz file
103      List<double[]> relevances = new List<double[]>(); // stores variable relevance information (same order as given in inputVarNames)
104
105      var nrand = new NormalDistributedRandom(random, 0, 1);
106      for (int c = 0; c < numLvl0; c++) {
107        inputVarNames.Add(new string[] { });
108        relevances.Add(new double[] { });
109        description.Add(" ~ N(0, 1)");
110        lvl0.Add(Enumerable.Range(0, TestPartitionEnd).Select(_ => nrand.NextDouble()).ToList());
111      }
112
113      // lvl1 contains variables which are functions of vars in lvl0 (+ noise)
114      int numLvl1 = (int)Math.Ceiling(numberOfFeatures * 0.33);
115      List<List<double>> lvl1 = CreateVariables(lvl0, numLvl1, inputVarNames, description, relevances);
116
117      // lvl2 contains variables which are functions of vars in lvl0 and lvl1 (+ noise)
118      int numLvl2 = (int)Math.Ceiling(numberOfFeatures * 0.2);
119      List<List<double>> lvl2 = CreateVariables(lvl0.Concat(lvl1).ToList(), numLvl2, inputVarNames, description, relevances);
120
121      // lvl3 contains variables which are functions of vars in lvl0, lvl1 and lvl2 (+ noise)
122      int numLvl3 = numberOfFeatures - numLvl0 - numLvl1 - numLvl2;
123      List<List<double>> lvl3 = CreateVariables(lvl0.Concat(lvl1).Concat(lvl2).ToList(), numLvl3, inputVarNames, description, relevances);
124
125      this.variableRelevances.Clear();
126      for (int i = 0; i < variableNames.Length; i++) {
127        var targetVarName = variableNames[i];
128        var targetRelevantInputs =
129          inputVarNames[i].Zip(relevances[i], (inputVar, rel) => new KeyValuePair<string, double>(inputVar, rel))
130            .ToArray();
131        variableRelevances.Add(targetVarName, targetRelevantInputs);
132      }
133
134      networkDefinition = string.Join(Environment.NewLine, variableNames.Zip(description, (n, d) => n + d).OrderBy(x => x));
135      // for graphviz
136      networkDefinition += Environment.NewLine + "digraph G {";
137      for (int i = 0; i < variableNames.Length; i++) {
138        var name = variableNames[i];
139        var selectedVarNames = inputVarNames[i];
140        var selectedRelevances = relevances[i];
141        for (int j = 0; j < selectedVarNames.Length; j++) {
142          var selectedVarName = selectedVarNames[j];
143          var selectedRelevance = selectedRelevances[j];
144          networkDefinition += Environment.NewLine + selectedVarName + " -> " + name +
145            string.Format(CultureInfo.InvariantCulture, " [label={0:N3}]", selectedRelevance);
146        }
147      }
148      networkDefinition += Environment.NewLine + "}";
149
150      // return a random permutation of all variables (to mix lvl0, lvl1, ... variables)
151      var allVars = lvl0.Concat(lvl1).Concat(lvl2).Concat(lvl3).ToList();
152      var orderedVars = allVars.Zip(variableNames, Tuple.Create).OrderBy(t => t.Item2).Select(t => t.Item1).ToList();
153      variableNames = variableNames.OrderBy(n => n).ToArray();
154      return orderedVars;
155    }
156
157    private List<List<double>> CreateVariables(List<List<double>> allowedInputs, int numVars, List<string[]> inputVarNames, List<string> description, List<double[]> relevances) {
158      var res = new List<List<double>>();
159      for (int c = 0; c < numVars; c++) {
160        string[] selectedVarNames;
161        double[] relevance;
162        var x = GenerateRandomFunction(random, allowedInputs, out selectedVarNames, out relevance);
163        var sigma = x.StandardDeviation();
164        var noisePrng = new NormalDistributedRandom(random, 0, sigma * Math.Sqrt(noiseRatio / (1.0 - noiseRatio)));
165        res.Add(x.Select(t => t + noisePrng.NextDouble()).ToList());
166        Array.Sort(selectedVarNames, relevance);
167        inputVarNames.Add(selectedVarNames);
168        relevances.Add(relevance);
169        var desc = string.Format("f({0})", string.Join(",", selectedVarNames));
170        // for the relevance information order variables by decreasing relevance
171        var relevanceStr = string.Join(", ",
172          selectedVarNames.Zip(relevance, Tuple.Create)
173          .OrderByDescending(t => t.Item2)
174          .Select(t => string.Format(CultureInfo.InvariantCulture, "{0}: {1:N3}", t.Item1, t.Item2)));
175        description.Add(string.Format(" ~ N({0}, {1:N3}) [Relevances: {2}]", desc, noisePrng.Sigma, relevanceStr));
176      }
177      return res;
178    }
179
180    // sample the input variables that are actually used and sample from a Gaussian process
181    private IEnumerable<double> GenerateRandomFunction(IRandom rand, List<List<double>> xs, out string[] selectedVarNames, out double[] relevance) {
182      double r = -Math.Log(1.0 - rand.NextDouble()) * 2.0; // r is exponentially distributed with lambda = 2
183      int nl = (int)Math.Floor(1.5 + r); // number of selected vars is likely to be between three and four
184      if (nl > xs.Count) nl = xs.Count; // limit max
185
186      var selectedIdx = Enumerable.Range(0, xs.Count).Shuffle(random)
187        .Take(nl).ToArray();
188
189      var selectedVars = selectedIdx.Select(i => xs[i]).ToArray();
190      selectedVarNames = selectedIdx.Select(i => VariableNames[i]).ToArray();
191      return SampleGaussianProcess(random, selectedVars, out relevance);
192    }
193
194    private IEnumerable<double> SampleGaussianProcess(IRandom random, List<double>[] xs, out double[] relevance) {
195      int nl = xs.Length;
196      int nRows = xs.First().Count;
197      double[,] K = new double[nRows, nRows];
198
199      // sample length-scales
200      var l = Enumerable.Range(0, nl)
201        .Select(_ => random.NextDouble() * 2 + 0.5)
202        .ToArray();
203      // calculate covariance matrix
204      for (int r = 0; r < nRows; r++) {
205        double[] xi = xs.Select(x => x[r]).ToArray();
206        for (int c = 0; c <= r; c++) {
207          double[] xj = xs.Select(x => x[c]).ToArray();
208          double dSqr = xi.Zip(xj, (xik, xjk) => (xik - xjk))
209            .Select(dk => dk * dk)
210            .Zip(l, (dk, lk) => dk / lk)
211            .Sum();
212          K[r, c] = Math.Exp(-dSqr);
213        }
214      }
215
216      // add a small diagonal matrix for numeric stability
217      for (int i = 0; i < nRows; i++) {
218        K[i, i] += 1.0E-7;
219      }
220
221      // decompose
222      alglib.trfac.spdmatrixcholesky(ref K, nRows, false);
223
224      // sample u iid ~ N(0, 1)
225      var u = Enumerable.Range(0, nRows).Select(_ => NormalDistributedRandom.NextDouble(random, 0, 1)).ToArray();
226
227      // calc y = Lu
228      var y = new double[u.Length];
229      alglib.ablas.rmatrixmv(nRows, nRows, K, 0, 0, 0, u, 0, ref y, 0);
230
231      // calculate variable relevance
232      // as per Rasmussen and Williams "Gaussian Processes for Machine Learning" page 106:
233      // ,,For the squared exponential covariance function [...] the l1, ..., lD hyperparameters
234      // play the role of characteristic length scales [...]. Such a covariance function implements
235      // automatic relevance determination (ARD) [Neal, 1996], since the inverse of the length-scale
236      // determines how relevant an input is: if the length-scale has a very large value, the covariance
237      // will become almost independent of that input, effectively removing it from inference.''
238      relevance = l.Select(li => 1.0 / li).ToArray();
239
240      return y;
241    }
242  }
243}
Note: See TracBrowser for help on using the repository browser.