Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.Instances.DataAnalysis/3.3/Classification/CSV/ClassifiactionCSVInstanceProvider.cs @ 15990

Last change on this file since 15990 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

File size: 7.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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;
24using System.Collections.Generic;
25using System.IO;
26using System.Linq;
27using HeuristicLab.Common;
28using HeuristicLab.Problems.DataAnalysis;
29
30namespace HeuristicLab.Problems.Instances.DataAnalysis {
31  public class ClassificationCSVInstanceProvider : ClassificationInstanceProvider {
32    public override string Name {
33      get { return "CSV File"; }
34    }
35    public override string Description {
36      get {
37        return "";
38      }
39    }
40    public override Uri WebLink {
41      get { return new Uri("http://dev.heuristiclab.com/trac.fcgi/wiki/Documentation/FAQ#DataAnalysisImportFileFormat"); }
42    }
43    public override string ReferencePublication {
44      get { return ""; }
45    }
46
47    public override IEnumerable<IDataDescriptor> GetDataDescriptors() {
48      return new List<IDataDescriptor>();
49    }
50
51    public override IClassificationProblemData LoadData(IDataDescriptor descriptor) {
52      throw new NotImplementedException();
53    }
54
55    public override bool CanImportData {
56      get { return true; }
57    }
58    public override IClassificationProblemData ImportData(string path) {
59      TableFileParser csvFileParser = new TableFileParser();
60
61      csvFileParser.Parse(path, csvFileParser.AreColumnNamesInFirstLine(path));
62
63      Dataset dataset = new Dataset(csvFileParser.VariableNames, csvFileParser.Values);
64      string targetVar = dataset.DoubleVariables.Last();
65
66      // turn of input variables that are constant in the training partition
67      var allowedInputVars = new List<string>();
68      var trainingIndizes = Enumerable.Range(0, (csvFileParser.Rows * 2) / 3);
69      if (trainingIndizes.Count() >= 2) {
70        foreach (var variableName in dataset.DoubleVariables) {
71          if (dataset.GetDoubleValues(variableName, trainingIndizes).Range() > 0 &&
72            variableName != targetVar)
73            allowedInputVars.Add(variableName);
74        }
75      } else {
76        allowedInputVars.AddRange(dataset.DoubleVariables.Where(x => !x.Equals(targetVar)));
77      }
78
79      ClassificationProblemData classificationData = new ClassificationProblemData(dataset, allowedInputVars, targetVar);
80
81      int trainingPartEnd = trainingIndizes.Last();
82      classificationData.TrainingPartition.Start = trainingIndizes.First();
83      classificationData.TrainingPartition.End = trainingPartEnd;
84      classificationData.TestPartition.Start = trainingPartEnd;
85      classificationData.TestPartition.End = csvFileParser.Rows;
86
87      classificationData.Name = Path.GetFileName(path);
88
89      return classificationData;
90    }
91
92    protected override IClassificationProblemData ImportData(string path, ClassificationImportType type, TableFileParser csvFileParser) {
93      int trainingPartEnd = (csvFileParser.Rows * type.TrainingPercentage) / 100;
94      List<IList> values = csvFileParser.Values;
95      if (type.Shuffle) {
96        values = Shuffle(values);
97        if (type.UniformlyDistributeClasses) {
98          values = Shuffle(values, csvFileParser.VariableNames.ToList().FindIndex(x => x.Equals(type.TargetVariable)),
99                           type.TrainingPercentage, out trainingPartEnd);
100        }
101      }
102
103      Dataset dataset = new Dataset(csvFileParser.VariableNames, values);
104
105      // turn of input variables that are constant in the training partition
106      var allowedInputVars = new List<string>();
107      var trainingIndizes = Enumerable.Range(0, trainingPartEnd);
108      if (trainingIndizes.Count() >= 2) {
109        foreach (var variableName in dataset.DoubleVariables) {
110          if (dataset.GetDoubleValues(variableName, trainingIndizes).Range() > 0 &&
111            variableName != type.TargetVariable)
112            allowedInputVars.Add(variableName);
113        }
114      } else {
115        allowedInputVars.AddRange(dataset.DoubleVariables.Where(x => !x.Equals(type.TargetVariable)));
116      }
117
118      ClassificationProblemData classificationData = new ClassificationProblemData(dataset, allowedInputVars, type.TargetVariable);
119
120      classificationData.TrainingPartition.Start = 0;
121      classificationData.TrainingPartition.End = trainingPartEnd;
122      classificationData.TestPartition.Start = trainingPartEnd;
123      classificationData.TestPartition.End = csvFileParser.Rows;
124
125      classificationData.Name = Path.GetFileName(path);
126
127      return classificationData;
128    }
129
130    protected List<IList> Shuffle(List<IList> values, int target, int trainingPercentage, out int trainingPartEnd) {
131      IList targetValues = values[target];
132      var group = targetValues.Cast<double>().GroupBy(x => x).Select(g => new { Key = g.Key, Count = g.Count() }).ToList();
133      Dictionary<double, double> taken = new Dictionary<double, double>();
134      foreach (var classCount in group) {
135        taken[classCount.Key] = (classCount.Count * trainingPercentage) / 100.0;
136      }
137
138      List<IList> training = GetListOfIListCopy(values);
139      List<IList> test = GetListOfIListCopy(values);
140
141      for (int i = 0; i < targetValues.Count; i++) {
142        if (taken[(double)targetValues[i]] > 0) {
143          AddRow(training, values, i);
144          taken[(double)targetValues[i]]--;
145        } else {
146          AddRow(test, values, i);
147        }
148      }
149
150      trainingPartEnd = training.First().Count;
151
152      for (int i = 0; i < training.Count; i++) {
153        for (int j = 0; j < test[i].Count; j++) {
154          training[i].Add(test[i][j]);
155        }
156      }
157
158      return training;
159    }
160
161    private void AddRow(List<IList> destination, List<IList> source, int index) {
162      for (int i = 0; i < source.Count; i++) {
163        destination[i].Add(source[i][index]);
164      }
165    }
166
167    private List<IList> GetListOfIListCopy(List<IList> values) {
168      List<IList> newList = new List<IList>(values.Count);
169      foreach (IList t in values) {
170        if (t is List<double>)
171          newList.Add(new List<double>());
172        else if (t is List<DateTime>)
173          newList.Add(new List<DateTime>());
174        else if (t is List<string>)
175          newList.Add(new List<string>());
176        else
177          throw new InvalidOperationException();
178      }
179      return newList;
180    }
181  }
182}
Note: See TracBrowser for help on using the repository browser.