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

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

closes #106 make_classifier is again taking DataLookup2D and Target making SupervisedClassifer? useful also in structure without SubsetGenerator?.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date ID
File size: 7.6 KB
Line 
1#ifndef _theplu_classifier_svm_
2#define _theplu_classifier_svm_
3
4// $Id$
5
6#include <c++_tools/classifier/KernelLookup.h>
7#include <c++_tools/classifier/SupervisedClassifier.h>
8#include <c++_tools/classifier/Target.h>
9#include <c++_tools/utility/vector.h>
10
11#include <cassert>
12#include <utility>
13#include <vector>
14
15
16namespace theplu {
17namespace classifier { 
18
19  class DataLookup2D;
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 utility::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    /// Destructor
119    ///
120    virtual ~SVM();
121
122    ///
123    /// If DataLookup2D is not a KernelLookup a bad_cast exception is thrown.
124    ///
125    SupervisedClassifier* 
126    make_classifier(const DataLookup2D&, const Target&) const;
127
128    ///
129    /// @return \f$ \alpha \f$
130    ///
131    inline const utility::vector& alpha(void) const { return alpha_; }
132
133    ///
134    /// The C-parameter is the balance term (see train()). A very
135    /// large C means the training will be focused on getting samples
136    /// correctly classified, with risk for overfitting and poor
137    /// generalisation. A too small C will result in a training where
138    /// misclassifications are not penalized. C is weighted with
139    /// respect to the size, so \f$ n_+C_+ = n_-C_- \f$, meaning a
140    /// misclassificaion of the smaller group is penalized
141    /// harder. This balance is equivalent to the one occuring for
142    /// regression with regularisation, or ANN-training with a
143    /// weight-decay term. Default is C set to infinity.
144    ///
145    /// @returns mean of vector \f$ C_i \f$
146    ///
147    inline double C(void) const { return 1/C_inverse_; }
148
149    ///
150    /// Default is max_epochs set to 10,000,000.
151    ///
152    /// @return number of maximal epochs
153    ///
154    inline long int max_epochs(void) const {return max_epochs_;}
155   
156    ///
157    /// The output is calculated as \f$ o_i = \sum \alpha_j t_j K_{ij}
158    /// + bias \f$, where \f$ t \f$ is the target.
159    ///
160    /// @return output
161    ///
162    inline const theplu::utility::vector& output(void) const { return output_; }
163
164    ///
165    /// Generate prediction @a predict from @a input. The prediction
166    /// is calculated as the output times the margin, i.e., geometric
167    /// distance from decision hyperplane: \f$ \frac{ \sum \alpha_j
168    /// t_j K_{ij} + bias}{w} \f$ The output has 2 rows. The first row
169    /// is for binary target true, and the second is for binary target
170    /// false. The second row is superfluous as it is the first row
171    /// negated. It exist just to be aligned with multi-class
172    /// SupervisedClassifiers. Each column in @a input and @a output
173    /// corresponds to a sample to predict. Each row in @a input
174    /// corresponds to a training sample, and more exactly row i in @a
175    /// input should correspond to row i in KernelLookup that was used
176    /// for training.
177    ///
178    /// @note
179    ///
180    void predict(const DataLookup2D& input, utility::matrix& predict) const;
181
182    ///
183    /// @return output times margin (i.e. geometric distance from
184    /// decision hyperplane) from data @a input
185    ///
186    double predict(const DataLookup1D& input) const;
187
188    ///
189    /// @return output times margin from data @a input with
190    /// corresponding @a weight
191    ///
192    double predict(const DataLookupWeighted1D& input) const;
193
194    ///
195    /// Function sets \f$ \alpha=0 \f$ and makes SVM untrained.
196    ///
197    inline void reset(void) 
198    { trained_=false; alpha_=utility::vector(target_.size(),0); }
199
200    ///
201    /// @brief sets the C-Parameter
202    ///
203    void set_C(const double);
204
205    ///
206    /// Training the SVM following Platt's SMO, with Keerti's
207    /// modifacation. Minimizing \f$ \frac{1}{2}\sum
208    /// y_iy_j\alpha_i\alpha_j(K_{ij}+\frac{1}{C_i}\delta_{ij}) \f$ ,
209    /// which corresponds to minimizing \f$ \sum w_i^2+\sum C_i\xi_i^2
210    /// \f$.
211    ///
212    bool train();
213
214       
215     
216  private:
217    ///
218    /// Copy constructor. (not implemented)
219    ///
220    SVM(const SVM&);
221         
222    ///
223    /// Calculates bounds for alpha2
224    ///
225    void bounds(double&, double&) const;
226
227    ///
228    /// @brief calculates the bias term
229    ///
230    /// @return true if successful
231    ///
232    bool calculate_bias(void);
233
234    ///
235    /// Calculate margin that is inverse of w
236    ///
237    void calculate_margin(void);
238
239    ///
240    ///   Private function choosing which two elements that should be
241    ///   updated. First checking for the biggest violation (output - target =
242    ///   0) among support vectors (alpha!=0). If no violation was found check
243    ///   sequentially among the other samples. If no violation there as
244    ///   well training is completed
245    ///
246    ///  @return true if a pair of samples that violate the conditions
247    ///  can be found
248    ///
249    bool choose(const theplu::utility::vector&);
250
251    ///
252    /// @return kernel modified with diagonal term (soft margin)
253    ///
254    inline double kernel_mod(const size_t i, const size_t j) const 
255    { return i!=j ? (*kernel_)(i,j) : (*kernel_)(i,j) + C_inverse_; }
256   
257    /// @return 1 if i belong to binary target true else -1
258    inline int target(size_t i) const { return target_.binary(i) ? 1 : -1; }
259
260    utility::vector alpha_;
261    double bias_;
262    double C_inverse_;
263    const KernelLookup* kernel_; 
264    double margin_;
265    unsigned long int max_epochs_;
266    utility::vector output_;
267    bool owner_;
268    Index sample_;
269    bool trained_;
270    double tolerance_;
271
272  };
273
274}} // of namespace classifier and namespace theplu
275
276#endif
Note: See TracBrowser for help on using the repository browser.