source: trunk/yat/classifier/NBC.cc @ 950

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

SVM::make_classifier is now throwing if KernelLookup? is not passed.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 5.0 KB
Line 
1// $Id: NBC.cc 950 2007-10-08 23:09:58Z peter $
2
3/*
4  Copyright (C) 2006 Jari Häkkinen, Markus Ringnér, Peter Johansson
5  Copyright (C) 2007 Peter Johansson
6
7  This file is part of the yat library, http://trac.thep.lu.se/trac/yat
8
9  The yat library is free software; you can redistribute it and/or
10  modify it under the terms of the GNU General Public License as
11  published by the Free Software Foundation; either version 2 of the
12  License, or (at your option) any later version.
13
14  The yat library is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  General Public License for more details.
18
19  You should have received a copy of the GNU General Public License
20  along with this program; if not, write to the Free Software
21  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
22  02111-1307, USA.
23*/
24
25#include "NBC.h"
26#include "DataLookup2D.h"
27#include "MatrixLookup.h"
28#include "MatrixLookupWeighted.h"
29#include "Target.h"
30#include "yat/statistics/AveragerWeighted.h"
31#include "yat/utility/matrix.h"
32
33#include <cassert>
34#include <cmath>
35#include <vector>
36
37namespace theplu {
38namespace yat {
39namespace classifier {
40
41  NBC::NBC(const MatrixLookup& data, const Target& target) 
42    : SupervisedClassifier(target), data_(data)
43  {
44  }
45
46  NBC::NBC(const MatrixLookupWeighted& data, const Target& target) 
47    : SupervisedClassifier(target), data_(data)
48  {
49  }
50
51  NBC::~NBC()   
52  {
53  }
54
55
56  const DataLookup2D& NBC::data(void) const
57  {
58    return data_;
59  }
60
61
62  SupervisedClassifier* 
63  NBC::make_classifier(const DataLookup2D& data, const Target& target) const 
64  {     
65    NBC* nbc=0;
66    try {
67      if(data.weighted()) {
68        nbc=new NBC(dynamic_cast<const MatrixLookupWeighted&>(data),target);
69      }
70      else {
71        nbc=new NBC(dynamic_cast<const MatrixLookup&>(data),target);
72      }     
73    }
74    catch (std::bad_cast) {
75      std::string str = 
76        "Error in NBC::make_classifier: DataLookup2D of unexpected class.";
77      throw std::runtime_error(str);
78    }
79    return nbc;
80  }
81
82
83  bool NBC::train()
84  {   
85    sigma2_.resize(data_.rows(), target_.nof_classes());
86    centroids_.resize(data_.rows(), target_.nof_classes());
87    utility::matrix nof_in_class(data_.rows(), target_.nof_classes());
88   
89    for(size_t i=0; i<data_.rows(); ++i) {
90      std::vector<statistics::AveragerWeighted> aver(target_.nof_classes());
91      for(size_t j=0; j<data_.columns(); ++j) {
92        if (data_.weighted()){
93          const MatrixLookupWeighted& data = 
94            dynamic_cast<const MatrixLookupWeighted&>(data_);
95          aver[target_(j)].add(data.data(i,j), data.weight(i,j));
96        }
97        else
98          aver[target_(j)].add(data_(i,j),1.0);
99      }
100      assert(centroids_.columns()==target_.nof_classes());
101      for (size_t j=0; j<target_.nof_classes(); ++j){
102        assert(i<centroids_.rows());
103        assert(j<centroids_.columns());
104        centroids_(i,j) = aver[j].mean();
105        assert(i<sigma2_.rows());
106        assert(j<sigma2_.columns());
107        sigma2_(i,j) = aver[j].variance();
108      }
109    }   
110    trained_=true;
111    return trained_;
112  }
113
114
115  void NBC::predict(const DataLookup2D& x,                   
116                    utility::matrix& prediction) const
117  {   
118    assert(data_.rows()==x.rows());
119    assert(x.rows()==sigma2_.rows());
120    assert(x.rows()==centroids_.rows());
121
122    const MatrixLookupWeighted* w = 
123      dynamic_cast<const MatrixLookupWeighted*>(&x);
124   
125    // each row in prediction corresponds to a sample label (class)
126    prediction.resize(centroids_.columns(), x.columns(), 0);
127    // first calculate -lnP = sum sigma_i + (x_i-m_i)^2/2sigma_i^2
128    for (size_t label=0; label<centroids_.columns(); ++label) {
129      double sum_ln_sigma=0;
130      assert(label<sigma2_.columns());
131      for (size_t i=0; i<x.rows(); ++i) {
132        assert(i<sigma2_.rows());
133        sum_ln_sigma += std::log(sigma2_(i, label));
134      }
135      sum_ln_sigma /= 2; // taking sum of log(sigma) not sigma2
136      for (size_t sample=0; sample<prediction.rows(); ++sample) {
137        for (size_t i=0; i<x.rows(); ++i) {
138          // weighted calculation
139          if (w){
140            // taking care of NaN
141            if (w->weight(i, label)){
142            prediction(label, sample) += w->weight(i, label)*
143              std::pow(w->data(i, label)-centroids_(i, label),2)/
144              sigma2_(i, label);
145            }
146          }
147          // no weights
148          else {
149            prediction(label, sample) += 
150              std::pow(x(i, label)-centroids_(i, label),2)/sigma2_(i, label);
151          }
152        }
153      }
154    }
155
156    // -lnP might be a large number, in order to avoid out of bound
157    // problems when calculating P = exp(- -lnP), we centralize matrix
158    // by adding a constant.
159    double m=0;
160    for (size_t i=0; i<prediction.rows(); ++i)
161      for (size_t j=0; j<prediction.columns(); ++j)
162        m+=prediction(i,j);
163    prediction -= m/prediction.rows()/prediction.columns();
164
165    // exponentiate
166    for (size_t i=0; i<prediction.rows(); ++i)
167      for (size_t j=0; j<prediction.columns(); ++j)
168        prediction(i,j) = std::exp(prediction(i,j));
169
170    // normalize each row (label) to sum up to unity (probability)
171    for (size_t i=0; i<prediction.rows(); ++i)
172      utility::vector(prediction,i) *= 
173        1.0/utility::sum(utility::vector(prediction,i));
174
175  }
176
177
178}}} // of namespace classifier, yat, and theplu
Note: See TracBrowser for help on using the repository browser.