Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistentDataStructures/HeuristicLab.ExtLibs/HeuristicLab.LibSVM/3.12/LibSVM-3.12/RangeTransform.cs @ 14710

Last change on this file since 14710 was 8607, checked in by gkronber, 12 years ago

#1944 added new C# port of libSVM 3.12 and the HL wrapper plugin

File size: 8.9 KB
Line 
1/*
2 * SVM.NET Library
3 * Copyright (C) 2008 Matthew Johnson
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 *
18 * Adaptions to work with direct C# translation of the java libSVM source code (version 3.1.2) by Gabriel Kronberger
19 *
20 */
21
22
23using System;
24using System.Globalization;
25using System.IO;
26using System.Linq;
27using System.Threading;
28
29namespace LibSVM {
30  /// <summary>
31  /// Class which encapsulates a range transformation.
32  /// </summary>
33  public class RangeTransform {
34    /// <summary>
35    /// Default lower bound for scaling (-1).
36    /// </summary>
37    public const int DEFAULT_LOWER_BOUND = -1;
38    /// <summary>
39    /// Default upper bound for scaling (1).
40    /// </summary>
41    public const int DEFAULT_UPPER_BOUND = 1;
42
43    /// <summary>
44    /// Determines the Range transform for the provided problem.  Uses the default lower and upper bounds.
45    /// </summary>
46    /// <param name="prob">The Problem to analyze</param>
47    /// <returns>The Range transform for the problem</returns>
48    public static RangeTransform Compute(svm_problem prob) {
49      return Compute(prob, DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND);
50    }
51    /// <summary>
52    /// Determines the Range transform for the provided problem.
53    /// </summary>
54    /// <param name="prob">The Problem to analyze</param>
55    /// <param name="lowerBound">The lower bound for scaling</param>
56    /// <param name="upperBound">The upper bound for scaling</param>
57    /// <returns>The Range transform for the problem</returns>
58    public static RangeTransform Compute(svm_problem prob, double lowerBound, double upperBound) {
59      // node indices must be ordered
60      int maxIndex = prob.x.Select(arr => arr.Last().index).Max();
61
62      double[] minVals = new double[maxIndex];
63      double[] maxVals = new double[maxIndex];
64      int[] count = new int[maxIndex];
65      for (int i = 0; i < maxIndex; i++) {
66        minVals[i] = double.MaxValue;
67        maxVals[i] = double.MinValue;
68        count[i] = 0;
69      }
70      for (int i = 0; i < prob.l; i++) {
71        for (int j = 0; j < prob.x[i].Length; j++) {
72          int index = prob.x[i][j].index - 1;
73          double value = prob.x[i][j].value;
74          minVals[index] = Math.Min(minVals[index], value);
75          maxVals[index] = Math.Max(maxVals[index], value);
76          count[index]++;
77        }
78      }
79      for (int i = 0; i < maxIndex; i++) {
80        if (count[i] == 0) {
81          minVals[i] = 0;
82          maxVals[i] = 0;
83        }
84      }
85      return new RangeTransform(minVals, maxVals, lowerBound, upperBound);
86    }
87
88    private double[] _inputStart;
89    private double[] _inputScale;
90    private double _outputStart;
91    private double _outputScale;
92    private int _length;
93
94    /// <summary>
95    /// Constructor.
96    /// </summary>
97    /// <param name="minValues">The minimum values in each dimension.</param>
98    /// <param name="maxValues">The maximum values in each dimension.</param>
99    /// <param name="lowerBound">The desired lower bound for all dimensions.</param>
100    /// <param name="upperBound">The desired upper bound for all dimensions.</param>
101    public RangeTransform(double[] minValues, double[] maxValues, double lowerBound, double upperBound) {
102      _length = minValues.Length;
103      if (maxValues.Length != _length)
104        throw new Exception("Number of max and min values must be equal.");
105      _inputStart = new double[_length];
106      _inputScale = new double[_length];
107      for (int i = 0; i < _length; i++) {
108        _inputStart[i] = minValues[i];
109        _inputScale[i] = maxValues[i] - minValues[i];
110      }
111      _outputStart = lowerBound;
112      _outputScale = upperBound - lowerBound;
113    }
114    private RangeTransform(double[] inputStart, double[] inputScale, double outputStart, double outputScale, int length) {
115      _inputStart = inputStart;
116      _inputScale = inputScale;
117      _outputStart = outputStart;
118      _outputScale = outputScale;
119      _length = length;
120    }
121    /// <summary>
122    /// Transforms the input array based upon the values provided.
123    /// </summary>
124    /// <param name="input">The input array</param>
125    /// <returns>A scaled array</returns>
126    public svm_node[] Transform(svm_node[] input) {
127      svm_node[] output = new svm_node[input.Length];
128      for (int i = 0; i < output.Length; i++) {
129        int index = input[i].index;
130        double value = input[i].value;
131        output[i] = new svm_node() { index = index, value = Transform(value, index) };
132      }
133      return output;
134    }
135
136    /// <summary>
137    /// Transforms this an input value using the scaling transform for the provided dimension.
138    /// </summary>
139    /// <param name="input">The input value to transform</param>
140    /// <param name="index">The dimension whose scaling transform should be used</param>
141    /// <returns>The scaled value</returns>
142    public double Transform(double input, int index) {
143      index--;
144      double tmp = input - _inputStart[index];
145      if (Math.Abs(_inputScale[index]) < 1E-12)
146        return 0;
147      tmp /= _inputScale[index];
148      tmp *= _outputScale;
149      return tmp + _outputStart;
150    }
151    /// <summary>
152    /// Writes this Range transform to a stream.
153    /// </summary>
154    /// <param name="stream">The stream to write to</param>
155    /// <param name="r">The range to write</param>
156    public static void Write(Stream stream, RangeTransform r) {
157      var savedCulture = Thread.CurrentThread.CurrentCulture;
158      Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
159
160
161      StreamWriter output = new StreamWriter(stream);
162      output.WriteLine(r._length);
163      output.Write(r._inputStart[0].ToString("r"));
164      for (int i = 1; i < r._inputStart.Length; i++)
165        output.Write(" " + r._inputStart[i].ToString("r"));
166      output.WriteLine();
167      output.Write(r._inputScale[0].ToString("r"));
168      for (int i = 1; i < r._inputScale.Length; i++)
169        output.Write(" " + r._inputScale[i].ToString("r"));
170      output.WriteLine();
171      output.WriteLine("{0} {1}", r._outputStart.ToString("r"), r._outputScale.ToString("r"));
172      output.Flush();
173
174      Thread.CurrentThread.CurrentCulture = savedCulture;
175    }
176
177    /// <summary>
178    /// Writes this Range transform to a file.    This will overwrite any previous data in the file.
179    /// </summary>
180    /// <param name="outputFile">The file to write to</param>
181    /// <param name="r">The Range to write</param>
182    public static void Write(string outputFile, RangeTransform r) {
183      FileStream s = File.Open(outputFile, FileMode.Create);
184      try {
185        Write(s, r);
186      }
187      finally {
188        s.Close();
189      }
190    }
191
192    /// <summary>
193    /// Reads a Range transform from a file.
194    /// </summary>
195    /// <param name="inputFile">The file to read from</param>
196    /// <returns>The Range transform</returns>
197    public static RangeTransform Read(string inputFile) {
198      FileStream s = File.OpenRead(inputFile);
199      try {
200        return Read(s);
201      }
202      finally {
203        s.Close();
204      }
205    }
206
207    /// <summary>
208    /// Reads a Range transform from a stream.
209    /// </summary>
210    /// <param name="stream">The stream to read from</param>
211    /// <returns>The Range transform</returns>
212    public static RangeTransform Read(Stream stream) {
213      return Read(new StreamReader(stream));
214    }
215
216    public static RangeTransform Read(TextReader input) {
217      var savedCulture = Thread.CurrentThread.CurrentCulture;
218      Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
219
220      int length = int.Parse(input.ReadLine());
221      double[] inputStart = new double[length];
222      double[] inputScale = new double[length];
223      string[] parts = input.ReadLine().Split();
224      for (int i = 0; i < length; i++)
225        inputStart[i] = double.Parse(parts[i]);
226      parts = input.ReadLine().Split();
227      for (int i = 0; i < length; i++)
228        inputScale[i] = double.Parse(parts[i]);
229      parts = input.ReadLine().Split();
230      double outputStart = double.Parse(parts[0]);
231      double outputScale = double.Parse(parts[1]);
232
233      Thread.CurrentThread.CurrentCulture = savedCulture;
234
235      return new RangeTransform(inputStart, inputScale, outputStart, outputScale, length);
236    }
237  }
238}
Note: See TracBrowser for help on using the repository browser.