#include #include #include #include #include #include "svm_rbf.h" namespace mpt { svm_rbf::svm_rbf( const std::string &ay_path, const std::string &vs_path ) : ay(num_support_vectors), vs(num_support_vectors*feature_vector_length) { load_ay( ay_path ); load_vs( vs_path ); } svm_rbf::~svm_rbf() { } // h=histogram representation [1xFEATURE_VECTOR_LENGTH] // vs = support vector in histogram representation [NUM_SUPPORT_VECTORSxFEATURE_VECTOR_LENGTH]. // ay = coefficients of support [NUM_SUPPORT_VECTORSx1] // g = gaussian width [1x1] double svm_rbf::decision( const std::vector &histogram, double g ) { double y = 0.0; if( feature_vector_length != histogram.size() ) { std::cerr << "Bad histogram length. Should be: " << feature_vector_length << ". Is: " << histogram.size() << std::endl; return 0.0; } for( unsigned int i = 0; i < num_support_vectors; ++i ) { double D2 = 0.0; // std::vector D(feature_vector_length); for( unsigned int j = 0; j < feature_vector_length; j++) { double D = histogram[j] - vs[i*feature_vector_length + j]; D2 += D * D; } y += ay[i] * exp(-0.5*D2/g); } return y; } void svm_rbf::load_ay( const std::string &path ) { unsigned int count = 0; std::ifstream ifs( path.c_str() ); if( ifs.good() ) { double val; for( unsigned int i = 0; i < num_support_vectors; ++i ) { if( ifs >> val ) { ay[i] = val; ++count; } else { // throw an exception std::cerr << "Missing value in ay. Index: " << i << std::endl; } } } if( count != num_support_vectors ) { // throw an exception std::cerr << "Vector ay is not the right size: " << num_support_vectors << std::endl; } } void svm_rbf::load_vs( const std::string &path ) { const unsigned int size = feature_vector_length * num_support_vectors; unsigned int count = 0; std::ifstream ifs( path.c_str() ); if( ifs.good() ) { for (unsigned int i = 0; i < num_support_vectors; i++) { std::string line; std::getline( ifs, line ); std::stringstream linestream( line ); for (unsigned int j = 0; j < feature_vector_length; j++) { double val; if( linestream >> val ) { vs[i*feature_vector_length + j] = val; ++count; } else { // throw an exception std::cerr << "Missing value in vs. Indexes i/j: " << i << "/" << j << std::endl; } } } } if( count != size ) { // throw an exception std::cerr << "Vector vs is not the right size. Should be " << size << ". Is " << count << std::endl; } } } // end namespace mpt