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

Last change on this file since 1157 was 1157, checked in by Markus Ringnér, 14 years ago

Refs #318

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date ID
File size: 6.8 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/utility/Matrix.h"
40#include "yat/utility/Vector.h"
41#include "yat/utility/stl_utility.h"
42#include "yat/utility/yat_assert.h"
43
44#include<iostream>
45#include<iterator>
46#include <map>
47#include <cmath>
48#include <stdexcept>
49
50namespace theplu {
51namespace yat {
52namespace classifier { 
53
54
55  ///
56  /// @brief Class for Nearest Centroid Classification.
57  ///
58  /// The template argument Distance should be a class modelling
59  /// the concept \ref concept_distance.
60  ///
61  template <typename Distance>
62  class NCC : public SupervisedClassifier
63  {
64 
65  public:
66    ///
67    /// @brief Constructor
68    ///
69    NCC(void);
70   
71
72    ///
73    /// @brief Destructor
74    ///
75    virtual ~NCC(void);
76
77    ///
78    /// @return the centroids for each class as columns in a matrix.
79    ///
80    const utility::Matrix& centroids(void) const;
81
82    NCC<Distance>* make_classifier(void) const;
83   
84    ///
85    /// Train the classifier with a training data set and
86    /// targets. Centroids are calculated for each class.
87    ///
88    void train(const MatrixLookup&, const Target&);
89
90
91    ///
92    /// Train the classifier with a weighted training data set and
93    /// targets. Centroids are calculated for each class.
94    ///
95    void train(const MatrixLookupWeighted&, const Target&);
96
97   
98    ///
99    /// Calculate the distance to each centroid for test samples
100    ///
101    void predict(const DataLookup2D&, utility::Matrix&) const;
102   
103   
104  private:
105
106    void predict_unweighted(const MatrixLookup&, utility::Matrix&) const;
107    void predict_weighted(const MatrixLookupWeighted&, utility::Matrix&) const;   
108
109    utility::Matrix* centroids_;
110    bool centroids_nan_;
111    Distance distance_;
112  };
113
114  ///
115  /// The output operator for the NCC class.
116  ///
117  //  std::ostream& operator<< (std::ostream&, const NCC&);
118 
119
120  // templates
121
122  template <typename Distance>
123  NCC<Distance>::NCC() 
124    : SupervisedClassifier(), centroids_(0), centroids_nan_(false)
125  {
126  }
127
128
129  template <typename Distance>
130  NCC<Distance>::~NCC()   
131  {
132    if(centroids_)
133      delete centroids_;
134  }
135
136
137  template <typename Distance>
138  const utility::Matrix& NCC<Distance>::centroids(void) const
139  {
140    return *centroids_;
141  }
142 
143
144  template <typename Distance>
145  NCC<Distance>* 
146  NCC<Distance>::make_classifier() const 
147  {     
148    return new NCC<Distance>();
149  }
150
151  template <typename Distance>
152  void NCC<Distance>::train(const MatrixLookup& data, const Target& target)
153  {   
154    if(centroids_) 
155      delete centroids_;
156    centroids_= new utility::Matrix(data.rows(), target.nof_classes());
157    for(size_t i=0; i<data.rows(); i++) {
158      std::vector<statistics::Averager> class_averager;
159      class_averager.resize(target.nof_classes());
160      for(size_t j=0; j<data.columns(); j++) {
161        class_averager[target(j)].add(data(i,j));
162      }
163      for(size_t c=0;c<target.nof_classes();c++) {
164        (*centroids_)(i,c) = class_averager[c].mean();
165      }
166    }
167    trained_=true;
168  }
169
170
171  template <typename Distance>
172  void NCC<Distance>::train(const MatrixLookupWeighted& data, const Target& target)
173  {   
174    if(centroids_) 
175      delete centroids_;
176    centroids_= new utility::Matrix(data.rows(), target.nof_classes());
177    for(size_t i=0; i<data.rows(); i++) {
178      std::vector<statistics::AveragerWeighted> class_averager;
179      class_averager.resize(target.nof_classes());
180      for(size_t j=0; j<data.columns(); j++) 
181        class_averager[target(j)].add(data.data(i,j),data.weight(i,j));
182      for(size_t c=0;c<target.nof_classes();c++) {
183        if(class_averager[c].sum_w()==0) {
184          centroids_nan_=true;
185        }
186        (*centroids_)(i,c) = class_averager[c].mean();
187      }
188    }
189    trained_=true;
190  }
191
192
193  template <typename Distance>
194  void NCC<Distance>::predict(const DataLookup2D& test,                     
195                              utility::Matrix& prediction) const
196  {   
197    utility::yat_assert<std::runtime_error>
198      (centroids_,"NCC::predict called for untrained classifier");
199    utility::yat_assert<std::runtime_error>
200      (centroids_->rows()==test.rows(),
201       "NCC::predict test data with incorrect number of rows");
202   
203    prediction.resize(centroids_->columns(), test.columns());
204
205    // unweighted test data
206    if (const MatrixLookup* test_unweighted =
207        dynamic_cast<const MatrixLookup*>(&test)) {
208      // If weighted training data has resulted in NaN in centroids: weighted calculations
209      if(centroids_nan_) { 
210        predict_weighted(MatrixLookupWeighted(*test_unweighted),prediction);
211      }
212      // If unweighted training data: unweighted calculations
213      else {
214        predict_unweighted(*test_unweighted,prediction);
215      }
216    }
217    // weighted test data: weighted calculations
218    else if (const MatrixLookupWeighted* test_weighted =
219             dynamic_cast<const MatrixLookupWeighted*>(&test)) { 
220      predict_weighted(*test_weighted,prediction);
221    }
222    else {
223      std::string str = 
224        "Error in NCC<Distance>::predict: DataLookup2D of unexpected class.";
225      throw std::runtime_error(str);
226    }
227  }
228 
229  template <typename Distance>
230  void NCC<Distance>::predict_unweighted(const MatrixLookup& test, 
231                                         utility::Matrix& prediction) const
232  {
233    MatrixLookup centroids(*centroids_);
234    for(size_t j=0; j<test.columns();j++)
235      for(size_t k=0; k<centroids_->columns();k++) 
236        prediction(k,j) = distance_(test.begin_column(j), test.end_column(j), 
237                                    centroids.begin_column(k));
238  }
239 
240  template <typename Distance>
241  void NCC<Distance>::predict_weighted(const MatrixLookupWeighted& test, 
242                                          utility::Matrix& prediction) const
243  {
244    MatrixLookupWeighted weighted_centroids(*centroids_);
245    for(size_t j=0; j<test.columns();j++) 
246      for(size_t k=0; k<centroids_->columns();k++)
247        prediction(k,j) = distance_(test.begin_column(j), test.end_column(j), 
248                                    weighted_centroids.begin_column(k));
249  }
250
251     
252}}} // of namespace classifier, yat, and theplu
253
254#endif
Note: See TracBrowser for help on using the repository browser.