Feature Selection Toolbox FST4
UTIA · Czech Academy of Sciences
Loading...
Searching...
No Matches
search_ranking.hpp
Go to the documentation of this file.
1#ifndef FSTSEARCHRANKING_H
2#define FSTSEARCHRANKING_H
3 /*
27=========================================================================
28Copyright and license:
29 * FST4 software (with the exception of any bundled or externally linked
30 third-party components) is Copyright (C) 2000-present Institute of
31 Information Theory and Automation of the Czech Academy of Sciences (UTIA).
32 * FST4 is free software: you can redistribute it and/or modify it under
33 the terms of the GNU Affero General Public License as published by the
34 Free Software Foundation, version 3. The full text of the license is in
35 the file LICENSE in the distribution root and at
36 https://www.gnu.org/licenses/agpl-3.0.html.
37 * FST4 is distributed in the hope that it will be useful, but WITHOUT ANY
38 WARRANTY; without even the implied warranty of MERCHANTABILITY or
39 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
40 License for more details.
41 * Closed-source use without the AGPL's copyleft obligations requires a
42 commercial license from UTIA; in case of interest write to
43 utia@utia.cas.cz. LICENSING.md in the distribution root explains both
44 options, the contributor license agreement that every contribution
45 requires, and the contacts (technical questions and pull requests:
46 somol@utia.cas.cz, with "FST" in the subject line).
47========================================================================== */
48
49#include <memory>
50#include <cassert>
51#ifdef FST_THREADED
52#include <mutex>
53#endif
54#include <iostream>
55#include <sstream>
56#include <list>
57#include "error.hpp"
58#include "global.hpp"
59#include "stopwatch.hpp"
60#include "search.hpp"
63
64/*============== Template parameter type naming conventions ==============
65--------- Numeric types: -------------------------------------------------
66DATATYPE - data sample values - usually real numbers (but may be integers
67 in text processing etc.)
68REALTYPE - must be real numbers - for representing intermediate results of
69 calculations like mean, covariance etc.
70IDXTYPE - index values for enumeration of data samples - (nonnegative) integers,
71 extent depends on numbers of samples in data
72DIMTYPE - index values for enumeration of features (dimensions), or classes (not
73 class sizes) - (nonnegative) integers, usually lower extent than IDXTYPE,
74 but be aware of expressions like _classes*_features*_features !
75 in linearized representations of feature matrices for all classes
76BINTYPE - feature selection marker type - represents ca. <10 different feature
77 states (selected, deselected, sel./desel. temporarily 1st nested loop, 2nd...)
78RETURNTYPE - criterion value: real value, but may be extended in future to support
79 multiple values
80--------- Class types: ---------------------------------------------------
81SUBSET - class of class type Subset
82CLASSIFIER - class implementing interface defined in abstract class Classifier
83EVALUATOR - class implementing interface defined in abstract class Sequential_Step
84DISTANCE - class implementing interface defined in abstract class Distance
85DATAACCESSOR - class implementing interface defined in abstract class Data_Accessor
86INTERVALCONTAINER - class of class type Data_Intervaller
87CONTAINER - STL container of class type Data_Interval
88========================================================================== */
89
90namespace FST {
91
112template<class RETURNTYPE, typename DIMTYPE, class SUBSET, class CRITERION>
113class Search_Ranking : public Search<RETURNTYPE,DIMTYPE,SUBSET,CRITERION>{
114public:
115 typedef Search<RETURNTYPE,DIMTYPE,SUBSET,CRITERION> parent;
116 typedef std::shared_ptr<CRITERION> PCriterion;
117 typedef std::shared_ptr<SUBSET> PSubset;
119 typedef std::shared_ptr<EVALUATORENGINE> PEvaluatorEngine;
121 explicit Search_Ranking(PEvaluatorEngine engine=PEvaluatorEngine()):Search<RETURNTYPE,DIMTYPE,SUBSET,CRITERION>(),_engine(engine) {
123 notify("Search_Ranking constructor.");
124 }
125 virtual ~Search_Ranking() {notify("Search_Ranking destructor.");}
126
127 // creates FEATURELIST, must be called before get*Feature() and search()
128 virtual bool evaluate_individuals(const DIMTYPE n, const PCriterion crit, std::ostream& os=std::cout) = 0;
129
130 // NOTE: crit is expected to be already initialize()d before use here
132 virtual bool search(const DIMTYPE target_d, RETURNTYPE &result, const PSubset sub, const PCriterion crit, std::ostream& os=std::cout) override;
133
134 bool getFirstFeature(RETURNTYPE &value, DIMTYPE &feature) const;
135 bool getNextFeature(RETURNTYPE &value, DIMTYPE &feature) const;
136
137 virtual std::ostream& print(std::ostream& os) const override {os << "Search_Ranking() abstract class"; return os;};
138protected:
141 typedef struct {
142 DIMTYPE feature;
143 RETURNTYPE critval;
144 } OneFeature;
145 typedef std::list<OneFeature> FEATURELIST;
147private:
148 mutable typename FEATURELIST::const_iterator get_iter;
149#ifdef FST_THREADED
150 mutable std::mutex get_iter_mutex;
151#endif
152};
153
154template<class RETURNTYPE, typename DIMTYPE, class SUBSET, class CRITERION>
155bool Search_Ranking<RETURNTYPE,DIMTYPE,SUBSET,CRITERION>::getFirstFeature(RETURNTYPE &value, DIMTYPE &feature) const
156{
157#ifdef FST_THREADED
158 std::unique_lock<std::mutex> lock(get_iter_mutex);
159#endif
160 get_iter = bifs.begin();
161 if(get_iter!=bifs.end()) {
162 value=(*get_iter).critval;
163 feature=(*get_iter).feature;
164 get_iter++;
165 return true;
166 } else return false;
167}
168
169template<class RETURNTYPE, typename DIMTYPE, class SUBSET, class CRITERION>
170bool Search_Ranking<RETURNTYPE,DIMTYPE,SUBSET,CRITERION>::getNextFeature(RETURNTYPE &value, DIMTYPE &feature) const
171{
172#ifdef FST_THREADED
173 std::unique_lock<std::mutex> lock(get_iter_mutex);
174#endif
175 if(get_iter!=bifs.end()) {
176 value=(*get_iter).critval;
177 feature=(*get_iter).feature;
178 get_iter++;
179 return true;
180 } else return false;
181}
182
183template<class RETURNTYPE, typename DIMTYPE, class SUBSET, class CRITERION>
184bool Search_Ranking<RETURNTYPE,DIMTYPE,SUBSET,CRITERION>::search(const DIMTYPE target_d, RETURNTYPE &result, const PSubset sub, const PCriterion crit, std::ostream& os) // returns found subset + criterion value
185{
186 StopWatch swatch;
187 notify("Search_Ranking::search().");
188 bool track=parent::result_tracker_active(); if(track) parent::_tracker->set_output_detail(parent::get_output_detail());
189 assert(sub);
190 assert(crit);
191 assert(sub->get_n()>0);
192 assert(target_d<sub->get_n());
193 DIMTYPE _n=sub->get_n();
194
196 msgbuf sos;
197 sos << "---------------------------------------" << std::endl;
198 sos << "Starting " << *this << std::endl;
199 sos << "with Criterion: " << *crit << std::endl;
200 if(target_d==0) sos << "Subset size to be optimized." << std::endl; else sos << "Target subset size set to: " << target_d << std::endl;
201 sos << std::endl << std::flush;
202 this->report(os,sos);
203 }
204
205 if(!evaluate_individuals(_n,crit,os)) return false;
206
207 std::shared_ptr<SUBSET> tempsub(new SUBSET(_n));
208 typename FEATURELIST::const_iterator iter;
209 DIMTYPE i;
210 if(target_d>0) { // return subset of size target_d
211 sub->deselect_all();
212 for(iter=bifs.begin(),i=0; iter!=bifs.end() && i<target_d; iter++,i++) sub->select((*iter).feature);
213 if(!crit->evaluate(result,sub)) return false;
214 if(track) parent::_tracker->add(result,sub);
215 }
216 else { // find best dimensionality
217 tempsub->deselect_all();
218 sub->deselect_all();
219 assert(bifs.begin()!=bifs.end());
220 assert(_engine);
221
222 // per-candidate work: track, keep best, report progress - fired in
223 // candidate (i.e., growing-subset-size) order by either engine; the
224 // sequential one fires it interleaved with the evaluations themselves
225 bool first=true;
226 RETURNTYPE best=RETURNTYPE();
227 typename EVALUATORENGINE::ResultCallback on_result=[&](const RETURNTYPE cval, const PSubset &csub, const DIMTYPE) {
228 if(track) parent::_tracker->add(cval,csub);
229 if(first || cval>best) {
230 best=cval;
231 sub->stateless_copy(*csub);
232 first=false;
233 if(parent::output_normal()) this->report_solution(os, cval, *csub, msgbuf() << "new best result="<<cval<<", " << *csub << std::endl << std::endl << std::flush);
234 } else {
235 if(parent::output_normal()) this->report_solution(os, cval, *csub, msgbuf() << "result="<<cval<<", " << *csub << std::endl << std::endl << std::flush);
236 }
237 };
238 _engine->initialize(crit, _n, on_result);
239 for(iter=bifs.begin(); iter!=bifs.end(); iter++) {
240 tempsub->select((*iter).feature);
241 if(!_engine->add_candidate(tempsub)) return false;
242 }
243 if(!_engine->collect()) return false;
244 result=best;
245 }
247 msgbuf sos;
248 sos << "......................................." << std::endl;
249 sos << *this << " search finished. " << swatch << std::endl;
250 sos << "Search result: "<< std::endl << *sub << std::endl << "Criterion value: " << result << std::endl << std::endl << std::flush;
251 this->report(os,sos);
252 }
253 return true;
254}
255
256
257} // namespace
258#endif // FSTSEARCHRANKING_H ///:~
Abstract candidate-evaluation strategy: the seam through which one search algorithm body evaluates ca...
Implements sequential in-line evaluation of a criterion on a set of subset candidates.
Implements sequential in-line evaluation of a criterion on a set of subset candidates.
Definition candidate_evaluator_sequential.hpp:62
Abstract candidate-evaluation strategy (sequential-inline vs. thread-pooled).
Definition candidate_evaluator.hpp:86
std::function< void(const RETURNTYPE, const PSubset &, const DIMTYPE)> ResultCallback
fired once per evaluated batch candidate: (criterion value, candidate, feature tag as passed to add_c...
Definition candidate_evaluator.hpp:94
Abstract base of the feature-ranking methods: scores features one by one, then turns the ranking into...
Definition search_ranking.hpp:113
virtual std::ostream & print(std::ostream &os) const override
writes a human-readable identification of the search and its configuration; base default writes nothi...
Definition search_ranking.hpp:137
FEATURELIST bifs
the individual-feature ranking; empty until evaluate_individuals() is called
Definition search_ranking.hpp:146
Search< RETURNTYPE, DIMTYPE, SUBSET, CRITERION > parent
the abstract Search interface this class implements
Definition search_ranking.hpp:115
std::mutex get_iter_mutex
protects get_iter for thread-safe iteration
Definition search_ranking.hpp:150
bool getFirstFeature(RETURNTYPE &value, DIMTYPE &feature) const
iterator over bifs (the ranking built by evaluate_individuals()), highest-ranked feature first; retur...
Definition search_ranking.hpp:155
PEvaluatorEngine _engine
Definition search_ranking.hpp:139
std::list< OneFeature > FEATURELIST
the individual-feature ranking built by evaluate_individuals(), sorted descending by critval
Definition search_ranking.hpp:145
Search_Ranking(PEvaluatorEngine engine=PEvaluatorEngine())
Definition search_ranking.hpp:121
std::shared_ptr< CRITERION > PCriterion
shared pointer to the criterion the search optimizes
Definition search_ranking.hpp:116
std::shared_ptr< SUBSET > PSubset
shared pointer to a feature subset
Definition search_ranking.hpp:117
virtual bool evaluate_individuals(const DIMTYPE n, const PCriterion crit, std::ostream &os=std::cout)=0
ranks all n features individually by crit, filling bifs descending by criterion value (the order with...
Candidate_Evaluator< RETURNTYPE, DIMTYPE, SUBSET, CRITERION > EVALUATORENGINE
the injected candidate-evaluation engine interface driving individual-feature evaluation
Definition search_ranking.hpp:118
FEATURELIST::const_iterator get_iter
iteration cursor for getFirstFeature()/getNextFeature() (single shared cursor; see get_iter_mutex und...
Definition search_ranking.hpp:148
std::shared_ptr< EVALUATORENGINE > PEvaluatorEngine
Definition search_ranking.hpp:119
virtual bool search(const DIMTYPE target_d, RETURNTYPE &result, const PSubset sub, const PCriterion crit, std::ostream &os=std::cout) override
ranks the features (evaluate_individuals()) and returns the target_d best-ranked ones,...
Definition search_ranking.hpp:184
bool getNextFeature(RETURNTYPE &value, DIMTYPE &feature) const
continues the getFirstFeature() iteration; returns false once the ranking is exhausted....
Definition search_ranking.hpp:170
bool output_normal() const
true unless output detail is SILENT
Definition search.hpp:159
void report(std::ostream &os, const msgbuf &m) const
delivers one pre-formatted progress message: to the observer if attached, otherwise as syncout text t...
Definition search.hpp:170
bool result_tracker_active() const
true if a result tracker was assigned via enable_result_tracking() and not since disabled
Definition search.hpp:155
OutputDetail get_output_detail() const
the currently configured output detail level
Definition search.hpp:158
PResultTracker _tracker
the assigned result tracker, or null (see enable_result_tracking()/result_tracker_active())
Definition search.hpp:179
void report_solution(std::ostream &os, const RETURNTYPE value, const SUBSET &sub, const msgbuf &m) const
like report(), for sites announcing a new (sub-)solution; fires on_solution instead
Definition search.hpp:175
Simple stopwatch to measure run time of search algorithms.
Definition stopwatch.hpp:92
Message accumulator for Search::report() - collects one progress message exactly as an std::ostringst...
Definition search.hpp:87
FST4 specific error passing class.
Global definitions.
The Feature Selection Toolbox 4 library: every library component – data access, criteria and classifi...
Definition data_accessor.hpp:80
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
Defines interface for search method implementations.
Simple tool to measure run time.
Structure to hold [feature,criterion value] pair while ranking features.
Definition search_ranking.hpp:141
RETURNTYPE critval
the feature's individual criterion value, as evaluated by evaluate_individuals()
Definition search_ranking.hpp:143
DIMTYPE feature
the feature's index
Definition search_ranking.hpp:142
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.