Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataAnalysisCSVImport/HeuristicLab.Problems.Instances.DataAnalysis/3.3/Classification/CSV/ClassifiactionCSVInstanceProvider.cs @ 8715

Last change on this file since 8715 was 8715, checked in by sforsten, 12 years ago

#1942:

  • added csv import dialog for regression
  • improved existing dialog (tool tip, design, preview of dataset)
File size: 9.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Globalization;
26using System.IO;
27using System.Linq;
28using System.Text;
29using HeuristicLab.Common;
30using HeuristicLab.Problems.DataAnalysis;
31
32namespace HeuristicLab.Problems.Instances.DataAnalysis {
33  public class ClassificationCSVInstanceProvider : ClassificationInstanceProvider {
34    public override string Name {
35      get { return "CSV File"; }
36    }
37    public override string Description {
38      get {
39        return "";
40      }
41    }
42    public override Uri WebLink {
43      get { return new Uri("http://dev.heuristiclab.com/trac/hl/core/wiki/UsersFAQ#DataAnalysisImportFileFormat"); }
44    }
45    public override string ReferencePublication {
46      get { return ""; }
47    }
48
49    public override IEnumerable<IDataDescriptor> GetDataDescriptors() {
50      return new List<IDataDescriptor>();
51    }
52
53    public override IClassificationProblemData LoadData(IDataDescriptor descriptor) {
54      throw new NotImplementedException();
55    }
56
57    public override bool CanImportData {
58      get { return true; }
59    }
60    public override IClassificationProblemData ImportData(string path) {
61      TableFileParser csvFileParser = new TableFileParser();
62
63      csvFileParser.Parse(path);
64
65      Dataset dataset = new Dataset(csvFileParser.VariableNames, csvFileParser.Values);
66      string targetVar = dataset.DoubleVariables.Last();
67
68      // turn of input variables that are constant in the training partition
69      var allowedInputVars = new List<string>();
70      var trainingIndizes = Enumerable.Range(0, (csvFileParser.Rows * 2) / 3);
71      if (trainingIndizes.Count() >= 2) {
72        foreach (var variableName in dataset.DoubleVariables) {
73          if (dataset.GetDoubleValues(variableName, trainingIndizes).Range() > 0 &&
74            variableName != targetVar)
75            allowedInputVars.Add(variableName);
76        }
77      } else {
78        allowedInputVars.AddRange(dataset.DoubleVariables.Where(x => !x.Equals(targetVar)));
79      }
80
81      ClassificationProblemData classificationData = new ClassificationProblemData(dataset, allowedInputVars, targetVar);
82
83      int trainingPartEnd = trainingIndizes.Last();
84      classificationData.TrainingPartition.Start = trainingIndizes.First();
85      classificationData.TrainingPartition.End = trainingPartEnd;
86      classificationData.TestPartition.Start = trainingPartEnd;
87      classificationData.TestPartition.End = csvFileParser.Rows;
88
89      classificationData.Name = Path.GetFileName(path);
90
91      return classificationData;
92    }
93
94    protected override IClassificationProblemData ImportData(string path, ClassificationImportType type, TableFileParser csvFileParser) {
95      int trainingPartEnd = (csvFileParser.Rows * type.Training) / 100;
96      List<IList> values = csvFileParser.Values;
97      if (type.Shuffle) {
98        values = Shuffle(values, csvFileParser.VariableNames.ToList().FindIndex(x => x.Equals(type.TargetVariable)),
99                         type.Training, out trainingPartEnd);
100      }
101
102      Dataset dataset = new Dataset(csvFileParser.VariableNames, values);
103
104      // turn of input variables that are constant in the training partition
105      var allowedInputVars = new List<string>();
106      var trainingIndizes = Enumerable.Range(0, trainingPartEnd);
107      if (trainingIndizes.Count() >= 2) {
108        foreach (var variableName in dataset.DoubleVariables) {
109          if (dataset.GetDoubleValues(variableName, trainingIndizes).Range() > 0 &&
110            variableName != type.TargetVariable)
111            allowedInputVars.Add(variableName);
112        }
113      } else {
114        allowedInputVars.AddRange(dataset.DoubleVariables.Where(x => !x.Equals(type.TargetVariable)));
115      }
116
117      ClassificationProblemData classificationData = new ClassificationProblemData(dataset, allowedInputVars, type.TargetVariable);
118
119      classificationData.TrainingPartition.Start = 0;
120      classificationData.TrainingPartition.End = trainingPartEnd;
121      classificationData.TestPartition.Start = trainingPartEnd;
122      classificationData.TestPartition.End = csvFileParser.Rows;
123
124      classificationData.Name = Path.GetFileName(path);
125
126      return classificationData;
127    }
128
129    protected List<IList> Shuffle(List<IList> values, int target, int trainingPercentage, out int trainingPartEnd) {
130      IList targetValues = values[target];
131      var group = targetValues.Cast<double>().GroupBy(x => x).Select(g => new { Key = g.Key, Count = g.Count() }).ToList();
132      Dictionary<double, double> taken = new Dictionary<double, double>();
133      foreach (var classCount in group) {
134        taken[classCount.Key] = (classCount.Count * trainingPercentage) / 100.0;
135      }
136
137      List<IList> training = GetListOfIListCopy(values);
138      List<IList> test = GetListOfIListCopy(values);
139
140      for (int i = 0; i < targetValues.Count; i++) {
141        if (taken[(double)targetValues[i]] > 0) {
142          AddRow(training, values, i);
143          taken[(double)targetValues[i]]--;
144        } else {
145          AddRow(test, values, i);
146        }
147      }
148
149      trainingPartEnd = training.First().Count;
150
151      training = Shuffle(training);
152      test = Shuffle(test);
153      for (int i = 0; i < training.Count; i++) {
154        for (int j = 0; j < test[i].Count; j++) {
155          training[i].Add(test[i][j]);
156        }
157      }
158
159      return training;
160    }
161
162    private void AddRow(List<IList> destination, List<IList> source, int index) {
163      for (int i = 0; i < source.Count; i++) {
164        destination[i].Add(source[i][index]);
165      }
166    }
167
168    private List<IList> GetListOfIListCopy(List<IList> values) {
169      List<IList> newList = new List<IList>(values.Count);
170      for (int col = 0; col < values.Count; col++) {
171
172        if (values[col] is List<double>)
173          newList.Add(new List<double>());
174        else if (values[col] is List<DateTime>)
175          newList.Add(new List<DateTime>());
176        else if (values[col] is List<string>)
177          newList.Add(new List<string>());
178        else
179          throw new InvalidOperationException();
180      }
181      return newList;
182    }
183
184    private List<IList> NormalizeClasses(List<IList> values) {
185      int column = GetLastDoubleColumn(values);
186      Dictionary<object, int> count = new Dictionary<object, int>();
187      foreach (var item in values[column]) {
188        if (count.Keys.Contains(item)) {
189          count[item]++;
190        } else {
191          count.Add(item, 1);
192        }
193      }
194      int min = count.Values.Min();
195      Dictionary<object, int> taken = new Dictionary<object, int>();
196      foreach (var key in count.Keys) {
197        taken[key] = 0;
198      }
199      List<IList> normalizedValues = new List<IList>(values.Count);
200      for (int col = 0; col < values.Count; col++) {
201
202        if (values[col] is List<double>)
203          normalizedValues.Add(new List<double>());
204        else if (values[col] is List<DateTime>)
205          normalizedValues.Add(new List<DateTime>());
206        else if (values[col] is List<string>)
207          normalizedValues.Add(new List<string>());
208        else
209          throw new InvalidOperationException();
210      }
211      for (int i = 0; i < values.First().Count; i++) {
212        if (taken[values[column][i]] < min) {
213          taken[values[column][i]]++;
214          for (int col = 0; col < values.Count; col++) {
215            normalizedValues[col].Add(values[col][i]);
216          }
217        }
218      }
219      return normalizedValues;
220    }
221
222    private int GetLastDoubleColumn(List<IList> values) {
223      for (int i = values.Count - 1; i >= 0; i--) {
224        if (values[i] is List<double>) {
225          return i;
226        }
227      }
228      throw new ArgumentException("No possible Target Variable could be found!");
229    }
230
231    public override bool CanExportData {
232      get { return true; }
233    }
234    public override void ExportData(IClassificationProblemData instance, string path) {
235      var strBuilder = new StringBuilder();
236      var colSep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
237      foreach (var variable in instance.Dataset.VariableNames) {
238        strBuilder.Append(variable.Replace(colSep, String.Empty) + colSep);
239      }
240      strBuilder.Remove(strBuilder.Length - colSep.Length, colSep.Length);
241      strBuilder.AppendLine();
242
243      var dataset = instance.Dataset;
244
245      for (int i = 0; i < dataset.Rows; i++) {
246        for (int j = 0; j < dataset.Columns; j++) {
247          if (j > 0) strBuilder.Append(colSep);
248          strBuilder.Append(dataset.GetValue(i, j));
249        }
250        strBuilder.AppendLine();
251      }
252
253      using (var writer = new StreamWriter(path)) {
254        writer.Write(strBuilder);
255      }
256    }
257  }
258}
Note: See TracBrowser for help on using the repository browser.