Chi2Kernel.cpp

Go to the documentation of this file.
00001 /*
00002  * This program is free software; you can redistribute it and/or modify
00003  * it under the terms of the GNU General Public License as published by
00004  * the Free Software Foundation; either version 3 of the License, or
00005  * (at your option) any later version.
00006  *
00007  * Written (W) 1999-2008 Soeren Sonnenburg
00008  * Copyright (C) 1999-2008 Fraunhofer Institute FIRST and Max-Planck-Society
00009  */
00010 
00011 #include "lib/common.h"
00012 #include "kernel/Chi2Kernel.h"
00013 #include "features/Features.h"
00014 #include "features/RealFeatures.h"
00015 #include "lib/io.h"
00016 
00017 CChi2Kernel::CChi2Kernel(int32_t size, float64_t w)
00018 : CSimpleKernel<float64_t>(size), width(w)
00019 {
00020 }
00021 
00022 CChi2Kernel::CChi2Kernel(
00023     CRealFeatures* l, CRealFeatures* r, float64_t w, int32_t size)
00024 : CSimpleKernel<float64_t>(size), width(w)
00025 {
00026     init(l,r);
00027 }
00028 
00029 CChi2Kernel::~CChi2Kernel()
00030 {
00031     cleanup();
00032 }
00033 
00034 bool CChi2Kernel::init(CFeatures* l, CFeatures* r)
00035 {
00036     bool result=CSimpleKernel<float64_t>::init(l,r);
00037     init_normalizer();
00038     return result;
00039 }
00040 
00041 bool CChi2Kernel::load_init(FILE* src)
00042 {
00043     return false;
00044 }
00045 
00046 bool CChi2Kernel::save_init(FILE* dest)
00047 {
00048     return false;
00049 }
00050 
00051 float64_t CChi2Kernel::compute(int32_t idx_a, int32_t idx_b)
00052 {
00053     int32_t alen, blen;
00054     bool afree, bfree;
00055 
00056     float64_t* avec=
00057         ((CRealFeatures*) lhs)->get_feature_vector(idx_a, alen, afree);
00058     float64_t* bvec=
00059         ((CRealFeatures*) rhs)->get_feature_vector(idx_b, blen, bfree);
00060     ASSERT(alen==blen);
00061 
00062     float64_t result=0;
00063     for (int32_t i=0; i<alen; i++)
00064     {
00065         float64_t n=avec[i]-bvec[i];
00066         float64_t d=avec[i]+bvec[i];
00067         if (d!=0)
00068             result+=n*n/d;
00069     }
00070 
00071     result=exp(-result/width);
00072 
00073     ((CRealFeatures*) lhs)->free_feature_vector(avec, idx_a, afree);
00074     ((CRealFeatures*) rhs)->free_feature_vector(bvec, idx_b, bfree);
00075 
00076     return result;
00077 }

SHOGUN Machine Learning Toolbox - Documentation