source: trunk/yat/classifier/NCC.h @ 1042

Last change on this file since 1042 was 1042, checked in by Peter, 14 years ago

fixes #268 - remove return value in SupervisedClassifier::train()

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date ID
File size: 8.5 KB
Line 
1#ifndef _theplu_yat_classifier_ncc_
2#define _theplu_yat_classifier_ncc_
3
4// $Id$
5
6/*
7  Copyright (C) 2005 Markus Ringnér, Peter Johansson
8  Copyright (C) 2006 Jari Häkkinen, Markus Ringnér, Peter Johansson
9  Copyright (C) 2007 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 "DataLookup1D.h"
30#include "DataLookup2D.h"
31#include "DataLookupWeighted1D.h"
32#include "MatrixLookup.h"
33#include "MatrixLookupWeighted.h"
34#include "SupervisedClassifier.h"
35#include "Target.h"
36
37#include "yat/statistics/Averager.h"
38#include "yat/statistics/AveragerWeighted.h"
39#include "yat/statistics/distance.h"
40
41#include "yat/utility/Iterator.h"
42#include "yat/utility/IteratorWeighted.h"
43#include "yat/utility/matrix.h"
44#include "yat/utility/vector.h"
45#include "yat/utility/stl_utility.h"
46#include "yat/utility/yat_assert.h"
47
48#include<iostream>
49#include<iterator>
50#include <map>
51#include <cmath>
52#include <stdexcept>
53
54namespace theplu {
55namespace yat {
56namespace classifier { 
57
58
59  ///
60  /// @brief Class for Nearest Centroid Classification.
61  ///
62
63  template <typename Distance>
64  class NCC : public SupervisedClassifier
65  {
66 
67  public:
68    ///
69    /// Constructor taking the training data and the target vector as
70    /// input
71    ///
72    NCC(const MatrixLookup&, const Target&);
73   
74    ///
75    /// Constructor taking the training data with weights and the
76    /// target vector as input.
77    ///
78    NCC(const MatrixLookupWeighted&, const Target&);
79
80    virtual ~NCC();
81
82    ///
83    /// @return the centroids for each class as columns in a matrix.
84    ///
85    const utility::matrix& centroids(void) const;
86
87    const DataLookup2D& data(void) const;
88
89    SupervisedClassifier* make_classifier(const DataLookup2D&, 
90                                          const Target&) const;
91   
92    ///
93    /// Train the classifier using the training data. Centroids are
94    /// calculated for each class.
95    ///
96    /// @return true if training succedeed.
97    ///
98    void train();
99
100   
101    ///
102    /// Calculate the distance to each centroid for test samples
103    ///
104    void predict(const DataLookup2D&, utility::matrix&) const;
105   
106   
107  private:
108
109    void predict_unweighted(const MatrixLookup&, utility::matrix&) const;
110    void predict_weighted(const MatrixLookupWeighted&, utility::matrix&) const;   
111
112    utility::matrix* centroids_;
113    bool centroids_nan_;
114
115    // data_ has to be of type DataLookup2D to accomodate both
116    // MatrixLookup and MatrixLookupWeighted
117    const DataLookup2D& data_;
118  };
119
120  ///
121  /// The output operator for the NCC class.
122  ///
123  //  std::ostream& operator<< (std::ostream&, const NCC&);
124 
125
126  // templates
127
128  template <typename Distance>
129  NCC<Distance>::NCC(const MatrixLookup& data, const Target& target) 
130    : SupervisedClassifier(target), centroids_(0), centroids_nan_(false), data_(data) 
131  {
132  }
133
134  template <typename Distance>
135  NCC<Distance>::NCC(const MatrixLookupWeighted& data, const Target& target)
136    : SupervisedClassifier(target), centroids_(0), centroids_nan_(false), data_(data)
137  {
138  }
139
140  template <typename Distance>
141  NCC<Distance>::~NCC()   
142  {
143    if(centroids_)
144      delete centroids_;
145  }
146
147  template <typename Distance>
148  const utility::matrix& NCC<Distance>::centroids(void) const
149  {
150    return *centroids_;
151  }
152 
153
154  template <typename Distance>
155  const DataLookup2D& NCC<Distance>::data(void) const
156  {
157    return data_;
158  }
159 
160  template <typename Distance>
161  SupervisedClassifier* 
162  NCC<Distance>::make_classifier(const DataLookup2D& data, const Target& target) const 
163  {     
164    NCC* ncc=0;
165    try {
166      if(data.weighted()) {
167        ncc=new NCC<Distance>(dynamic_cast<const MatrixLookupWeighted&>(data),
168                              target);
169      }
170      else {
171        ncc=new NCC<Distance>(dynamic_cast<const MatrixLookup&>(data),
172                              target);
173      }
174    }
175    catch (std::bad_cast) {
176      std::string str = "Error in NCC<Distance>::make_classifier: DataLookup2D of unexpected class.";
177      throw std::runtime_error(str);
178    }
179    return ncc;
180  }
181
182
183  template <typename Distance>
184  void NCC<Distance>::train()
185  {   
186    if(centroids_) 
187      delete centroids_;
188    centroids_= new utility::matrix(data_.rows(), target_.nof_classes());
189    // data_ is a MatrixLookup or a MatrixLookupWeighted
190    if(data_.weighted()) {
191      const MatrixLookupWeighted* weighted_data = 
192        dynamic_cast<const MatrixLookupWeighted*>(&data_);     
193      for(size_t i=0; i<data_.rows(); i++) {
194        std::vector<statistics::AveragerWeighted> class_averager;
195        class_averager.resize(target_.nof_classes());
196        for(size_t j=0; j<data_.columns(); j++) {
197          class_averager[target_(j)].add(weighted_data->data(i,j),
198                                         weighted_data->weight(i,j));
199        }
200        for(size_t c=0;c<target_.nof_classes();c++) {
201          (*centroids_)(i,c) = class_averager[c].mean();
202          if(class_averager[c].sum_w()==0)
203            centroids_nan_=true;
204        }
205      }
206    }
207    else {
208      const MatrixLookup* unweighted_data = 
209        dynamic_cast<const MatrixLookup*>(&data_);     
210      for(size_t i=0; i<data_.rows(); i++) {
211        std::vector<statistics::Averager> class_averager;
212        class_averager.resize(target_.nof_classes());
213        for(size_t j=0; j<data_.columns(); j++) {
214          class_averager[target_(j)].add((*unweighted_data)(i,j));
215        }
216        for(size_t c=0;c<target_.nof_classes();c++) {
217          (*centroids_)(i,c) = class_averager[c].mean();
218        }
219      }
220    }
221  }
222
223  template <typename Distance>
224  void NCC<Distance>::predict(const DataLookup2D& test,                     
225                              utility::matrix& prediction) const
226  {   
227    utility::yat_assert<std::runtime_error>
228      (centroids_,"NCC::predict called for untrained classifier");
229    utility::yat_assert<std::runtime_error>
230      (data_.rows()==test.rows(),
231       "NCC::predict test data with incorrect number of rows");
232   
233    prediction.clone(utility::matrix(centroids_->columns(), test.columns()));       
234
235    // unweighted test data
236    if (const MatrixLookup* test_unweighted =
237        dynamic_cast<const MatrixLookup*>(&test)) {
238      // If weighted training data resulting in NaN in centroids: weighted calculations
239      if(centroids_nan_) { 
240        //        predict_weighted(MatrixLookupWeighted(*test_unweighted),prediction);
241        std::string str = 
242        "Error in NCC<Distance>::predict: weighted training unweighted test not implemented yet";
243      throw std::runtime_error(str);
244      }
245      // If unweighted training data: unweighted calculations
246      else {
247        predict_unweighted(*test_unweighted,prediction);
248      }
249    }
250    // weighted test data: weighted calculations
251    else if (const MatrixLookupWeighted* test_weighted =
252             dynamic_cast<const MatrixLookupWeighted*>(&test)) { 
253      predict_weighted(*test_weighted,prediction);
254    }
255    else {
256      std::string str = 
257        "Error in NCC<Distance>::predict: DataLookup2D of unexpected class.";
258      throw std::runtime_error(str);
259    }
260  }
261 
262  template <typename Distance>
263  void NCC<Distance>::predict_unweighted(const MatrixLookup& test, 
264                                         utility::matrix& prediction) const
265  {
266    MatrixLookup unweighted_centroids(*centroids_);
267    for(size_t j=0; j<test.columns();j++) {       
268      DataLookup1D in(test,j,false);
269      for(size_t k=0; k<centroids_->columns();k++) {
270        DataLookup1D centroid(unweighted_centroids,k,false);           
271        utility::yat_assert<std::runtime_error>(in.size()==centroid.size());
272        prediction(k,j)=statistics::
273          distance(in.begin(),in.end(),centroid.begin(),
274                   typename statistics::distance_traits<Distance>::distance());
275      }
276    }
277  }
278
279  template <typename Distance>
280  void NCC<Distance>::predict_weighted(const MatrixLookupWeighted& test, 
281                                          utility::matrix& prediction) const
282  {
283    MatrixLookupWeighted weighted_centroids(*centroids_);
284    for(size_t j=0; j<test.columns();j++) {       
285      DataLookupWeighted1D in(test,j,false);
286      for(size_t k=0; k<centroids_->columns();k++) {
287        DataLookupWeighted1D centroid(weighted_centroids,k,false);
288        utility::yat_assert<std::runtime_error>(in.size()==centroid.size());
289        prediction(k,j)=statistics::
290          distance(in.begin(),in.end(),centroid.begin(),
291                   typename statistics::distance_traits<Distance>::distance());
292      }
293    }
294  }
295
296     
297}}} // of namespace classifier, yat, and theplu
298
299#endif
Note: See TracBrowser for help on using the repository browser.