Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/LibSVM/RangeTransform.cs @ 2561

Last change on this file since 2561 was 2418, checked in by gkronber, 15 years ago

Fixed bugs in text export/import of SVM models. #772.

File size: 8.3 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
19
20using System;
21using System.IO;
22using System.Threading;
23using System.Globalization;
24
25namespace SVM {
26  /// <summary>
27  /// Class which encapsulates a range transformation.
28  /// </summary>
29  public class RangeTransform : IRangeTransform {
30    /// <summary>
31    /// Default lower bound for scaling (-1).
32    /// </summary>
33    public const int DEFAULT_LOWER_BOUND = -1;
34    /// <summary>
35    /// Default upper bound for scaling (1).
36    /// </summary>
37    public const int DEFAULT_UPPER_BOUND = 1;
38
39    /// <summary>
40    /// Determines the Range transform for the provided problem.  Uses the default lower and upper bounds.
41    /// </summary>
42    /// <param name="prob">The Problem to analyze</param>
43    /// <returns>The Range transform for the problem</returns>
44    public static RangeTransform Compute(Problem prob) {
45      return Compute(prob, DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND);
46    }
47    /// <summary>
48    /// Determines the Range transform for the provided problem.
49    /// </summary>
50    /// <param name="prob">The Problem to analyze</param>
51    /// <param name="lowerBound">The lower bound for scaling</param>
52    /// <param name="upperBound">The upper bound for scaling</param>
53    /// <returns>The Range transform for the problem</returns>
54    public static RangeTransform Compute(Problem prob, double lowerBound, double upperBound) {
55      double[] minVals = new double[prob.MaxIndex];
56      double[] maxVals = new double[prob.MaxIndex];
57      for (int i = 0; i < prob.MaxIndex; i++) {
58        minVals[i] = double.MaxValue;
59        maxVals[i] = double.MinValue;
60      }
61      for (int i = 0; i < prob.Count; i++) {
62        for (int j = 0; j < prob.X[i].Length; j++) {
63          int index = prob.X[i][j].Index - 1;
64          double value = prob.X[i][j].Value;
65          minVals[index] = Math.Min(minVals[index], value);
66          maxVals[index] = Math.Max(maxVals[index], value);
67        }
68      }
69      for (int i = 0; i < prob.MaxIndex; i++) {
70        if (minVals[i] == double.MaxValue || maxVals[i] == double.MinValue) {
71          minVals[i] = 0;
72          maxVals[i] = 0;
73        }
74      }
75      return new RangeTransform(minVals, maxVals, lowerBound, upperBound);
76    }
77
78    private double[] _inputStart;
79    private double[] _inputScale;
80    private double _outputStart;
81    private double _outputScale;
82    private int _length;
83
84    /// <summary>
85    /// Constructor.
86    /// </summary>
87    /// <param name="minValues">The minimum values in each dimension.</param>
88    /// <param name="maxValues">The maximum values in each dimension.</param>
89    /// <param name="lowerBound">The desired lower bound for all dimensions.</param>
90    /// <param name="upperBound">The desired upper bound for all dimensions.</param>
91    public RangeTransform(double[] minValues, double[] maxValues, double lowerBound, double upperBound) {
92      _length = minValues.Length;
93      if (maxValues.Length != _length)
94        throw new Exception("Number of max and min values must be equal.");
95      _inputStart = new double[_length];
96      _inputScale = new double[_length];
97      for (int i = 0; i < _length; i++) {
98        _inputStart[i] = minValues[i];
99        _inputScale[i] = maxValues[i] - minValues[i];
100      }
101      _outputStart = lowerBound;
102      _outputScale = upperBound - lowerBound;
103    }
104    private RangeTransform(double[] inputStart, double[] inputScale, double outputStart, double outputScale, int length) {
105      _inputStart = inputStart;
106      _inputScale = inputScale;
107      _outputStart = outputStart;
108      _outputScale = outputScale;
109      _length = length;
110    }
111    /// <summary>
112    /// Transforms the input array based upon the values provided.
113    /// </summary>
114    /// <param name="input">The input array</param>
115    /// <returns>A scaled array</returns>
116    public Node[] Transform(Node[] input) {
117      Node[] output = new Node[input.Length];
118      for (int i = 0; i < output.Length; i++) {
119        int index = input[i].Index;
120        double value = input[i].Value;
121        output[i] = new Node(index, Transform(value, index));
122      }
123      return output;
124    }
125
126    /// <summary>
127    /// Transforms this an input value using the scaling transform for the provided dimension.
128    /// </summary>
129    /// <param name="input">The input value to transform</param>
130    /// <param name="index">The dimension whose scaling transform should be used</param>
131    /// <returns>The scaled value</returns>
132    public double Transform(double input, int index) {
133      index--;
134      double tmp = input - _inputStart[index];
135      if (_inputScale[index] == 0)
136        return 0;
137      tmp /= _inputScale[index];
138      tmp *= _outputScale;
139      return tmp + _outputStart;
140    }
141    /// <summary>
142    /// Writes this Range transform to a stream.
143    /// </summary>
144    /// <param name="stream">The stream to write to</param>
145    /// <param name="r">The range to write</param>
146    public static void Write(Stream stream, RangeTransform r) {
147      TemporaryCulture.Start();
148
149      StreamWriter output = new StreamWriter(stream);
150      output.WriteLine(r._length);
151      output.Write(r._inputStart[0].ToString("r"));
152      for (int i = 1; i < r._inputStart.Length; i++)
153        output.Write(" " + r._inputStart[i].ToString("r"));
154      output.WriteLine();
155      output.Write(r._inputScale[0].ToString("r"));
156      for (int i = 1; i < r._inputScale.Length; i++)
157        output.Write(" " + r._inputScale[i].ToString("r"));
158      output.WriteLine();
159      output.WriteLine("{0} {1}", r._outputStart.ToString("r"), r._outputScale.ToString("r"));
160      output.Flush();
161
162      TemporaryCulture.Stop();
163    }
164
165    /// <summary>
166    /// Writes this Range transform to a file.    This will overwrite any previous data in the file.
167    /// </summary>
168    /// <param name="outputFile">The file to write to</param>
169    /// <param name="r">The Range to write</param>
170    public static void Write(string outputFile, RangeTransform r) {
171      FileStream s = File.Open(outputFile, FileMode.Create);
172      try {
173        Write(s, r);
174      }
175      finally {
176        s.Close();
177      }
178    }
179
180    /// <summary>
181    /// Reads a Range transform from a file.
182    /// </summary>
183    /// <param name="inputFile">The file to read from</param>
184    /// <returns>The Range transform</returns>
185    public static RangeTransform Read(string inputFile) {
186      FileStream s = File.OpenRead(inputFile);
187      try {
188        return Read(s);
189      }
190      finally {
191        s.Close();
192      }
193    }
194
195    /// <summary>
196    /// Reads a Range transform from a stream.
197    /// </summary>
198    /// <param name="stream">The stream to read from</param>
199    /// <returns>The Range transform</returns>
200    public static RangeTransform Read(Stream stream) {
201      return Read(new StreamReader(stream));
202    }
203
204    public static RangeTransform Read(TextReader input) {
205      TemporaryCulture.Start();
206
207      int length = int.Parse(input.ReadLine());
208      double[] inputStart = new double[length];
209      double[] inputScale = new double[length];
210      string[] parts = input.ReadLine().Split();
211      for (int i = 0; i < length; i++)
212        inputStart[i] = double.Parse(parts[i]);
213      parts = input.ReadLine().Split();
214      for (int i = 0; i < length; i++)
215        inputScale[i] = double.Parse(parts[i]);
216      parts = input.ReadLine().Split();
217      double outputStart = double.Parse(parts[0]);
218      double outputScale = double.Parse(parts[1]);
219
220      TemporaryCulture.Stop();
221
222      return new RangeTransform(inputStart, inputScale, outputStart, outputScale, length);
223    }
224  }
225}
Note: See TracBrowser for help on using the repository browser.