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

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

NCC and IGP have been changed to templates on Distance

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date ID
File size: 5.6 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/trac/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/vector_distance.h"
38
39#include "yat/utility/Iterator.h"
40#include "yat/utility/IteratorWeighted.h"
41#include "yat/utility/matrix.h"
42#include "yat/utility/vector.h"
43#include "yat/utility/stl_utility.h"
44#include "yat/utility/yat_assert.h"
45
46#include<iostream>
47#include<iterator>
48#include <map>
49#include <cmath>
50
51
52namespace theplu {
53namespace yat {
54namespace classifier { 
55
56
57  ///
58  /// @brief Class for Nearest Centroid Classification.
59  ///
60
61  template <typename Distance>
62  class NCC : public SupervisedClassifier
63  {
64 
65  public:
66    ///
67    /// Constructor taking the training data and the target vector as
68    /// input
69    ///
70    NCC(const MatrixLookup&, const Target&);
71   
72    ///
73    /// Constructor taking the training data with weights and the
74    /// target vector as input.
75    ///
76    NCC(const MatrixLookupWeighted&, const Target&);
77
78    virtual ~NCC();
79
80    ///
81    /// @return the centroids for each class as columns in a matrix.
82    ///
83    const utility::matrix& centroids(void) const;
84
85    const DataLookup2D& data(void) const;
86
87    SupervisedClassifier* make_classifier(const DataLookup2D&, 
88                                          const Target&) const;
89   
90    ///
91    /// Train the classifier using the training data. Centroids are
92    /// calculated for each class.
93    ///
94    /// @return true if training succedeed.
95    ///
96    bool train();
97
98   
99    ///
100    /// Calculate the distance to each centroid for test samples
101    ///
102    void predict(const DataLookup2D&, utility::matrix&) const;
103   
104   
105  private:
106
107    utility::matrix centroids_;
108
109    // data_ has to be of type DataLookup2D to accomodate both
110    // MatrixLookup and MatrixLookupWeighted
111    const DataLookup2D& data_;
112
113  };
114
115  ///
116  /// The output operator for the NCC class.
117  ///
118  //  std::ostream& operator<< (std::ostream&, const NCC&);
119 
120
121  // templates
122
123  template <typename Distance>
124  NCC<Distance>::NCC(const MatrixLookup& data, const Target& target) 
125    : SupervisedClassifier(target), data_(data)
126  {
127  }
128
129  template <typename Distance>
130  NCC<Distance>::NCC(const MatrixLookupWeighted& data, const Target& target)
131    : SupervisedClassifier(target), data_(data)
132  {
133  }
134
135  template <typename Distance>
136  NCC<Distance>::~NCC()   
137  {
138  }
139
140
141  template <typename Distance>
142  const utility::matrix& NCC<Distance>::centroids(void) const
143  {
144    return centroids_;
145  }
146 
147
148  template <typename Distance>
149  const DataLookup2D& NCC<Distance>::data(void) const
150  {
151    return data_;
152  }
153 
154  template <typename Distance>
155  SupervisedClassifier* 
156  NCC<Distance>::make_classifier(const DataLookup2D& data, const Target& target) const 
157  {     
158    NCC* ncc=0;
159    if(data.weighted()) {
160      ncc=new NCC<Distance>(dynamic_cast<const MatrixLookupWeighted&>(data),
161                  target);
162    }
163    else {
164      ncc=new NCC<Distance>(dynamic_cast<const MatrixLookup&>(data),
165                  target);
166    }
167    return ncc;
168  }
169
170
171  template <typename Distance>
172  bool NCC<Distance>::train()
173  {   
174    centroids_.clone(utility::matrix(data_.rows(), target_.nof_classes()));
175    utility::matrix nof_in_class(data_.rows(), target_.nof_classes());
176    const MatrixLookupWeighted* weighted_data = 
177      dynamic_cast<const MatrixLookupWeighted*>(&data_);
178    bool weighted = weighted_data;
179
180    for(size_t i=0; i<data_.rows(); i++) {
181      for(size_t j=0; j<data_.columns(); j++) {
182        centroids_(i,target_(j)) += data_(i,j);
183        if (weighted)
184          nof_in_class(i,target_(j))+= weighted_data->weight(i,j);
185        else
186          nof_in_class(i,target_(j))+=1.0;
187      }
188    }   
189    centroids_.div(nof_in_class);
190    trained_=true;
191    return trained_;
192  }
193
194  template <typename Distance>
195  void NCC<Distance>::predict(const DataLookup2D& input,                   
196                    utility::matrix& prediction) const
197  {   
198    prediction.clone(utility::matrix(centroids_.columns(), input.columns()));   
199
200    // Weighted case
201    const MatrixLookupWeighted* testdata =
202      dynamic_cast<const MatrixLookupWeighted*>(&input);     
203    if (testdata) {
204      MatrixLookupWeighted weighted_centroids(centroids_);
205      for(size_t j=0; j<input.columns();j++) {       
206        DataLookupWeighted1D in(*testdata,j,false);
207        for(size_t k=0; k<centroids_.columns();k++) {
208          DataLookupWeighted1D centroid(weighted_centroids,k,false);
209
210          yat_assert(in.size()==centroid.size());
211          prediction(k,j)=statistics::
212            vector_distance(in.begin(),in.end(),centroid.begin(),
213                             typename statistics::vector_distance_traits<Distance>::distance());
214        }
215      }
216    }
217    else {
218      std::string str;
219      str = "Error in NCC<Distance>::predict: DataLookup2D of unexpected class.";
220      throw std::runtime_error(str);
221    }
222  }
223     
224}}} // of namespace classifier, yat, and theplu
225
226#endif
Note: See TracBrowser for help on using the repository browser.