Feature Selection Toolbox FST4
UTIA · Czech Academy of Sciences
Loading...
Searching...
No Matches
classifier_rbf_svm.hpp
Go to the documentation of this file.
1#ifndef FSTCLASSIFIERRBFSVM_H
2#define FSTCLASSIFIERRBFSVM_H
3 /*
25=========================================================================
26Copyright and license:
27 * FST4 software (with the exception of any bundled or externally linked
28 third-party components) is Copyright (C) 2000-present Institute of
29 Information Theory and Automation of the Czech Academy of Sciences (UTIA).
30 * FST4 is free software: you can redistribute it and/or modify it under
31 the terms of the GNU Affero General Public License as published by the
32 Free Software Foundation, version 3. The full text of the license is in
33 the file LICENSE in the distribution root and at
34 https://www.gnu.org/licenses/agpl-3.0.html.
35 * FST4 is distributed in the hope that it will be useful, but WITHOUT ANY
36 WARRANTY; without even the implied warranty of MERCHANTABILITY or
37 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
38 License for more details.
39 * Closed-source use without the AGPL's copyleft obligations requires a
40 commercial license from UTIA; in case of interest write to
41 utia@utia.cas.cz. LICENSING.md in the distribution root explains both
42 options, the contributor license agreement that every contribution
43 requires, and the contacts (technical questions and pull requests:
44 somol@utia.cas.cz, with "FST" in the subject line).
45========================================================================== */
46
47#include <memory>
48#include <vector>
49#include <cmath>
50#include <limits>
51#include <cassert>
52#include <iostream>
53#include <sstream>
54#include "error.hpp"
55#include "global.hpp"
56#include "dense_train_tools.hpp"
57#include "clonable.hpp"
58#include "classifier.hpp"
59#include "fst_rand.hpp"
60
61/*============== Template parameter type naming conventions ==============
62--------- Numeric types: -------------------------------------------------
63DATATYPE - data sample values - usually real numbers (but may be integers
64 in text processing etc.)
65REALTYPE - must be real numbers - for representing intermediate results of
66 calculations like mean, covariance etc.
67IDXTYPE - index values for enumeration of data samples - (nonnegative) integers,
68 extent depends on numbers of samples in data
69DIMTYPE - index values for enumeration of features (dimensions), or classes (not
70 class sizes) - (nonnegative) integers, usually lower extent than IDXTYPE,
71 but be aware of expressions like _classes*_features*_features !
72 in linearized representations of feature matrices for all classes
73BINTYPE - feature selection marker type - represents ca. <10 different feature
74 states (selected, deselected, sel./desel. temporarily 1st nested loop, 2nd...)
75RETURNTYPE - criterion value: real value, but may be extended in future to support
76 multiple values
77--------- Class types: ---------------------------------------------------
78SUBSET - class of class type Subset
79CLASSIFIER - class implementing interface defined in abstract class Classifier
80EVALUATOR - class implementing interface defined in abstract class Sequential_Step
81DISTANCE - class implementing interface defined in abstract class Distance
82DATAACCESSOR - class implementing interface defined in abstract class Data_Accessor
83INTERVALCONTAINER - class of class type Data_Intervaller
84CONTAINER - STL container of class type Data_Interval
85========================================================================== */
86
87namespace FST {
88
127template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
128class Classifier_RBF_SVM : public Clonable_Impl<Classifier_RBF_SVM<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>,Classifier<RETURNTYPE,DIMTYPE,SUBSET,DATAACCESSOR> > {
129public:
132 typedef std::shared_ptr<DATAACCESSOR> PDataAccessor;
133 typedef std::shared_ptr<SUBSET> PSubset;
134 typedef typename DATAACCESSOR::PPattern PPattern;
135 Classifier_RBF_SVM() : _C(1.0), _gamma(0.0), _l2loss(false), _max_iter(1000), _tol(0.1),
136 _classes(0), _features(0), _subfeatures(0), _gamma_eff(0.0), _sv_count(0) {notify("Classifier_RBF_SVM constructor.");}
137 virtual ~Classifier_RBF_SVM() {notify("Classifier_RBF_SVM destructor.");}
138
139 void set_parameter_C(const REALTYPE c) {assert(c>0.0); _C=c;}
140 void set_parameter_gamma(const REALTYPE g) {assert(g>=0.0); _gamma=g;}
141 void set_l2_loss(const bool l2) {_l2loss=l2;}
142 void set_max_iter(const unsigned int mi) {assert(mi>0); _max_iter=mi;}
143 void set_tolerance(const REALTYPE t) {assert(t>0.0); _tol=t;}
144 REALTYPE get_parameter_C() const {return _C;}
145 REALTYPE get_parameter_gamma() const {return _gamma;}
146
147 void initialize(const PDataAccessor da);
148
162 bool optimize_parameters(const PDataAccessor da, const PSubset sub, const int max_points=100, const int max_throws=100,
163 const double lgC_min=-5, const double lgC_max=9, const double lggamma_min=-15, const double lggamma_max=3, std::ostream& os=std::cout);
164 bool mean_cv_accuracy(const PDataAccessor da, const PSubset sub, RETURNTYPE &mean);
165
170 virtual bool classify(DIMTYPE &cls, const PPattern &pattern) override;
174 virtual bool classify_scores(std::vector<RETURNTYPE> &scores, const PPattern &pattern) override;
186 virtual bool train(const PDataAccessor da, const PSubset sub) override;
187 // test() is the accuracy loop inherited from the Classifier base
188
189 virtual std::ostream& print(std::ostream& os) const override
190 {
191 os << "Classifier_RBF_SVM(C=" << _C << ", gamma=";
192 if(_gamma>0.0) os << _gamma; else os << "auto(1/d)";
193 os << ", loss=" << (_l2loss?"l2":"l1") << ", max_iter=" << _max_iter << ", tol=" << _tol << ")";
194 return os;
195 }
196protected:
197 // configuration
198 REALTYPE _C;
199 REALTYPE _gamma;
200 bool _l2loss;
201 unsigned int _max_iter;
202 REALTYPE _tol;
203
204 // data shape + trained state (support vectors only — compacted after training)
205 DIMTYPE _classes;
206 DIMTYPE _features;
207 DIMTYPE _subfeatures;
208 std::vector<DIMTYPE> _index;
209 std::vector<REALTYPE> _mean;
210 std::vector<REALTYPE> _scale;
211 REALTYPE _gamma_eff;
212 IDXTYPE _sv_count;
213 std::vector<REALTYPE> _sv;
214 std::vector<REALTYPE> _beta;
215
216 // training scratch (copied by clones harmlessly)
217 std::vector<REALTYPE> _Z;
218 std::vector<DIMTYPE> _y;
219 std::vector<REALTYPE> _alpha;
220 std::vector<REALTYPE> _s;
221 std::vector<REALTYPE> _K;
222 std::vector<REALTYPE> _krow;
223 std::vector<REALTYPE> _cs_x;
224 std::vector<REALTYPE> _cs_kv;
225 std::vector<RETURNTYPE> _cs_sc;
226 std::vector<REALTYPE> _beta_full;
227
229 static constexpr std::size_t KERNEL_BUDGET_ENTRIES=((std::size_t)1<<29)/sizeof(REALTYPE);
230
235 REALTYPE kernel_value(const REALTYPE *a, const REALTYPE *b) const
236 {
237 REALTYPE dist2=0.0;
238 for(std::size_t f=0;f<(std::size_t)_subfeatures;f++) {const REALTYPE dd=a[f]-b[f]; dist2+=dd*dd;}
239 return std::exp(-_gamma_eff*dist2)+(REALTYPE)1.0; // +1 = the penalized-bias kernel offset
240 }
241
246 const REALTYPE* kernel_row(const std::size_t i, const std::size_t N)
247 {
248 if(!_K.empty()) return &_K[i*N];
249 const REALTYPE *zi=&_Z[i*(std::size_t)_subfeatures];
250 for(std::size_t k=0;k<N;k++) _krow[k]=kernel_value(zi,&_Z[k*(std::size_t)_subfeatures]);
251 return _krow.data();
252 }
253
260 void solve_dual(REALTYPE *beta, const DIMTYPE positive_class);
261 DIMTYPE model_count() const {return (_classes==2)?1:_classes;}
262};
263
264template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
266{
267 notify("Classifier_RBF_SVM::initialize().");
268 assert(da);
269 assert(da->getNoOfFeatures()>0);
270 if(da->getNoOfClasses()<2) throw fst_error("Classifier_RBF_SVM requires at least 2 classes");
271 _classes=da->getNoOfClasses();
272 _features=da->getNoOfFeatures();
273 _index.resize(_features);
274 _subfeatures=0; // no model yet
275}
276
277template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
279{
280 RETURNTYPE val, result=0.0, cnt=0.0;
281 for(bool b=da->getFirstSplit();b==true;b=da->getNextSplit()) {
282 if(!train(da,sub)) return false;
283 if(!this->test(val,da)) return false; // this-> because test() lives in the dependent Classifier base
284 result+=val;
285 cnt+=1.0;
286 }
287 mean=result/(RETURNTYPE)cnt;
288 return true;
289}
290
291template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
292bool Classifier_RBF_SVM<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::optimize_parameters(const PDataAccessor da, const PSubset sub, const int max_points, const int max_throws, const double lgC_min, const double lgC_max, const double lggamma_min, const double lggamma_max, std::ostream& os)
293{
294 // the Classifier_LIBSVM::optimize_parameters protocol, C/gamma only (no coef0 axis)
295 assert(da);
296 assert(sub);
297 assert(sub->get_d_raw()>0);
298 assert(max_points>0);
299 assert(max_throws>0);
300 assert(lgC_max>lgC_min);
301 assert(lggamma_max>lggamma_min);
302 const double lgCrange=lgC_max-lgC_min;
303 const double lggammarange=lggamma_max-lggamma_min;
304 struct PSet {RETURNTYPE val; double Cpar, gamma;};
305 std::vector<PSet> paramlist;
306 // evaluate the initial (current) parameter set; gamma 0 = auto resolves to 1/d on the first train()
307 RETURNTYPE val, maxval, firstval;
308 if(!mean_cv_accuracy(da,sub,val)) return false;
309 firstval=maxval=val;
310 {
311 // NOTE: this line reports _gamma_eff (auto resolved to 1/d by the train() just done);
312 // the optimizer sets _gamma explicitly from here on, so the per-candidate and
313 // "after" lines below print concrete, directly comparable values as well
314 std::ostringstream sos;
315 sos << "RBF SVM before optimization: accuracy=" << val << ", C=" << _C << ", gamma=" << _gamma_eff << std::endl;
316 syncout::print(os,sos);
317 }
318 paramlist.push_back(PSet{val,(double)_C,(double)_gamma_eff});
319 PSet tmpset{0.0,0.0,0.0}, bestset{0.0,0.0,0.0};
320 for(int i=0;i<max_points;i++)
321 { // find and evaluate next parameter set candidate (space-filling choice, as in the LibSVM twin)
322 double maxdistmin=0.0;
323 for(int j=0;j<max_throws;j++)
324 {
325 // the bounds are natural logarithms: a candidate is exp(uniform(min,max))
326 tmpset.Cpar =std::exp(lgC_min+(((double)fst_rand()*(double)(lgC_max-lgC_min))/(double)FST_RAND_MAX));
327 tmpset.gamma=std::exp(lggamma_min+(((double)fst_rand()*(double)(lggamma_max-lggamma_min))/(double)FST_RAND_MAX));
328 double distmin=-1.0; // candidate (weighted) distance to already evaluated candidates
329 for(const PSet &ps : paramlist)
330 {
331 const double dC=(std::log(tmpset.Cpar)-std::log(ps.Cpar))/lgCrange;
332 const double dG=(std::log(tmpset.gamma)-std::log(ps.gamma))/lggammarange;
333 const double dist=std::sqrt(dC*dC+dG*dG);
334 // candidates more distant from all others are preferred; distances are
335 // weighed to penalize closeness to worse-performing candidates
336 assert(ps.val>0.0);
337 if(distmin<0 || dist*ps.val<distmin) distmin=dist*ps.val;
338 }
339 assert(distmin>=0.0);
340 if(distmin>maxdistmin) {maxdistmin=distmin; bestset=tmpset;}
341 }
342 // evaluate the chosen candidate and add it to the list
343 set_parameter_C((REALTYPE)bestset.Cpar);
344 set_parameter_gamma((REALTYPE)bestset.gamma);
345 if(!mean_cv_accuracy(da,sub,val)) return false;
346 bestset.val=val;
347 paramlist.push_back(bestset);
348 {
349 std::ostringstream sos;
350 sos << i+1 << ". ";
351 if(val>maxval) {maxval=val; sos << "BEST accuracy=";} else sos << "test accuracy=";
352 sos << bestset.val << ", C=" << _C << ", gamma=" << _gamma << std::endl;
353 syncout::print(os,sos);
354 }
355 }
356 // identify the best parameter set among all tested ones
357 assert(!paramlist.empty());
358 bestset=paramlist.front();
359 for(const PSet &ps : paramlist) if(ps.val>bestset.val) bestset=ps;
360 set_parameter_C((REALTYPE)bestset.Cpar);
361 set_parameter_gamma((REALTYPE)bestset.gamma);
362 {
363 std::ostringstream sos;
364 sos << "RBF SVM after optimization: accuracy=" << bestset.val << ", C=" << _C << ", gamma=" << _gamma << std::endl;
365 sos << "Accuracy difference=" << bestset.val-firstval << std::endl << std::endl;
366 syncout::print(os,sos);
367 }
368 return true;
369}
370
371template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
373{
374 // kernel dual coordinate descent: min 1/2 a^T Qbar a - e^T a, 0<=a_i<=U,
375 // Qbar_ij = y_i y_j K'_ij (+ diag 1/(2C) for L2-loss); the margin sums _s are
376 // maintained so the gradient check is O(1); an alpha update touches one kernel row
377 const std::size_t N=_y.size();
378 const REALTYPE U=_l2loss?std::numeric_limits<REALTYPE>::infinity():_C;
379 const REALTYPE Dii=_l2loss?(REALTYPE)1.0/((REALTYPE)2.0*_C):(REALTYPE)0.0;
380 const REALTYPE Qii=(REALTYPE)2.0+Dii; // K'(x,x) = exp(0)+1 = 2 on the diagonal, always
381
382 _alpha.assign(N,0.0);
383 _s.assign(N,0.0);
384 for(unsigned int sweep=0;sweep<_max_iter;sweep++)
385 {
386 REALTYPE pg_max=0.0;
387 for(std::size_t i=0;i<N;i++) // FIXED cyclic order - deterministic by design (no RNG)
388 {
389 const REALTYPE yi=(_y[i]==positive_class)?(REALTYPE)1.0:(REALTYPE)-1.0;
390 const REALTYPE g=yi*_s[i]-(REALTYPE)1.0+Dii*_alpha[i];
391
392 REALTYPE pg=g; // projected gradient at the box bounds
393 if(_alpha[i]<=0.0 && g>0.0) pg=0.0;
394 else if(_alpha[i]>=U && g<0.0) pg=0.0;
395 const REALTYPE apg=std::fabs(pg);
396 if(apg>pg_max) pg_max=apg;
397 if(apg>0.0)
398 {
399 const REALTYPE aold=_alpha[i];
400 REALTYPE anew=aold-g/Qii;
401 if(anew<0.0) anew=0.0; else if(anew>U) anew=U;
402 const REALTYPE step=(anew-aold)*yi;
403 _alpha[i]=anew;
404 if(step!=0.0)
405 {
406 const REALTYPE *row=kernel_row(i,N);
407 for(std::size_t k=0;k<N;k++) _s[k]+=step*row[k];
408 }
409 }
410 }
411 if(pg_max<_tol) break;
412 }
413 for(std::size_t i=0;i<N;i++) beta[i]=_alpha[i]*((_y[i]==positive_class)?(REALTYPE)1.0:(REALTYPE)-1.0);
414}
415
416template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
418{
419 notify("Classifier_RBF_SVM::train().");
420 assert(da);
421 assert(sub);
422 assert(_classes==da->getNoOfClasses());
423 assert(_features==da->getNoOfFeatures());
424 assert(sub->get_n_raw()==da->getNoOfFeatures());
425
426 // buffer the feature subset index
427 _subfeatures=0;
428 for(DIMTYPE fsel : sub->selected_features()) {assert(_subfeatures<_features); _index[_subfeatures++]=fsel;}
429 assert(_subfeatures==sub->get_d_raw());
430 assert(_subfeatures>0);
431 const std::size_t d=_subfeatures;
432
433 // pass 1 + standardize via the shared helper (dense_train_tools.hpp); no bias
434 // coordinate here (the penalized-bias kernel offset supplies it), label rides along
435 _y.clear();
437 [this](const auto *pat, const DIMTYPE c){(void)pat; _y.push_back(c);});
438 if(N==0) return false;
439
440 _gamma_eff=(_gamma>0.0)?_gamma:(REALTYPE)1.0/(REALTYPE)d;
441
442 // kernel matrix, shared by all one-vs-rest models; above budget rows are recomputed on demand
443 if(N*N<=KERNEL_BUDGET_ENTRIES)
444 {
445 _K.resize(N*N);
446 for(std::size_t a=0;a<N;a++)
447 {
448 _K[a*N+a]=(REALTYPE)2.0;
449 for(std::size_t b=a+1;b<N;b++) _K[a*N+b]=_K[b*N+a]=kernel_value(&_Z[a*d],&_Z[b*d]);
450 }
451 _krow.clear();
452 }
453 else {_K.clear(); _krow.resize(N);}
454
455 // one-vs-rest models (two-class data: the single model's +1 side is class index 0)
456 const DIMTYPE M=model_count();
457 _beta_full.assign((std::size_t)M*N,0.0);
458 for(DIMTYPE m=0;m<M;m++) solve_dual(&_beta_full[(std::size_t)m*N],m);
459
460 // compact to support vectors: keep samples with a nonzero coefficient in ANY model
461 _sv_count=0;
462 _sv.clear(); _beta.clear();
463 std::vector<std::size_t> keep;
464 for(std::size_t n=0;n<N;n++)
465 {
466 bool used=false;
467 for(DIMTYPE m=0;m<M && !used;m++) if(_beta_full[(std::size_t)m*N+n]!=0.0) used=true;
468 if(used) keep.push_back(n);
469 }
470 _sv_count=(IDXTYPE)keep.size();
471 _sv.resize(keep.size()*d);
472 _beta.resize((std::size_t)M*keep.size());
473 for(std::size_t k=0;k<keep.size();k++)
474 {
475 for(std::size_t f=0;f<d;f++) _sv[k*d+f]=_Z[keep[k]*d+f];
476 for(DIMTYPE m=0;m<M;m++) _beta[(std::size_t)m*keep.size()+k]=_beta_full[(std::size_t)m*N+keep[k]];
477 }
478 return true;
479}
480
481template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
483{
484 assert(_subfeatures>0); // train() must have succeeded
485 const std::size_t d=_subfeatures, nsv=_sv_count;
486 scores.resize(_classes);
487 // standardize the pattern, then evaluate the kernel against each support vector ONCE (shared by all models)
488 _cs_x.resize(d); _cs_kv.resize(nsv);
489 for(std::size_t f=0;f<d;f++) _cs_x[f]=((REALTYPE)pattern[_index[f]]-_mean[f])/_scale[f];
490 for(std::size_t k=0;k<nsv;k++) _cs_kv[k]=kernel_value(&_sv[k*d],_cs_x.data());
491 const DIMTYPE M=model_count();
492 for(DIMTYPE m=0;m<M;m++)
493 {
494 const REALTYPE *b=&_beta[(std::size_t)m*nsv];
495 REALTYPE dec=0.0; // the intercept lives inside the +1 kernel offset
496 for(std::size_t k=0;k<nsv;k++) dec+=b[k]*_cs_kv[k];
497 scores[m]=(RETURNTYPE)dec;
498 }
499 if(_classes==2) scores[1]=-scores[0]; // the single binary model scores both sides
500 return true;
501}
502
503template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
505{
506 if(!classify_scores(_cs_sc,pattern)) return false;
507 cls=0;
508 for(DIMTYPE c=1;c<_classes;c++) if(_cs_sc[c]>_cs_sc[cls]) cls=c; // first maximum wins
509 return true;
510}
511
512
513} // namespace
514#endif // FSTCLASSIFIERRBFSVM_H ///:~
Dependency-free RBF kernel SVM trained by kernel dual coordinate descent (implemented from scratch,...
Definition classifier_rbf_svm.hpp:128
std::vector< REALTYPE > _beta
models x sv_count dual coefficients alpha_i*y_i; two-class data holds ONE model
Definition classifier_rbf_svm.hpp:214
void solve_dual(REALTYPE *beta, const DIMTYPE positive_class)
One one-vs-rest kernel dual coordinate-descent run: patterns of class positive_class are the +1 side,...
Definition classifier_rbf_svm.hpp:372
std::vector< REALTYPE > _sv
sv_count x d standardized support-vector values
Definition classifier_rbf_svm.hpp:213
void initialize(const PDataAccessor da)
records data shape, allocates the index buffer
Definition classifier_rbf_svm.hpp:265
DIMTYPE _classes
class count, set by initialize()
Definition classifier_rbf_svm.hpp:205
bool mean_cv_accuracy(const PDataAccessor da, const PSubset sub, RETURNTYPE &mean)
train+test over the accessor's split loop (optimize_parameters' evaluation)
Definition classifier_rbf_svm.hpp:278
Clonable_Impl< Classifier_RBF_SVM, parent > parent_impl
implements clone() via the (implicit, member-wise) copy-constructor – all members are value-semantic
Definition classifier_rbf_svm.hpp:131
void set_l2_loss(const bool l2)
false = hinge (C-SVC correspondence, default), true = squared hinge
Definition classifier_rbf_svm.hpp:141
DIMTYPE _subfeatures
d = current subset size
Definition classifier_rbf_svm.hpp:207
std::vector< REALTYPE > _scale
standardization scale per subset position (1 for constant features)
Definition classifier_rbf_svm.hpp:210
static constexpr std::size_t KERNEL_BUDGET_ENTRIES
kernel-matrix memory budget in entries (512 MB of double); above it rows are recomputed on demand
Definition classifier_rbf_svm.hpp:229
std::vector< REALTYPE > _beta_full
models x N pre-compaction dual coefficients (solve_dual() output before the support-vector compaction...
Definition classifier_rbf_svm.hpp:226
REALTYPE get_parameter_C() const
returns the configured C
Definition classifier_rbf_svm.hpp:144
REALTYPE _C
regularization parameter, see set_parameter_C()
Definition classifier_rbf_svm.hpp:198
bool optimize_parameters(const PDataAccessor da, const PSubset sub, const int max_points=100, const int max_throws=100, const double lgC_min=-5, const double lgC_max=9, const double lggamma_min=-15, const double lggamma_max=3, std::ostream &os=std::cout)
Definition classifier_rbf_svm.hpp:292
REALTYPE kernel_value(const REALTYPE *a, const REALTYPE *b) const
The penalized-bias RBF kernel K'(a,b) = exp(-gamma_eff*||a-b||^2) + 1 over the current _subfeatures s...
Definition classifier_rbf_svm.hpp:235
bool _l2loss
false = hinge loss (default), true = squared hinge
Definition classifier_rbf_svm.hpp:200
DATAACCESSOR::PPattern PPattern
one data sample as exposed by DATAACCESSOR
Definition classifier_rbf_svm.hpp:134
std::vector< DIMTYPE > _index
subset position -> raw feature index (first d entries valid)
Definition classifier_rbf_svm.hpp:208
std::vector< REALTYPE > _cs_x
classify_scores() per-pattern scratch: the standardized query pattern (kept as a member to avoid per-...
Definition classifier_rbf_svm.hpp:223
virtual bool classify(DIMTYPE &cls, const PPattern &pattern) override
Definition classifier_rbf_svm.hpp:504
std::shared_ptr< DATAACCESSOR > PDataAccessor
shared pointer to the data accessor supplying train/test blocks
Definition classifier_rbf_svm.hpp:132
std::vector< RETURNTYPE > _cs_sc
classify() score scratch
Definition classifier_rbf_svm.hpp:225
DIMTYPE _features
raw (full, unnarrowed) feature count, set by initialize()
Definition classifier_rbf_svm.hpp:206
REALTYPE _tol
max |projected gradient| sweep-stopping threshold
Definition classifier_rbf_svm.hpp:202
virtual bool train(const PDataAccessor da, const PSubset sub) override
Trains the RBF-kernel SVM: buffers the subset index, standardizes the design (dense_train_tools....
Definition classifier_rbf_svm.hpp:417
void set_tolerance(const REALTYPE t)
max |projected gradient| sweep-stopping threshold; default 0.1
Definition classifier_rbf_svm.hpp:143
virtual std::ostream & print(std::ostream &os) const override
writes a human-readable identification of the object; base default writes nothing
Definition classifier_rbf_svm.hpp:189
std::vector< REALTYPE > _K
N x N kernel matrix K' (only when within budget, else empty – see KERNEL_BUDGET_ENTRIES).
Definition classifier_rbf_svm.hpp:221
unsigned int _max_iter
cap on full coordinate sweeps in solve_dual()
Definition classifier_rbf_svm.hpp:201
const REALTYPE * kernel_row(const std::size_t i, const std::size_t N)
Row i of the N x N kernel matrix over the N training patterns in _Z. When _K was precomputed (the wit...
Definition classifier_rbf_svm.hpp:246
std::vector< REALTYPE > _mean
standardization shift per subset position
Definition classifier_rbf_svm.hpp:209
REALTYPE _gamma_eff
gamma actually used by the trained model (resolves _gamma's 0=auto to 1/d)
Definition classifier_rbf_svm.hpp:211
std::vector< REALTYPE > _alpha
N dual variables of the model currently being trained (solve_dual() scratch).
Definition classifier_rbf_svm.hpp:219
std::vector< REALTYPE > _krow
kernel-row scratch for the above-budget mode (filled by kernel_row())
Definition classifier_rbf_svm.hpp:222
std::shared_ptr< SUBSET > PSubset
shared pointer to the feature subset being trained/evaluated
Definition classifier_rbf_svm.hpp:133
std::vector< REALTYPE > _cs_kv
classify_scores() per-pattern scratch: kernel value against each support vector
Definition classifier_rbf_svm.hpp:224
void set_parameter_gamma(const REALTYPE g)
RBF width on standardized features; 0 = auto (1/d), which is the default.
Definition classifier_rbf_svm.hpp:140
DIMTYPE model_count() const
number of one-vs-rest models actually trained: 1 for two-class data (the single model scores both sid...
Definition classifier_rbf_svm.hpp:261
void set_parameter_C(const REALTYPE c)
sets the SVM regularization parameter C (box constraint upper bound U under L1-loss); default 1
Definition classifier_rbf_svm.hpp:139
std::vector< REALTYPE > _s
N maintained margin sums s_k = sum_j alpha_j y_j K'_jk.
Definition classifier_rbf_svm.hpp:220
std::vector< REALTYPE > _Z
N x d standardized design (no bias coordinate — the +1 kernel offset carries it).
Definition classifier_rbf_svm.hpp:217
void set_max_iter(const unsigned int mi)
cap on full coordinate sweeps; default 1000
Definition classifier_rbf_svm.hpp:142
std::vector< DIMTYPE > _y
N training labels.
Definition classifier_rbf_svm.hpp:218
Classifier< RETURNTYPE, DIMTYPE, SUBSET, DATAACCESSOR > parent
the immediate abstract base
Definition classifier_rbf_svm.hpp:130
IDXTYPE _sv_count
support vectors kept (nonzero dual coefficient in ANY model)
Definition classifier_rbf_svm.hpp:212
virtual bool classify_scores(std::vector< RETURNTYPE > &scores, const PPattern &pattern) override
Definition classifier_rbf_svm.hpp:482
REALTYPE _gamma
configured RBF gamma; 0 = auto: 1/d per train() (the effective value actually used is _gamma_eff)
Definition classifier_rbf_svm.hpp:199
REALTYPE get_parameter_gamma() const
the configured value (0 = auto 1/d until set explicitly)
Definition classifier_rbf_svm.hpp:145
abstract class, defines interface for classifier implementations (mainly to be used in wrappers)
Definition classifier.hpp:97
virtual bool test(RETURNTYPE &result, const PDataAccessor da)
Definition classifier.hpp:153
CRTP mixin implementing the Clonable protocol for a concrete class.
Definition clonable.hpp:184
FST4 specific error passing class.
Definition error.hpp:61
static void print(std::ostream &os, std::ostringstream &sos)
Writes sos's buffered content to os, serializing concurrent writers under FST_THREADED via a shared m...
Definition global.hpp:86
Defines interface for classifier implementations.
Defines interface for classes that may need to get cloned.
Shared dense-training helpers: standardized-design build and Cholesky factor/solve.
FST4 specific error passing class.
FST4-owned pseudo-random number generator (UCRT-compatible LCG), replacing platform-specific std::ran...
Global definitions.
The Feature Selection Toolbox 4 library: every library component – data access, criteria and classifi...
Definition data_accessor.hpp:80
int fst_rand()
Returns the next pseudo-random draw in 0..FST_RAND_MAX; use instead of std::rand().
Definition fst_rand.hpp:93
const int FST_RAND_MAX
Maximum value fst_rand() can return; use instead of the libc macro RAND_MAX.
Definition fst_rand.hpp:101
void notify(const std::string msg)
Prints msg followed by a newline via syncout::print(); a no-op unless the preprocessor macro DEBUG is...
Definition global.hpp:112
std::size_t standardize_design(const std::shared_ptr< DATAACCESSOR > &da, const DIMTYPE classes, const std::size_t d, const std::size_t zstride, const std::vector< DIMTYPE > &index, std::vector< REALTYPE > &Z, std::vector< REALTYPE > &mean, std::vector< REALTYPE > &scale, AFTERPATTERN after_pattern)
Definition dense_train_tools.hpp:84
Copyright © 2000–present ÚTIA, Institute of Information Theory and Automation of the Czech Academy of Sciences · Contacts · This site sets no cookies and uses no analytics.