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

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

merge patch release 0.4.2 to trunk. Delta 0.4.2-0.4.1

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 5.9 KB
Line 
1// $Id: NBC.cc 1437 2008-08-25 17:55:00Z peter $
2
3/*
4  Copyright (C) 2006, 2007 Jari Häkkinen, Peter Johansson, Markus Ringnér
5  Copyright (C) 2008 Peter Johansson, Markus Ringnér
6
7  This file is part of the yat library, http://dev.thep.lu.se/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 "MatrixLookup.h"
27#include "MatrixLookupWeighted.h"
28#include "Target.h"
29#include "yat/statistics/Averager.h"
30#include "yat/statistics/AveragerWeighted.h"
31#include "yat/utility/Matrix.h"
32
33#include <cassert>
34#include <cmath>
35#include <limits>
36#include <stdexcept>
37#include <vector>
38
39namespace theplu {
40namespace yat {
41namespace classifier {
42
43  NBC::NBC() 
44    : SupervisedClassifier()
45  {
46  }
47
48
49  NBC::~NBC()   
50  {
51  }
52
53
54  NBC* NBC::make_classifier() const 
55  {     
56    return new NBC();
57  }
58
59
60  void NBC::train(const MatrixLookup& data, const Target& target)
61  {   
62    sigma2_.resize(data.rows(), target.nof_classes());
63    centroids_.resize(data.rows(), target.nof_classes());
64   
65    for(size_t i=0; i<data.rows(); ++i) {
66      std::vector<statistics::Averager> aver(target.nof_classes());
67      for(size_t j=0; j<data.columns(); ++j) 
68        aver[target(j)].add(data(i,j));
69     
70      assert(centroids_.columns()==target.nof_classes());
71      for (size_t j=0; j<target.nof_classes(); ++j){
72        assert(i<centroids_.rows());
73        assert(j<centroids_.columns());
74        assert(i<sigma2_.rows());
75        assert(j<sigma2_.columns());
76        if (aver[j].n()>1){
77          sigma2_(i,j) = aver[j].variance();
78          centroids_(i,j) = aver[j].mean();
79        }
80        else {
81            sigma2_(i,j) = std::numeric_limits<double>::quiet_NaN();
82            centroids_(i,j) = std::numeric_limits<double>::quiet_NaN();
83        }
84      }
85    }
86  }   
87
88
89  void NBC::train(const MatrixLookupWeighted& data, const Target& target)
90  {   
91    sigma2_.resize(data.rows(), target.nof_classes());
92    centroids_.resize(data.rows(), target.nof_classes());
93
94    for(size_t i=0; i<data.rows(); ++i) {
95      std::vector<statistics::AveragerWeighted> aver(target.nof_classes());
96      for(size_t j=0; j<data.columns(); ++j) 
97        aver[target(j)].add(data.data(i,j), data.weight(i,j));
98     
99      assert(centroids_.columns()==target.nof_classes());
100      for (size_t j=0; j<target.nof_classes(); ++j) {
101        assert(i<centroids_.rows());
102        assert(j<centroids_.columns());
103        assert(i<sigma2_.rows());
104        assert(j<sigma2_.columns());
105        if (aver[j].n()>1){
106          sigma2_(i,j) = aver[j].variance();
107          centroids_(i,j) = aver[j].mean();
108        }
109        else {
110          sigma2_(i,j) = std::numeric_limits<double>::quiet_NaN();
111          centroids_(i,j) = std::numeric_limits<double>::quiet_NaN();
112        }
113      }
114    }
115  }
116
117
118  void NBC::predict(const MatrixLookup& ml,                     
119                    utility::Matrix& prediction) const
120  {   
121    assert(ml.rows()==sigma2_.rows());
122    assert(ml.rows()==centroids_.rows());
123    // each row in prediction corresponds to a sample label (class)
124    prediction.resize(centroids_.columns(), ml.columns(), 0);
125
126    // first calculate -lnP = sum sigma_i + (x_i-m_i)^2/2sigma_i^2
127    for (size_t label=0; label<centroids_.columns(); ++label) {
128      double sum_log_sigma = sum_logsigma(label);
129      for (size_t sample=0; sample<prediction.rows(); ++sample) {
130        prediction(label,sample) = sum_log_sigma;
131        for (size_t i=0; i<ml.rows(); ++i) 
132          prediction(label, sample) += 
133            std::pow(ml(i, label)-centroids_(i, label),2)/
134            sigma2_(i, label);
135      }
136    }
137    standardize_lnP(prediction);
138  }
139
140     
141  void NBC::predict(const MatrixLookupWeighted& mlw,                   
142                    utility::Matrix& prediction) const
143  {   
144    assert(mlw.rows()==sigma2_.rows());
145    assert(mlw.rows()==centroids_.rows());
146   
147    // each row in prediction corresponds to a sample label (class)
148    prediction.resize(centroids_.columns(), mlw.columns(), 0);
149
150    // first calculate -lnP = sum (sigma_i) +
151    // N sum w_i(x_i-m_i)^2/2sigma_i^2 / sum w_i
152    for (size_t label=0; label<centroids_.columns(); ++label) {
153      double sum_log_sigma = sum_logsigma(label);
154      for (size_t sample=0; sample<prediction.rows(); ++sample) {
155        statistics::AveragerWeighted aw;
156        for (size_t i=0; i<mlw.rows(); ++i) 
157          aw.add(std::pow(mlw.data(i, label)-centroids_(i, label),2)/
158                 sigma2_(i, label), mlw.weight(i, label));
159        prediction(label,sample) = sum_log_sigma + mlw.rows()*aw.mean()/2;
160      }
161    }
162    standardize_lnP(prediction);
163  }
164
165  void NBC::standardize_lnP(utility::Matrix& prediction) const
166  {
167    /// -lnP might be a large number, in order to avoid out of bound
168    /// problems when calculating P = exp(- -lnP), we centralize matrix
169    /// by adding a constant.
170    // lookup of prediction with zero weights for NaNs
171    MatrixLookupWeighted mlw(prediction);
172    statistics::AveragerWeighted a;
173    add(a, mlw.begin(), mlw.end());
174    prediction -= a.mean();
175   
176    // exponentiate
177    for (size_t i=0; i<prediction.rows(); ++i)
178      for (size_t j=0; j<prediction.columns(); ++j)
179        prediction(i,j) = std::exp(prediction(i,j));
180   
181    // normalize each row (label) to sum up to unity (probability)
182    for (size_t i=0; i<prediction.rows(); ++i){
183      // calculate sum of row ignoring NaNs
184      statistics::AveragerWeighted a;
185      add(a, mlw.begin_row(i), mlw.end_row(i));
186      prediction.row_view(i) *= 1.0/a.sum_wx();
187    }
188  }
189
190
191  double NBC::sum_logsigma(size_t label) const
192  {
193    double sum_log_sigma=0;
194    assert(label<sigma2_.columns());
195    for (size_t i=0; i<sigma2_.rows(); ++i) {
196      sum_log_sigma += std::log(sigma2_(i, label));
197    }
198    return sum_log_sigma / 2; // taking sum of log(sigma) not sigma2
199  }
200
201}}} // of namespace classifier, yat, and theplu
Note: See TracBrowser for help on using the repository browser.