source: trunk/yat/classifier/EnsembleBuilder.h @ 1221

Last change on this file since 1221 was 1221, checked in by Peter, 13 years ago

writing size_t directly rather than vector<>::size_type

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date ID
File size: 7.2 KB
Line 
1#ifndef _theplu_yat_classifier_ensemblebuilder_
2#define _theplu_yat_classifier_ensemblebuilder_
3
4// $Id$
5
6/*
7  Copyright (C) 2005 Markus Ringnér
8  Copyright (C) 2006 Jari Häkkinen, Markus Ringnér, Peter Johansson
9  Copyright (C) 2007, 2008 Peter Johansson
10
11  This file is part of the yat library, http://trac.thep.lu.se/yat
12
13  The yat library is free software; you can redistribute it and/or
14  modify it under the terms of the GNU General Public License as
15  published by the Free Software Foundation; either version 2 of the
16  License, or (at your option) any later version.
17
18  The yat library is distributed in the hope that it will be useful,
19  but WITHOUT ANY WARRANTY; without even the implied warranty of
20  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21  General Public License for more details.
22
23  You should have received a copy of the GNU General Public License
24  along with this program; if not, write to the Free Software
25  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26  02111-1307, USA.
27*/
28
29#include "FeatureSelector.h"
30#include "Sampler.h"
31#include "SubsetGenerator.h"
32#include "yat/statistics/Averager.h"
33#include "yat/utility/Matrix.h"
34
35#include <vector>
36
37namespace theplu {
38namespace yat {
39namespace classifier { 
40
41  ///
42  /// @brief Class for ensembles of supervised classifiers
43  ///
44  template <class Classifier, class Data>
45  class EnsembleBuilder
46  {
47  public:
48    /**
49       \brief Type of classifier that ensemble is built on.
50     */
51    typedef Classifier classifier_type;
52
53    /**
54       Type of container used for storing data. Must be MatrixLookup,
55       MatrixLookupWeighted, or KernelLookup
56     */
57    typedef Data data_type;
58
59    ///
60    /// Constructor.
61    ///
62    EnsembleBuilder(const Classifier&, const Data&, const Sampler&);
63
64    ///
65    /// Constructor.
66    ///
67    EnsembleBuilder(const Classifier&, const Data&, const Sampler&, 
68                    FeatureSelector&);
69
70    ///
71    /// Destructor.
72    ///
73    virtual ~EnsembleBuilder(void);
74
75    ///
76    /// Generate ensemble. Function trains each member of the Ensemble.
77    ///
78    void build(void);
79
80    ///
81    /// @return classifier
82    ///
83    const Classifier& classifier(size_t i) const;
84     
85    ///
86    /// @return Number of classifiers in ensemble
87    ///
88    u_long size(void) const;
89
90    ///
91    /// @brief Generate validation data for ensemble
92    ///
93    /// validate()[i][j] return averager for class @a i for sample @a j
94    ///
95    const std::vector<std::vector<statistics::Averager> >& validate(void);
96   
97    /**
98       Predict a dataset using the ensemble.
99       
100       If @a data is a KernelLookup each column should correspond to a
101       test sample and each row should correspond to a training
102       sample. More exactly row \f$ i \f$ in @a data should correspond
103       to the same sample as row/column \f$ i \f$ in the training
104       kernel corresponds to.
105    */
106    void predict(const Data& data, 
107                 std::vector<std::vector<statistics::Averager> > &);
108
109  private:
110    // no copying
111    EnsembleBuilder(const EnsembleBuilder&);
112    const EnsembleBuilder& operator=(const EnsembleBuilder&);
113   
114
115    const Classifier& mother_;
116    SubsetGenerator<Data>* subset_;
117    std::vector<Classifier*> classifier_;
118    KernelLookup test_data(const KernelLookup&, size_t k);
119    MatrixLookup test_data(const MatrixLookup&, size_t k);
120    MatrixLookupWeighted test_data(const MatrixLookupWeighted&, size_t k);
121    std::vector<std::vector<statistics::Averager> > validation_result_;
122
123  };
124 
125
126  // implementation
127
128  template <class C, class D> 
129  EnsembleBuilder<C,D>::EnsembleBuilder(const C& sc, const D& data,
130                                        const Sampler& sampler) 
131    : mother_(sc),subset_(new SubsetGenerator<D>(sampler,data))
132  {
133  }
134
135
136  template <class C, class D> 
137  EnsembleBuilder<C, D>::EnsembleBuilder(const C& sc, const D& data, 
138                                         const Sampler& sampler,
139                                         FeatureSelector& fs) 
140    : mother_(sc),
141      subset_(new SubsetGenerator<D>(sampler,data,fs))
142  {
143  }
144
145
146  template <class C, class D> 
147  EnsembleBuilder<C, D>::~EnsembleBuilder(void) 
148  {
149    for(size_t i=0; i<classifier_.size(); i++)
150      delete classifier_[i];
151    delete subset_;
152  }
153
154
155  template <class C, class D> 
156  void EnsembleBuilder<C, D>::build(void) 
157  {
158    for(u_long i=0; i<subset_->size();++i) {
159      C* classifier = mother_.make_classifier();
160      classifier->train(subset_->training_data(i), 
161                        subset_->training_target(i));
162      classifier_.push_back(classifier);
163    }   
164  }
165
166
167  template <class C, class D> 
168  const C& EnsembleBuilder<C, D>::classifier(size_t i) const
169  {
170    return *(classifier_[i]);
171  }
172
173
174  template <class C, class D> 
175  void EnsembleBuilder<C, D>::predict
176  (const D& data, std::vector<std::vector<statistics::Averager> >& result)
177  {
178    result.clear();
179    result.reserve(subset_->target().nof_classes());   
180    for(size_t i=0; i<subset_->target().nof_classes();i++)
181      result.push_back(std::vector<statistics::Averager>(data.columns()));
182   
183    utility::Matrix prediction; 
184
185    for(u_long k=0;k<subset_->size();++k) {       
186      D sub_data =  test_data(data, k);
187      classifier(k).predict(sub_data,prediction);
188    }
189
190    for(size_t i=0; i<prediction.rows();i++) 
191      for(size_t j=0; j<prediction.columns();j++) 
192        result[i][j].add(prediction(i,j));   
193  }
194
195 
196  template <class C, class D> 
197  u_long EnsembleBuilder<C, D>::size(void) const
198  {
199    return classifier_.size();
200  }
201
202
203  template <class C, class D> 
204  MatrixLookup EnsembleBuilder<C, D>::test_data(const MatrixLookup& data, 
205                                                size_t k)
206  {
207    return MatrixLookup(data, subset_->training_features(k), true);
208  }
209 
210
211  template <class C, class D> 
212  MatrixLookupWeighted
213  EnsembleBuilder<C, D>::test_data(const MatrixLookupWeighted& data, size_t k)
214  {
215    return MatrixLookupWeighted(data, subset_->training_features(k), true);
216  }
217 
218
219  template <class C, class D> 
220  KernelLookup
221  EnsembleBuilder<C, D>::test_data(const KernelLookup& kernel, size_t k)
222  {
223    // weighted case
224    if (kernel.weighted()){
225      assert(false);
226      // no feature selection
227      if (kernel.data_weighted().rows()==subset_->training_features(k).size())
228        return KernelLookup(kernel, subset_->training_index(k), true);
229      MatrixLookupWeighted mlw = test_data(kernel.data_weighted(), k);
230      return subset_->training_data(k).test_kernel(mlw);
231
232    }
233    // unweighted case
234
235    // no feature selection
236    if (kernel.data().rows()==subset_->training_features(k).size())
237      return KernelLookup(kernel, subset_->training_index(k), true);
238   
239    // feature selection
240    return subset_->training_data(k).test_kernel(test_data(kernel.data(),k));
241  }
242 
243
244  template <class C, class D> 
245  const std::vector<std::vector<statistics::Averager> >& 
246  EnsembleBuilder<C, D>::validate(void)
247  {
248    validation_result_.clear();
249
250    validation_result_.reserve(subset_->target().nof_classes());   
251    for(size_t i=0; i<subset_->target().nof_classes();i++)
252      validation_result_.push_back(std::vector<statistics::Averager>(subset_->target().size()));
253   
254    utility::Matrix prediction; 
255    for(u_long k=0;k<subset_->size();k++) {
256      classifier(k).predict(subset_->validation_data(k),prediction);
257     
258      // map results to indices of samples in training + validation data set
259      for(size_t i=0; i<prediction.rows();i++) 
260        for(size_t j=0; j<prediction.columns();j++) {
261          validation_result_[i][subset_->validation_index(k)[j]].
262            add(prediction(i,j));
263        }           
264    }
265    return validation_result_;
266  }
267
268}}} // of namespace classifier, yat, and theplu
269
270#endif
Note: See TracBrowser for help on using the repository browser.