Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 13939 was 13939, checked in by gkronber, 8 years ago

#2618: added regression benchmark instances (random functions) and first implementation of synthetic benchmark instances for variable networks

File size: 8.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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 System.Text;
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
65    private string[] variableNames;
66    protected override string[] VariableNames {
67      get {
68        return variableNames;
69      }
70    }
71
72    // there is no specific target variable in variable network analysis but we still need to specify one
73    protected override string TargetVariable { get { return VariableNames.Last(); } }
74
75    protected override string[] AllowedInputVariables {
76      get {
77        return VariableNames.Take(numberOfFeatures - 1).ToArray();
78      }
79    }
80
81    protected override int TrainingPartitionStart { get { return 0; } }
82    protected override int TrainingPartitionEnd { get { return nTrainingSamples; } }
83    protected override int TestPartitionStart { get { return nTrainingSamples; } }
84    protected override int TestPartitionEnd { get { return nTrainingSamples + nTestSamples; } }
85
86
87    protected override List<List<double>> GenerateValues() {
88      // var shuffledIdx = Enumerable.Range(0, numberOfFeatures).Shuffle(random).ToList();
89
90      // variable names are shuffled in the beginning (and sorted at the end)
91      variableNames = variableNames.Shuffle(random).ToArray();
92
93      // a third of all variables are independen vars
94      List<List<double>> lvl0 = new List<List<double>>();
95      int numLvl0 = (int)Math.Ceiling(numberOfFeatures * 0.33);
96
97      List<string> description = new List<string>(); // store information how the variable is actually produced
98
99      var nrand = new NormalDistributedRandom(random, 0, 1);
100      for (int c = 0; c < numLvl0; c++) {
101        var datai = Enumerable.Range(0, TestPartitionEnd).Select(_ => nrand.NextDouble()).ToList();
102        description.Add("~ N(0, 1)");
103        lvl0.Add(datai);
104      }
105
106      // lvl1 contains variables which are functions of vars in lvl0 (+ noise)
107      List<List<double>> lvl1 = new List<List<double>>();
108      int numLvl1 = (int)Math.Ceiling(numberOfFeatures * 0.33);
109      for (int c = 0; c < numLvl1; c++) {
110        string desc;
111        var x = GenerateRandomFunction(random, lvl0, out desc);
112        var sigma = x.StandardDeviation();
113        var noisePrng = new NormalDistributedRandom(random, 0, sigma * Math.Sqrt(noiseRatio / (1.0 - noiseRatio)));
114        lvl1.Add(x.Select(t => t + noisePrng.NextDouble()).ToList());
115        description.Add(string.Format(" ~ N({0}, {1:N3})", desc, noisePrng.Sigma));
116      }
117
118      // lvl2 contains variables which are functions of vars in lvl0 and lvl1 (+ noise)
119      List<List<double>> lvl2 = new List<List<double>>();
120      int numLvl2 = (int)Math.Ceiling(numberOfFeatures * 0.2);
121      for (int c = 0; c < numLvl2; c++) {
122        string desc;
123        var x = GenerateRandomFunction(random, lvl0.Concat(lvl1).ToList(), out desc);
124        var sigma = x.StandardDeviation();
125        var noisePrng = new NormalDistributedRandom(random, 0, sigma * Math.Sqrt(noiseRatio / (1.0 - noiseRatio)));
126        lvl2.Add(x.Select(t => t + noisePrng.NextDouble()).ToList());
127        description.Add(string.Format(" ~ N({0}, {1:N3})", desc, noisePrng.Sigma));
128      }
129
130      // lvl3 contains variables which are functions of vars in lvl0, lvl1 and lvl2 (+ noise)
131      List<List<double>> lvl3 = new List<List<double>>();
132      int numLvl3 = numberOfFeatures - numLvl0 - numLvl1 - numLvl2;
133      for (int c = 0; c < numLvl3; c++) {
134        string desc;
135        var x = GenerateRandomFunction(random, lvl0.Concat(lvl1).Concat(lvl2).ToList(), out desc);
136        var sigma = x.StandardDeviation();
137        var noisePrng = new NormalDistributedRandom(random, 0, sigma * Math.Sqrt(noiseRatio / (1.0 - noiseRatio)));
138        lvl3.Add(x.Select(t => t + noisePrng.NextDouble()).ToList());
139        description.Add(string.Format(" ~ N({0}, {1:N3})", desc, noisePrng.Sigma));
140      }
141
142      // return a random permutation of all variables
143      var allVars = lvl0.Concat(lvl1).Concat(lvl2).Concat(lvl3).ToList();
144      networkDefinition = string.Join(Environment.NewLine, variableNames.Zip(description, (n, d) => n + d));
145      var orderedVars = allVars.Zip(variableNames, Tuple.Create).OrderBy(t => t.Item2).Select(t => t.Item1).ToList();
146      variableNames = variableNames.OrderBy(n => n).ToArray();
147      return orderedVars;
148    }
149
150    // sample the input variables that are actually used and sample from a Gaussian process
151    private IEnumerable<double> GenerateRandomFunction(IRandom rand, List<List<double>> xs, out string desc) {
152      int nRows = xs.First().Count;
153
154      double r = -Math.Log(1.0 - rand.NextDouble()) * 2.0; // r is exponentially distributed with lambda = 2
155      int nl = (int)Math.Floor(1.5 + r); // number of selected vars is likely to be between three and four
156      if (nl > xs.Count) nl = xs.Count; // limit max
157
158      var selectedIdx = Enumerable.Range(0, xs.Count).Shuffle(random)
159        .Take(nl).ToArray();
160
161      var selectedVars = selectedIdx.Select(i => xs[i]).ToArray();
162      desc = string.Format("f({0})", string.Join(",", selectedIdx.Select(i => VariableNames[i])));
163      return SampleGaussianProcess(random, selectedVars);
164    }
165
166    private IEnumerable<double> SampleGaussianProcess(IRandom random, List<double>[] xs) {
167      int nl = xs.Length;
168      int nRows = xs.First().Count;
169      double[,] K = new double[nRows, nRows];
170
171      // sample length-scales
172      var l = Enumerable.Range(0, nl)
173        .Select(_ => random.NextDouble()*2+0.5)
174        .ToArray();
175      // calculate covariance matrix
176      for (int r = 0; r < nRows; r++) {
177        double[] xi = xs.Select(x => x[r]).ToArray();
178        for (int c = 0; c <= r; c++) {
179          double[] xj = xs.Select(x => x[c]).ToArray();
180          double dSqr = xi.Zip(xj, (xik, xjk) => (xik - xjk))
181            .Select(dk => dk * dk)
182            .Zip(l, (dk, lk) => dk / lk)
183            .Sum();
184          K[r, c] = Math.Exp(-dSqr);
185        }
186      }
187
188      // add a small diagonal matrix for numeric stability
189      for (int i = 0; i < nRows; i++) {
190        K[i, i] += 1.0E-7;
191      }
192
193      // decompose
194      alglib.trfac.spdmatrixcholesky(ref K, nRows, false);
195
196      // sample u iid ~ N(0, 1)
197      var u = Enumerable.Range(0, nRows).Select(_ => NormalDistributedRandom.NextDouble(random, 0, 1)).ToArray();
198
199      // calc y = Lu
200      var y = new double[u.Length];
201      alglib.ablas.rmatrixmv(nRows, nRows, K, 0, 0, 0, u, 0, ref y, 0);
202
203      return y;
204    }
205  }
206}
Note: See TracBrowser for help on using the repository browser.