2 * svrt is the ``Synthetic Visual Reasoning Test'', an image
3 * generator for evaluating classification performance of machine
4 * learning systems, humans and primates.
6 * Copyright (c) 2009 Idiap Research Institute, http://www.idiap.ch/
7 * Written by Francois Fleuret <francois.fleuret@idiap.ch>
9 * This file is part of svrt.
11 * svrt is free software: you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 3 as
13 * published by the Free Software Foundation.
15 * svrt is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with svrt. If not, see <http://www.gnu.org/licenses/>.
25 #include "naive_bayesian_classifier.h"
26 #include "classifier_reader.h"
28 NaiveBayesianClassifier::NaiveBayesianClassifier() { }
30 NaiveBayesianClassifier::~NaiveBayesianClassifier() { }
32 const char *NaiveBayesianClassifier::name() {
33 return "NAIVE_BAYESIAN";
36 void NaiveBayesianClassifier::train(int nb_vignettes, Vignette *vignettes, int *labels) {
37 for(int k = 0; k < Vignette::width * Vignette::height * Vignette::nb_grayscales; k++) {
42 int nb_0 = 0, nb_1 = 0;
44 global.bar.init(&cout, nb_vignettes);
45 for(int n = 0; n < nb_vignettes; n++) {
48 for(int k = 0; k < Vignette::width * Vignette::height; k++) {
49 proba_given_1[k * Vignette::nb_grayscales + vignettes[n].content[k]] += 1.0;
53 for(int k = 0; k < Vignette::width * Vignette::height; k++) {
54 proba_given_0[k * Vignette::nb_grayscales + vignettes[n].content[k]] += 1.0;
57 global.bar.refresh(&cout, n);
59 global.bar.finish(&cout);
61 for(int k = 0; k < Vignette::width * Vignette::height * Vignette::nb_grayscales; k++) {
62 proba_given_0[k] /= scalar_t(nb_0);
63 proba_given_1[k] /= scalar_t(nb_1);
67 scalar_t NaiveBayesianClassifier::classify(Vignette *vignette) {
68 scalar_t result = 0.0;
70 for(int k = 0; k < Vignette::width * Vignette::height; k++) {
71 result += log(proba_given_1[k * Vignette::nb_grayscales + vignette->content[k]])
72 - log(proba_given_0[k * Vignette::nb_grayscales + vignette->content[k]]);
78 void NaiveBayesianClassifier::read(istream *in) {
79 in->read((char *) proba_given_0, sizeof(scalar_t) * Vignette::width * Vignette::height * Vignette::nb_grayscales);
80 in->read((char *) proba_given_1, sizeof(scalar_t) * Vignette::width * Vignette::height * Vignette::nb_grayscales);
83 void NaiveBayesianClassifier::write(ostream *out) {
85 t = CT_NAIVE_BAYESIAN;
87 out->write((char *) proba_given_0, sizeof(scalar_t) * Vignette::width * Vignette::height * Vignette::nb_grayscales);
88 out->write((char *) proba_given_1, sizeof(scalar_t) * Vignette::width * Vignette::height * Vignette::nb_grayscales);