Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/DataAnalysisProblemData.cs @ 4681

Last change on this file since 4681 was 4543, checked in by gkronber, 14 years ago

Adapted SVM classes to work correctly for overlapping training / test partitions. #1226

File size: 20.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.IO;
25using System.Linq;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Problems.DataAnalysis {
33  [Item("DataAnalysisProblemData", "Represents an item containing all data defining a data analysis problem.")]
34  [StorableClass]
35  public class DataAnalysisProblemData : ParameterizedNamedItem, IStorableContent {
36    protected bool suppressEvents = false;
37    #region IStorableContent Members
38    public string Filename { get; set; }
39    #endregion
40    #region default data
41    // y = x^4 + x^3 + x^2 + x
42    private static double[,] kozaF1 = new double[,] {
43{2.017885919, -1.449165046},
44{1.30060506,  -1.344523885},
45{1.147134798, -1.317989331},
46{0.877182504, -1.266142284},
47{0.852562452, -1.261020794},
48{0.431095788, -1.158793317},
49{0.112586002, -1.050908405},
50{0.04594507,  -1.021989402},
51{0.042572879, -1.020438113},
52{-0.074027291,  -0.959859562},
53{-0.109178553,  -0.938094706},
54{-0.259721109,  -0.803635355},
55{-0.272991057,  -0.387519561},
56{-0.161978191,  -0.193611001},
57{-0.102489983,  -0.114215349},
58{-0.01469968, -0.014918985},
59{-0.008863365,  -0.008942626},
60{0.026751057, 0.026054094},
61{0.166922436, 0.14309643},
62{0.176953808, 0.1504144},
63{0.190233418, 0.159916534},
64{0.199800708, 0.166635331},
65{0.261502822, 0.207600348},
66{0.30182879,  0.232370249},
67{0.83763905,  0.468046718}
68    };
69    #endregion
70    #region parameter properties
71    public IValueParameter<Dataset> DatasetParameter {
72      get { return (IValueParameter<Dataset>)Parameters["Dataset"]; }
73    }
74    public IValueParameter<StringValue> TargetVariableParameter {
75      get { return (IValueParameter<StringValue>)Parameters["TargetVariable"]; }
76    }
77    public IValueParameter<ICheckedItemList<StringValue>> InputVariablesParameter {
78      get { return (IValueParameter<ICheckedItemList<StringValue>>)Parameters["InputVariables"]; }
79    }
80    public IValueParameter<IntValue> TrainingSamplesStartParameter {
81      get { return (IValueParameter<IntValue>)Parameters["TrainingSamplesStart"]; }
82    }
83    public IValueParameter<IntValue> TrainingSamplesEndParameter {
84      get { return (IValueParameter<IntValue>)Parameters["TrainingSamplesEnd"]; }
85    }
86    public IValueParameter<IntValue> TestSamplesStartParameter {
87      get { return (IValueParameter<IntValue>)Parameters["TestSamplesStart"]; }
88    }
89    public IValueParameter<IntValue> TestSamplesEndParameter {
90      get { return (IValueParameter<IntValue>)Parameters["TestSamplesEnd"]; }
91    }
92    public IValueParameter<PercentValue> ValidationPercentageParameter {
93      get { return (IValueParameter<PercentValue>)Parameters["ValidationPercentage"]; }
94    }
95    #endregion
96
97    #region properties
98    public Dataset Dataset {
99      get { return DatasetParameter.Value; }
100      set {
101        if (value != Dataset) {
102          if (value == null) throw new ArgumentNullException();
103          DatasetParameter.Value = value;
104        }
105      }
106    }
107    public StringValue TargetVariable {
108      get { return TargetVariableParameter.Value; }
109      set {
110        if (value != TargetVariableParameter.Value) {
111          if (value == null) throw new ArgumentNullException();
112          if (TargetVariable != null) DeregisterStringValueEventHandlers(TargetVariable);
113          TargetVariableParameter.Value = value;
114        }
115      }
116    }
117    public ICheckedItemList<StringValue> InputVariables {
118      get { return InputVariablesParameter.Value; }
119      set {
120        if (value != InputVariables) {
121          if (value == null) throw new ArgumentNullException();
122          if (InputVariables != null) DeregisterInputVariablesEventHandlers();
123          InputVariablesParameter.Value = value;
124        }
125      }
126    }
127    public IntValue TrainingSamplesStart {
128      get { return TrainingSamplesStartParameter.Value; }
129      set {
130        if (value != TrainingSamplesStart) {
131          if (value == null) throw new ArgumentNullException();
132          if (TrainingSamplesStart != null) DeregisterValueTypeEventHandlers(TrainingSamplesStart);
133          TrainingSamplesStartParameter.Value = value;
134        }
135      }
136    }
137    public IntValue TrainingSamplesEnd {
138      get { return TrainingSamplesEndParameter.Value; }
139      set {
140        if (value != TrainingSamplesEnd) {
141          if (value == null) throw new ArgumentNullException();
142          if (TrainingSamplesEnd != null) DeregisterValueTypeEventHandlers(TrainingSamplesEnd);
143          TrainingSamplesEndParameter.Value = value;
144        }
145      }
146    }
147    public IntValue TestSamplesStart {
148      get { return TestSamplesStartParameter.Value; }
149      set {
150        if (value != TestSamplesStart) {
151          if (value == null) throw new ArgumentNullException();
152          if (TestSamplesStart != null) DeregisterValueTypeEventHandlers(TestSamplesStart);
153          TestSamplesStartParameter.Value = value;
154        }
155      }
156    }
157    public IntValue TestSamplesEnd {
158      get { return TestSamplesEndParameter.Value; }
159      set {
160        if (value != TestSamplesEnd) {
161          if (value == null) throw new ArgumentNullException();
162          if (TestSamplesEnd != null) DeregisterValueTypeEventHandlers(TestSamplesEnd);
163          TestSamplesEndParameter.Value = value;
164        }
165      }
166    }
167    public PercentValue ValidationPercentage {
168      get { return ValidationPercentageParameter.Value; }
169      set {
170        if (value != ValidationPercentage) {
171          if (value == null) throw new ArgumentNullException();
172          if (value.Value < 0 || value.Value > 1) throw new ArgumentException("ValidationPercentage must be between 0 and 1.");
173          if (ValidationPercentage != null) DeregisterValueTypeEventHandlers(ValidationPercentage);
174          ValidationPercentageParameter.Value = value;
175        }
176      }
177    }
178
179    public IEnumerable<int> TrainingIndizes {
180      get {
181        return Enumerable.Range(TrainingSamplesStart.Value, TrainingSamplesEnd.Value - TrainingSamplesStart.Value)
182                         .Where(i => i >= 0 && i < Dataset.Rows && (i < TestSamplesStart.Value || TestSamplesEnd.Value <= i));
183      }
184    }
185    public IEnumerable<int> TestIndizes {
186      get {
187        return Enumerable.Range(TestSamplesStart.Value, TestSamplesEnd.Value - TestSamplesStart.Value)
188           .Where(i => i >= 0 && i < Dataset.Rows);
189      }
190    }
191    #endregion
192
193
194    public DataAnalysisProblemData()
195      : base() {
196      var inputVariables = new CheckedItemList<StringValue>();
197      StringValue inputVariable = new StringValue("x");
198      inputVariables.Add(inputVariable);
199      StringValue targetVariable = new StringValue("y");
200      var validTargetVariables = new ItemSet<StringValue>();
201      validTargetVariables.Add(targetVariable);
202      Parameters.Add(new ValueParameter<Dataset>("Dataset", new Dataset(new string[] { "y", "x" }, kozaF1)));
203      Parameters.Add(new ValueParameter<ICheckedItemList<StringValue>>("InputVariables", inputVariables.AsReadOnly()));
204      Parameters.Add(new ConstrainedValueParameter<StringValue>("TargetVariable", validTargetVariables, targetVariable));
205      Parameters.Add(new ValueParameter<IntValue>("TrainingSamplesStart", new IntValue(0)));
206      Parameters.Add(new ValueParameter<IntValue>("TrainingSamplesEnd", new IntValue(15)));
207      Parameters.Add(new ValueParameter<IntValue>("TestSamplesStart", new IntValue(15)));
208      Parameters.Add(new ValueParameter<IntValue>("TestSamplesEnd", new IntValue(25)));
209      Parameters.Add(new ValueParameter<PercentValue>("ValidationPercentage", "The relative amount of the training samples that should be used as validation set.", new PercentValue(0.5)));
210      RegisterParameterEventHandlers();
211      RegisterParameterValueEventHandlers();
212    }
213
214    public DataAnalysisProblemData(Dataset dataset, IEnumerable<string> inputVariables, string targetVariable,
215      int trainingSamplesStart, int trainingSamplesEnd, int testSamplesStart, int testSamplesEnd) {
216      var inputVariablesList = new CheckedItemList<StringValue>(inputVariables.Select(x => new StringValue(x)).ToList());
217      StringValue targetVariableValue = new StringValue(targetVariable);
218      var validTargetVariables = new ItemSet<StringValue>();
219      foreach (var variable in dataset.VariableNames)
220        if (variable != targetVariable)
221          validTargetVariables.Add(new StringValue(variable));
222      validTargetVariables.Add(targetVariableValue);
223      Parameters.Add(new ValueParameter<Dataset>("Dataset", dataset));
224      Parameters.Add(new ValueParameter<ICheckedItemList<StringValue>>("InputVariables", inputVariablesList.AsReadOnly()));
225      Parameters.Add(new ConstrainedValueParameter<StringValue>("TargetVariable", validTargetVariables, targetVariableValue));
226      Parameters.Add(new ValueParameter<IntValue>("TrainingSamplesStart", new IntValue(trainingSamplesStart)));
227      Parameters.Add(new ValueParameter<IntValue>("TrainingSamplesEnd", new IntValue(trainingSamplesEnd)));
228      Parameters.Add(new ValueParameter<IntValue>("TestSamplesStart", new IntValue(testSamplesStart)));
229      Parameters.Add(new ValueParameter<IntValue>("TestSamplesEnd", new IntValue(testSamplesEnd)));
230      Parameters.Add(new ValueParameter<PercentValue>("ValidationPercentage", "The relative amount of the training samples that should be used as validation set.", new PercentValue(0.5)));
231      RegisterParameterEventHandlers();
232      RegisterParameterValueEventHandlers();
233    }
234
235    [StorableConstructor]
236    protected DataAnalysisProblemData(bool deserializing) : base(deserializing) { }
237
238    [StorableHook(HookType.AfterDeserialization)]
239    private void AfterDeserializationHook() {
240      if (!Parameters.ContainsKey("ValidationPercentage"))
241        Parameters.Add(new ValueParameter<PercentValue>("ValidationPercentage", "The relative amount of the training samples that should be used as validation set.", new PercentValue(0.5)));
242
243      RegisterParameterEventHandlers();
244      RegisterParameterValueEventHandlers();
245    }
246
247    #region events
248    public event EventHandler ProblemDataChanged;
249    protected virtual void OnProblemDataChanged(EventArgs e) {
250      if (TrainingSamplesStart.Value < 0) TrainingSamplesStart.Value = 0;
251      else if (TestSamplesStart.Value < 0) TestSamplesStart.Value = 0;
252      else if (TrainingSamplesEnd.Value > Dataset.Rows - 1) TrainingSamplesEnd.Value = Dataset.Rows - 1;
253      else if (TestSamplesEnd.Value > Dataset.Rows - 1) TestSamplesEnd.Value = Dataset.Rows - 1;
254      else if (TrainingSamplesStart.Value > TrainingSamplesEnd.Value) TrainingSamplesStart.Value = TestSamplesEnd.Value;
255      else if (TestSamplesStart.Value > TestSamplesEnd.Value) TestSamplesStart.Value = TestSamplesEnd.Value;
256      else if (ValidationPercentage.Value < 0) ValidationPercentage.Value = 0;
257      else if (ValidationPercentage.Value > 1) ValidationPercentage.Value = 1;
258      else if (!TrainingIndizes.Any()) throw new ArgumentException("No training samples are available.");
259      else if (!suppressEvents) {
260        var listeners = ProblemDataChanged;
261        if (listeners != null) listeners(this, e);
262      }
263    }
264
265    private void RegisterParameterEventHandlers() {
266      DatasetParameter.ValueChanged += new EventHandler(DatasetParameter_ValueChanged);
267      InputVariablesParameter.ValueChanged += new EventHandler(InputVariablesParameter_ValueChanged);
268      TargetVariableParameter.ValueChanged += new EventHandler(TargetVariableParameter_ValueChanged);
269      TrainingSamplesStartParameter.ValueChanged += new EventHandler(TrainingSamplesStartParameter_ValueChanged);
270      TrainingSamplesEndParameter.ValueChanged += new EventHandler(TrainingSamplesEndParameter_ValueChanged);
271      TestSamplesStartParameter.ValueChanged += new EventHandler(TestSamplesStartParameter_ValueChanged);
272      TestSamplesEndParameter.ValueChanged += new EventHandler(TestSamplesEndParameter_ValueChanged);
273      ValidationPercentageParameter.ValueChanged += new EventHandler(ValidationPercentageParameter_ValueChanged);
274    }
275
276    private void RegisterParameterValueEventHandlers() {
277      RegisterInputVariablesEventHandlers();
278      if (TargetVariable != null) RegisterStringValueEventHandlers(TargetVariable);
279      RegisterValueTypeEventHandlers(TrainingSamplesStart);
280      RegisterValueTypeEventHandlers(TrainingSamplesEnd);
281      RegisterValueTypeEventHandlers(TestSamplesStart);
282      RegisterValueTypeEventHandlers(TestSamplesEnd);
283      RegisterValueTypeEventHandlers(ValidationPercentage);
284    }
285
286
287    #region parameter value changed event handlers
288    private void DatasetParameter_ValueChanged(object sender, EventArgs e) {
289      OnProblemDataChanged(EventArgs.Empty);
290    }
291    private void InputVariablesParameter_ValueChanged(object sender, EventArgs e) {
292      RegisterInputVariablesEventHandlers();
293      OnProblemDataChanged(EventArgs.Empty);
294    }
295    private void TargetVariableParameter_ValueChanged(object sender, EventArgs e) {
296      if (TargetVariable != null) {
297        RegisterStringValueEventHandlers(TargetVariable);
298        OnProblemDataChanged(EventArgs.Empty);
299      }
300    }
301    private void TrainingSamplesStartParameter_ValueChanged(object sender, EventArgs e) {
302      RegisterValueTypeEventHandlers(TrainingSamplesStart);
303      OnProblemDataChanged(EventArgs.Empty);
304    }
305    private void TrainingSamplesEndParameter_ValueChanged(object sender, EventArgs e) {
306      RegisterValueTypeEventHandlers(TrainingSamplesEnd);
307      OnProblemDataChanged(EventArgs.Empty);
308    }
309    private void TestSamplesStartParameter_ValueChanged(object sender, EventArgs e) {
310      RegisterValueTypeEventHandlers(TestSamplesStart);
311      OnProblemDataChanged(EventArgs.Empty);
312    }
313    private void TestSamplesEndParameter_ValueChanged(object sender, EventArgs e) {
314      RegisterValueTypeEventHandlers(TestSamplesEnd);
315      OnProblemDataChanged(EventArgs.Empty);
316    }
317    private void ValidationPercentageParameter_ValueChanged(object sender, EventArgs e) {
318      RegisterValueTypeEventHandlers(ValidationPercentage);
319      OnProblemDataChanged(EventArgs.Empty);
320    }
321    #endregion
322
323    private void RegisterInputVariablesEventHandlers() {
324      InputVariables.CollectionReset += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_CollectionReset);
325      InputVariables.ItemsAdded += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_ItemsAdded);
326      InputVariables.ItemsRemoved += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_ItemsRemoved);
327      InputVariables.CheckedItemsChanged += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_CheckedItemsChanged);
328      foreach (var item in InputVariables) {
329        item.ValueChanged += new EventHandler(InputVariable_ValueChanged);
330      }
331    }
332
333    private void DeregisterInputVariablesEventHandlers() {
334      InputVariables.CollectionReset -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_CollectionReset);
335      InputVariables.ItemsAdded -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_ItemsAdded);
336      InputVariables.ItemsRemoved -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_ItemsRemoved);
337      InputVariables.CheckedItemsChanged -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<HeuristicLab.Collections.IndexedItem<StringValue>>(InputVariables_CheckedItemsChanged);
338      foreach (var item in InputVariables) {
339        item.ValueChanged -= new EventHandler(InputVariable_ValueChanged);
340      }
341    }
342
343    private void InputVariables_CheckedItemsChanged(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<HeuristicLab.Collections.IndexedItem<StringValue>> e) {
344      OnProblemDataChanged(e);
345    }
346    private void InputVariables_ItemsRemoved(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<HeuristicLab.Collections.IndexedItem<StringValue>> e) {
347      foreach (var indexedItem in e.Items)
348        indexedItem.Value.ValueChanged -= new EventHandler(InputVariable_ValueChanged);
349      OnProblemDataChanged(e);
350    }
351    private void InputVariables_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<HeuristicLab.Collections.IndexedItem<StringValue>> e) {
352      foreach (var indexedItem in e.Items)
353        indexedItem.Value.ValueChanged += new EventHandler(InputVariable_ValueChanged);
354      OnProblemDataChanged(e);
355    }
356    private void InputVariables_CollectionReset(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<HeuristicLab.Collections.IndexedItem<StringValue>> e) {
357      foreach (var indexedItem in e.OldItems)
358        indexedItem.Value.ValueChanged -= new EventHandler(InputVariable_ValueChanged);
359      OnProblemDataChanged(e);
360    }
361    private void InputVariable_ValueChanged(object sender, EventArgs e) {
362      OnProblemDataChanged(e);
363    }
364
365    #region helper
366    private void RegisterValueTypeEventHandlers<T>(ValueTypeValue<T> value) where T : struct {
367      value.ValueChanged += new EventHandler(value_ValueChanged);
368    }
369    private void DeregisterValueTypeEventHandlers<T>(ValueTypeValue<T> value) where T : struct {
370      value.ValueChanged -= new EventHandler(value_ValueChanged);
371    }
372    private void RegisterStringValueEventHandlers(StringValue value) {
373      value.ValueChanged += new EventHandler(value_ValueChanged);
374    }
375    private void DeregisterStringValueEventHandlers(StringValue value) {
376      value.ValueChanged -= new EventHandler(value_ValueChanged);
377    }
378
379    private void value_ValueChanged(object sender, EventArgs e) {
380      OnProblemDataChanged(e);
381    }
382    #endregion
383    #endregion
384
385    public virtual void ImportFromFile(string fileName) {
386      var csvFileParser = new CsvFileParser();
387      csvFileParser.Parse(fileName);
388      suppressEvents = true;
389      Name = "Data imported from " + Path.GetFileName(fileName);
390      Dataset = new Dataset(csvFileParser.VariableNames, csvFileParser.Values);
391      Dataset.Name = Path.GetFileName(fileName);
392      var variableNames = Dataset.VariableNames.Select(x => new StringValue(x).AsReadOnly()).ToList();
393      ((ConstrainedValueParameter<StringValue>)TargetVariableParameter).ValidValues.Clear();
394      foreach (var variableName in variableNames)
395        ((ConstrainedValueParameter<StringValue>)TargetVariableParameter).ValidValues.Add(variableName);
396      TargetVariable = variableNames.First();
397      InputVariables = new CheckedItemList<StringValue>(variableNames).AsReadOnly();
398      InputVariables.SetItemCheckedState(variableNames.First(), false);
399      int middle = (int)(csvFileParser.Rows * 0.5);
400      TrainingSamplesStart = new IntValue(0);
401      TrainingSamplesEnd = new IntValue(middle);
402      TestSamplesStart = new IntValue(middle);
403      TestSamplesEnd = new IntValue(csvFileParser.Rows);
404      suppressEvents = false;
405      OnProblemDataChanged(EventArgs.Empty);
406    }
407
408    public override IDeepCloneable Clone(Cloner cloner) {
409      DataAnalysisProblemData clone = (DataAnalysisProblemData)base.Clone(cloner);
410      clone.RegisterParameterEventHandlers();
411      clone.RegisterParameterValueEventHandlers();
412      return clone;
413    }
414  }
415}
Note: See TracBrowser for help on using the repository browser.