source: trunk/c++_tools/classifier/SVM.h @ 592

Last change on this file since 592 was 592, checked in by Peter, 15 years ago

added random_shuffle function in Target class

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 8.1 KB
Line 
1// $Id: SVM.h 592 2006-08-24 11:18:28Z peter $
2
3#ifndef _theplu_classifier_svm_
4#define _theplu_classifier_svm_
5
6#include <c++_tools/classifier/DataLookup2D.h>
7#include <c++_tools/classifier/KernelLookup.h>
8#include <c++_tools/classifier/SupervisedClassifier.h>
9#include <c++_tools/classifier/Target.h>
10#include <c++_tools/gslapi/vector.h>
11
12#include <cassert>
13#include <utility>
14#include <vector>
15
16
17namespace theplu {
18namespace classifier { 
19
20  // @internal Class keeping track of which samples are support vectors and
21  // not. The first nof_sv elements in the vector are indices of the
22  // support vectors
23  //
24  class Index
25  {
26
27  public:
28    //Default Contructor
29    Index(); 
30
31    //
32    Index(const size_t);
33
34    // @return index_first
35    inline size_t index_first(void) const 
36    { assert(index_first_<size()); return index_first_; }
37
38    // @return index_second
39    inline size_t index_second(void) const 
40    { assert(index_second_<size()); return index_second_; }
41
42    // synch the object against alpha
43    void init(const gslapi::vector& alpha, const double);
44
45    // @return nof samples
46    inline size_t size(void) const { return vec_.size(); }
47
48    // @return nof support vectors
49    inline size_t nof_sv(void) const { return nof_sv_; }
50
51    // making first to an nsv. If already sv, nothing happens.
52    void nsv_first(void);
53
54    // making second to an nsv. If already sv, nothing happens.
55    void nsv_second(void);   
56
57    // randomizes the nsv part of vector and sets index_first to
58    // nof_sv_ (the first nsv)
59    void shuffle(void);
60
61    // making first to a sv. If already sv, nothing happens.
62    void sv_first(void);
63
64    // making second to a sv. If already sv, nothing happens.
65    void sv_second(void);
66
67    //
68    void update_first(const size_t);
69
70    //
71    void update_second(const size_t);
72
73    // @return value_first
74    inline size_t value_first(void) const 
75    { assert(value_first_<size()); return value_first_; }
76
77    // @return const ref value_second
78    inline size_t value_second(void) const 
79    { assert(value_first_<size()); return value_second_; }
80
81    inline size_t operator()(size_t i) const { 
82      assert(i<size()); assert(vec_[i]<size()); return vec_[i]; }
83
84  private:
85    size_t index_first_;
86    size_t index_second_;
87    size_t nof_sv_;
88    std::vector<size_t> vec_;
89    size_t value_first_; // vec_[index_first_] exists for fast access
90    size_t value_second_; // vec_[index_second_] exists for fast access
91   
92  };
93
94  ///
95  /// @brief Support Vector Machine
96  ///
97  ///
98  ///
99  /// Class for SVM using Keerthi's second modification of Platt's
100  /// Sequential Minimal Optimization. The SVM uses all data given for
101  /// training. If validation or testing is wanted this should be
102  /// taken care of outside (in the kernel).
103  ///   
104  class SVM : public SupervisedClassifier
105  {
106 
107  public:
108    ///
109    /// Constructor taking the kernel and the target vector as
110    /// input.
111    ///
112    /// @note if the @a target or @a kernel
113    /// is destroyed the behaviour is undefined.
114    ///
115    SVM(const KernelLookup& kernel, const Target& target);
116
117    ///
118    /// Constructor taking the kernel, the target vector, the score
119    /// used to rank data inputs, and the number of top ranked data
120    /// inputs to use in the classification.
121    ///
122    /// @note if the @a target or @a kernel
123    /// is destroyed the behaviour is undefined.
124    ///
125    /// @note make no effect yet
126    SVM(const KernelLookup& kernel, const Target& target,
127        statistics::Score&, const size_t);
128
129    ///
130    /// Destructor
131    ///
132    virtual ~SVM();
133
134    ///
135    /// @todo doc
136    ///
137    SupervisedClassifier* 
138    make_classifier(const DataLookup2D&, const Target&) const;
139
140    ///
141    /// @return \f$\alpha\f$
142    ///
143    inline const gslapi::vector& alpha(void) const { return alpha_; }
144
145    ///
146    /// The C-parameter is the balance term (see train()). A very
147    /// large C means the training will be focused on getting samples
148    /// correctly classified, with risk for overfitting and poor
149    /// generalisation. A too small C will result in a training where
150    /// misclassifications are not penalized. C is weighted with
151    /// respect to the size, so \f$ n_+C_+ = n_-C_- \f$, meaning a
152    /// misclassificaion of the smaller group is penalized
153    /// harder. This balance is equivalent to the one occuring for
154    /// regression with regularisation, or ANN-training with a
155    /// weight-decay term. Default is C set to infinity.
156    ///
157    /// @returns mean of vector \f$ C_i \f$
158    ///
159    inline double C(void) const { return 1/C_inverse_; }
160
161    ///
162    /// Default is max_epochs set to 10,000,000.
163    ///
164    /// @return number of maximal epochs
165    ///
166    inline long int max_epochs(void) const {return max_epochs_;}
167   
168    ///
169    /// The output is calculated as \f$ o_i = \sum \alpha_j t_j K_{ij}
170    /// + bias \f$, where \f$ t \f$ is the target.
171    ///
172    /// @return output
173    ///
174    inline const theplu::gslapi::vector& output(void) const { return output_; }
175
176    ///
177    /// Generate prediction @a predict from @a input. The prediction
178    /// is calculated as the output times the margin, i.e., geometric
179    /// distance from decision hyperplane: \f$ \frac{ \sum \alpha_j
180    /// t_j K_{ij} + bias}{w} \f$ The output has 2 rows. The first row
181    /// is for binary target true, and the second is for binary target
182    /// false. The second row is superfluous as it is the first row
183    /// negated. It exist just to be aligned with multi-class
184    /// SupervisedClassifiers. Each column in @a input and @a output
185    /// corresponds to a sample to predict. Each row in @a input
186    /// corresponds to a training sample, and more exactly row i in @a
187    /// input should correspond to row i in KernelLookup that was used
188    /// for training.
189    ///
190    /// @note
191    ///
192    void predict(const DataLookup2D& input, gslapi::matrix& predict) const;
193
194    ///
195    /// @return output times margin (i.e. geometric distance from
196    /// decision hyperplane) from data @a input
197    ///
198    double predict(const DataLookup1D& input) const;
199
200    ///
201    /// @return output times margin from data @a input with
202    /// corresponding @a weight
203    ///
204    double predict(const DataLookup1D& input, const DataLookup1D& weight) const;
205
206    ///
207    /// Function sets \f$ \alpha=0 \f$ and makes SVM untrained.
208    ///
209    inline void reset(void) 
210    { trained_=false; alpha_=gslapi::vector(target_.size(),0); }
211
212    ///
213    /// @brief sets the C-Parameter
214    ///
215    void set_C(const double);
216
217    ///
218    /// Training the SVM following Platt's SMO, with Keerti's
219    /// modifacation. Minimizing \f$ \frac{1}{2}\sum
220    /// y_iy_j\alpha_i\alpha_j(K_{ij}+\frac{1}{C_i}\delta_{ij}) \f$,
221    /// which corresponds to minimizing \f$ \sum w_i^2+\sum C_i\xi_i^2
222    /// \f$.
223    ///
224    bool train();
225
226       
227     
228  private:
229    ///
230    /// Copy constructor. (not implemented)
231    ///
232    SVM(const SVM&);
233         
234    ///
235    /// Calculates bounds for alpha2
236    ///
237    void bounds(double&, double&) const;
238
239    ///
240    /// @brief calculates the bias term
241    ///
242    /// @return true if successful
243    ///
244    bool calculate_bias(void);
245
246    ///
247    /// Calculate margin that is inverse of w
248    ///
249    void calculate_margin(void);
250
251    ///
252    ///   Private function choosing which two elements that should be
253    ///   updated. First checking for the biggest violation (output - target =
254    ///   0) among support vectors (alpha!=0). If no violation was found check
255    ///   sequentially among the other samples. If no violation there as
256    ///   well training is completed
257    ///
258    ///  @return true if a pair of samples that violate the conditions
259    ///  can be found
260    ///
261    bool choose(const theplu::gslapi::vector&);
262
263    ///
264    /// @return kernel modified with diagonal term (soft margin)
265    ///
266    inline double kernel_mod(const size_t i, const size_t j) const 
267    { return i!=j ? (*kernel_)(i,j) : (*kernel_)(i,j) + C_inverse_; }
268   
269    /// @return 1 if i belong to binary target true else -1
270    inline int target(size_t i) const { return target_.binary(i) ? 1 : -1; }
271
272    gslapi::vector alpha_;
273    double bias_;
274    double C_inverse_;
275    const KernelLookup* kernel_; 
276    double margin_;
277    unsigned long int max_epochs_;
278    gslapi::vector output_;
279    bool owner_;
280    Index sample_;
281    bool trained_;
282    double tolerance_;
283
284  };
285
286  ///
287  /// @todo The output operator for the SVM class.
288  ///
289  //std::ostream& operator<< (std::ostream& s, const SVM&);
290 
291 
292}} // of namespace classifier and namespace theplu
293
294#endif
Note: See TracBrowser for help on using the repository browser.