Feature Selection Toolbox FST4
UTIA · Czech Academy of Sciences
Loading...
Searching...
No Matches
criterion_multinom_bhattacharyya.hpp
Go to the documentation of this file.
1#ifndef FSTCRITERIONMULTINOMBHATTACHARYYA_H
2#define FSTCRITERIONMULTINOMBHATTACHARYYA_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#include <iostream>
52#include <sstream>
53#include <cmath>
54#include "error.hpp"
55#include "global.hpp"
57#include "model_multinom.hpp"
58
59/*============== Template parameter type naming conventions ==============
60--------- Numeric types: -------------------------------------------------
61DATATYPE - data sample values - usually real numbers (but may be integers
62 in text processing etc.)
63REALTYPE - must be real numbers - for representing intermediate results of
64 calculations like mean, covariance etc.
65IDXTYPE - index values for enumeration of data samples - (nonnegative) integers,
66 extent depends on numbers of samples in data
67DIMTYPE - index values for enumeration of features (dimensions), or classes (not
68 class sizes) - (nonnegative) integers, usually lower extent than IDXTYPE,
69 but be aware of expressions like _classes*_features*_features !
70 in linearized representations of feature matrices for all classes
71BINTYPE - feature selection marker type - represents ca. <10 different feature
72 states (selected, deselected, sel./desel. temporarily 1st nested loop, 2nd...)
73RETURNTYPE - criterion value: real value, but may be extended in future to support
74 multiple values
75--------- Class types: ---------------------------------------------------
76SUBSET - class of class type Subset
77CLASSIFIER - class implementing interface defined in abstract class Classifier
78EVALUATOR - class implementing interface defined in abstract class Sequential_Step
79DISTANCE - class implementing interface defined in abstract class Distance
80DATAACCESSOR - class implementing interface defined in abstract class Data_Accessor
81INTERVALCONTAINER - class of class type Data_Intervaller
82CONTAINER - STL container of class type Data_Interval
83========================================================================== */
84
85namespace FST {
86
99template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
100class Criterion_Multinomial_Bhattacharyya : public Clonable_Impl<Criterion_Multinomial_Bhattacharyya<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>,Criterion_Multinomial<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> > {
101public:
104 typedef std::shared_ptr<DATAACCESSOR> PDataAccessor;
105 typedef std::shared_ptr<SUBSET> PSubset;
106 Criterion_Multinomial_Bhattacharyya() {_IB_computed=false; notify("Criterion_Multinomial_Bhattacharyya constructor.");}
107 virtual ~Criterion_Multinomial_Bhattacharyya() {notify("Criterion_Multinomial_Bhattacharyya destructor.");}
108
110 virtual bool evaluate(RETURNTYPE &result, const PSubset sub) override;
111 virtual bool initialize(PDataAccessor da) override;
112
113
114
115 virtual std::ostream& print(std::ostream& os) const override {os << "Criterion_Multinomial_Bhattacharyya()"; return os;}
116private:
117 friend parent_impl;
119 Criterion_Multinomial_Bhattacharyya(const Criterion_Multinomial_Bhattacharyya& cmb);
120private:
122};
123
124template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
125Criterion_Multinomial_Bhattacharyya<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::Criterion_Multinomial_Bhattacharyya(const Criterion_Multinomial_Bhattacharyya& cmb) :
126 parent_impl(cmb),
128{
129 notify("Criterion_Multinomial_Bhattacharyya copy-constructor.");
130}
131
132
133
134template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
136{
137 notify("Criterion_Multinomial_Bhattacharyya::evaluate().");
138 assert(parent::_model);
139 assert(parent::get_n()>0);
140 assert(sub);
141 if(sub->get_d_raw()==0) return false;
142 DIMTYPE _d = sub->get_d_raw();
143 DIMTYPE f;
144
145 if(_d==1) {// general form of Bhattacharyya unusable, return the individual Bhattacharyya (see the class warning: different scale)
146 if(!_IB_computed) {
147 parent::_model->denarrow();
148 parent::_model->compute_theta();
149 parent::_model->compute_IB();
150 _IB_computed=true;
151 }
152 { // expects a singleton subset: read its single selected feature index
153 auto r=sub->selected_features(); auto it=r.begin();
154 if(!(it!=r.end())) return false;
155 f=*it;
156 }
157 assert(f<parent::_model->get_n());
158 result = parent::_model->get_IB()[f]; // individual Bhatt - higher values denote better terms
159 } else {
160 parent::_model->narrow_to(sub);
161 parent::_model->compute_theta();
162 REALTYPE doc_avg_length = parent::_model->get_doc_avg_length(); // valid after compute_theta() call
163 DIMTYPE _classes=parent::_model->get_classes();
164
165 REALTYPE *tmpoint1, *tmpoint2;
166 RETURNTYPE thetasum;
167 RETURNTYPE value=0.0;
168 DIMTYPE c1,c2;
169 // the DEBUG blocks below trace the per-class-pair accumulation of the Bhattacharyya
170 // coefficient; they are compiled in only in DEBUG builds and print nothing otherwise
171#ifdef DEBUG
172 {
173 std::ostringstream sos; sos << "d="<<_d<<", doc_avg_length="<<doc_avg_length<<std::endl;
174 syncout::print(std::cout,sos);
175 }
176#endif
177 for(c1=0;c1<_classes;c1++) for(c2=c1+1;c2<_classes;c2++) // for class pair c1,c2
178 {
179 tmpoint1=&(parent::_model->get_theta()[c1*_d]);
180 tmpoint2=&(parent::_model->get_theta()[c2*_d]);
181 thetasum=0.0;
182 for(f=0;f<_d;f++)
183 {
184 thetasum+=sqrt(tmpoint1[f]*tmpoint2[f]);
185#ifdef DEBUG
186 {
187 std::ostringstream sos; sos << "classes<"<<c1<<","<<c2<<">: feat "<<f<<".thetasum="<<thetasum<<", tmpoint1[i="<<f<<"]="<< tmpoint1[f]<< ", tmpoint2[i="<<f<<"]="<< tmpoint2[f]<<std::endl;
188 syncout::print(std::cout,sos);
189 }
190#endif
191 }
192 value+= (double)log(thetasum) * parent::_model->get_Pc(c1) * parent::_model->get_Pc(c2); // weighted
193 }
194 result = (-doc_avg_length)*value;
195#ifdef DEBUG
196 {
197 std::ostringstream sos; sos << "result="<<result<<std::endl<<std::endl;
198 syncout::print(std::cout,sos);
199 }
200#endif
201 }
202 return true;
203}
204
205template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
207{
208 notify("Criterion_Multinomial_Bhattacharyya::initialize().");
210 _IB_computed=false;
211 return true;
212}
213
214
215//----------------------------------------------------------------------------
216
223template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
224class Criterion_Multinomial_MI : public Clonable_Impl<Criterion_Multinomial_MI<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>,Criterion_Multinomial<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> > {
225public:
228 typedef std::shared_ptr<DATAACCESSOR> PDataAccessor;
229 typedef std::shared_ptr<SUBSET> PSubset;
230 Criterion_Multinomial_MI() {_MI_computed=false; notify("Criterion_Multinomial_MI constructor.");}
231 virtual ~Criterion_Multinomial_MI() {notify("Criterion_Multinomial_MI destructor.");}
232
234 virtual bool evaluate(RETURNTYPE &result, const PSubset sub) override;
235 virtual bool initialize(PDataAccessor da) override;
236
237 virtual std::ostream& print(std::ostream& os) const override {os << "Criterion_Multinomial_MI()"; return os;}
238private:
239 friend parent_impl;
241 Criterion_Multinomial_MI(const Criterion_Multinomial_MI &cmi) : parent_impl(cmi), _MI_computed(cmi._MI_computed) {notify("Criterion_Multinomial_MI copy-constructor.");}
243};
244
245template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
247{
248 notify("Criterion_Multinomial_MI::evaluate().");
249 assert(parent::_model);
250 assert(parent::get_n()>0);
251 assert(sub);
252 if(sub->get_d_raw()==0) return false;
253
254 if(!_MI_computed) {
255 parent::_model->denarrow();
256 parent::_model->compute_theta();
257 parent::_model->compute_MI();
258 _MI_computed=true;
259 }
260 { // sum of individual MI over the selected features;
261 // on a singleton (the ranking phase) this equals the individual MI itself
262 result=0;
263 bool any=false;
264 for(DIMTYPE f : sub->selected_features()) {
265 assert(f<parent::_model->get_n());
266 result += parent::_model->get_MI()[f]; // individual MI - higher values denote better terms
267 any=true;
268 }
269 if(!any) return false;
270 }
271 return true;
272}
273
274template<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>
276{
277 notify("Criterion_Multinomial_MI::initialize().");
279 _MI_computed=false;
280 return true;
281}
282
283} // namespace
284#endif // FSTCRITERIONMULTINOMBHATTACHARYYA_H ///:~
CRTP mixin implementing the Clonable protocol for a concrete class.
Definition clonable.hpp:184
Implements Bhattacharyya distance based on multinomial model to serve as feature selection criterion.
Definition criterion_multinom_bhattacharyya.hpp:100
virtual bool initialize(PDataAccessor da) override
learns the model (parent::initialize()) and resets the lazily-computed individual-Bhattacharyya cache
Definition criterion_multinom_bhattacharyya.hpp:206
bool _IB_computed
true once the per-feature individual-Bhattacharyya cache (Model_Multinomial::get_IB()) has been compu...
Definition criterion_multinom_bhattacharyya.hpp:121
std::shared_ptr< DATAACCESSOR > PDataAccessor
shared pointer to the data accessor the model is learned from
Definition criterion_multinom_bhattacharyya.hpp:104
Criterion_Multinomial< RETURNTYPE, DATATYPE, REALTYPE, IDXTYPE, DIMTYPE, SUBSET, DATAACCESSOR > parent
base class: the multinomial-model learning/interface skeleton
Definition criterion_multinom_bhattacharyya.hpp:102
Clonable_Impl< Criterion_Multinomial_Bhattacharyya, parent > parent_impl
implements clone(); sharing/stateless_clone throw in Criterion
Definition criterion_multinom_bhattacharyya.hpp:103
virtual std::ostream & print(std::ostream &os) const override
writes a human-readable identification of the object; base default writes nothing
Definition criterion_multinom_bhattacharyya.hpp:115
virtual bool evaluate(RETURNTYPE &result, const PSubset sub) override
Scores sub: the general multinomial Bhattacharyya distance over class pairs, or (on a singleton) the ...
Definition criterion_multinom_bhattacharyya.hpp:135
std::shared_ptr< SUBSET > PSubset
shared pointer to the feature subset being evaluated
Definition criterion_multinom_bhattacharyya.hpp:105
Implements individual Mutual Information based on multinomial model to serve as feature selection cri...
Definition criterion_multinom_bhattacharyya.hpp:224
Criterion_Multinomial< RETURNTYPE, DATATYPE, REALTYPE, IDXTYPE, DIMTYPE, SUBSET, DATAACCESSOR > parent
base class: the multinomial-model learning/interface skeleton
Definition criterion_multinom_bhattacharyya.hpp:226
Clonable_Impl< Criterion_Multinomial_MI, parent > parent_impl
implements clone(); sharing/stateless_clone throw in Criterion
Definition criterion_multinom_bhattacharyya.hpp:227
Criterion_Multinomial_MI(const Criterion_Multinomial_MI &cmi)
Copy-constructor; copies _MI_computed (base _model copied by parent_impl).
Definition criterion_multinom_bhattacharyya.hpp:241
bool _MI_computed
true once the per-feature individual-MI cache (Model_Multinomial::get_MI()) has been computed for the...
Definition criterion_multinom_bhattacharyya.hpp:242
std::shared_ptr< SUBSET > PSubset
shared pointer to the feature subset being evaluated
Definition criterion_multinom_bhattacharyya.hpp:229
virtual bool initialize(PDataAccessor da) override
learns the model (parent::initialize()) and resets the lazily-computed individual-MI cache
Definition criterion_multinom_bhattacharyya.hpp:275
std::shared_ptr< DATAACCESSOR > PDataAccessor
shared pointer to the data accessor the model is learned from
Definition criterion_multinom_bhattacharyya.hpp:228
virtual bool evaluate(RETURNTYPE &result, const PSubset sub) override
Scores sub as the sum of per-feature individual Mutual Information values over its selected features.
Definition criterion_multinom_bhattacharyya.hpp:246
virtual std::ostream & print(std::ostream &os) const override
writes a human-readable identification of the object; base default writes nothing
Definition criterion_multinom_bhattacharyya.hpp:237
Abstract class, defines interface for feature selection criterion implementations based on multinomia...
Definition criterion_multinom.hpp:96
std::unique_ptr< Model_Multinomial< DATATYPE, REALTYPE, IDXTYPE, DIMTYPE, SUBSET, DATAACCESSOR > > _model
the learned per-class multinomial (term-probability) model
Definition criterion_multinom.hpp:121
virtual bool initialize(PDataAccessor da)
learns the multinomial model from da; subclasses must call this base before their own initialize() wo...
Definition criterion_multinom.hpp:139
DIMTYPE get_n() const
the full (raw, unnarrowed) feature count the model was learned for
Definition criterion_multinom.hpp:114
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 feature selection criterion implementations based on multinomial model.
FST4 specific error passing class.
Global definitions.
Implements multinomial model.
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
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.