#include #include #include #include "pcSVM.hpp" using namespace pcsvm; // using namespace pcsvm; typedef float (*klassFun)(float, float); float urand() { return std::rand()/float(RAND_MAX); } void run(std::string name, KernelI* k, klassFun f) { std::cout << std::endl; std::cout << "Test : " << name << std::endl; SparseVector exVec; ClassificationProblem prob; for (int i=0; i<100; ++i) { // generate example // // loop: // only accept examples with some distance to // decision surface float dist; // distance to decision surface float x,y; do { // points in [-1,1] x [-1,1] x = 2.0f*(-.5f + urand()); y = 2.0f*(-.5f + urand()); dist = (*f)(x,y); } while (std::fabs(dist)<.1); exVec[0] = x; exVec[1] = y; prob.push_back(ClassificationExample(exVec, dist>0.0f ? true : false)); } ClassifierCSVM klass(&prob, k); try { klass.train(9999); } catch (std::runtime_error e) { std::cout << "!!! caught runtimer error: " << e.what() << std::endl; std::exit(1); } // check known support vectors ! int failed=0; for (int i=0; i<100;++i) { float x = 2.0f*(-.5f + urand()); float y = 2.0f*(-.5f + urand()); exVec[0] = x; exVec[1] = y; float tobe = (*f)(x,y)>0.0f; if (tobe*klass(exVec)<0.0) failed += 1; } std::cout << "failed: " << failed << " of 100 test examples" << std::endl; } float isInCircle(float x, float y) { return 1-x*x-y*y; } float isInHalfPlane(float x, float y) { return x+y; } float testXOR(float x, float y) { float fx = std::fabs(x), fy=std::fabs(y); float dist = fx > fy ? fy : fx; float sign = x*y > 0 ? 1.0 : -1.0; return sign*dist; } int main() { std::srand(std::time(0)); KernelI *p; p = new LinearKernel; run("half plane, linear kernel", p, &isInHalfPlane); p = new RadialKernel; run("circle, radial kernel", p, &isInCircle); delete p; p = new PolynomialKernel(0,2); run("circle, poly(0,2) kernel", p, &isInCircle); delete p; p = new PolynomialKernel(0,2); run("xor, poly(0,2) kernel", p, &testXOR); delete p; p = new RadialKernel(1); run("xor, radial(1) kernel", p, &testXOR); delete p; p = new RadialKernel(.1); run("xor, radial(.10) kernel", p, &testXOR); delete p; return 0; }