CosineDistance.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) 2008 Christian Gehl
00008  * Copyright (C) 2008 Fraunhofer Institute FIRST
00009  */
00010 
00011 #include "lib/config.h"
00012 #include "lib/common.h"
00013 #include "lib/io.h"
00014 #include "distance/CosineDistance.h"
00015 #include "features/Features.h"
00016 #include "features/RealFeatures.h"
00017 
00018 CCosineDistance::CCosineDistance()
00019 : CSimpleDistance<float64_t>()
00020 {
00021 }
00022 
00023 CCosineDistance::CCosineDistance(CRealFeatures* l, CRealFeatures* r)
00024 : CSimpleDistance<float64_t>()
00025 {
00026     init(l, r);
00027 }
00028 
00029 CCosineDistance::~CCosineDistance()
00030 {
00031     cleanup();
00032 }
00033 
00034 bool CCosineDistance::init(CFeatures* l, CFeatures* r)
00035 {
00036     bool result=CSimpleDistance<float64_t>::init(l,r);
00037 
00038     return result;
00039 }
00040 
00041 void CCosineDistance::cleanup()
00042 {
00043 }
00044 
00045 bool CCosineDistance::load_init(FILE* src)
00046 {
00047     return false;
00048 }
00049 
00050 bool CCosineDistance::save_init(FILE* dest)
00051 {
00052     return false;
00053 }
00054 
00055 float64_t CCosineDistance::compute(int32_t idx_a, int32_t idx_b)
00056 {
00057     int32_t alen, blen;
00058     bool afree, bfree;
00059 
00060     float64_t* avec=
00061         ((CRealFeatures*) lhs)->get_feature_vector(idx_a, alen, afree);
00062     float64_t* bvec=
00063         ((CRealFeatures*) rhs)->get_feature_vector(idx_b, blen, bfree);
00064 
00065     ASSERT(alen==blen);
00066     float64_t s=0;
00067     float64_t ab=0;
00068     float64_t sa=0;
00069     float64_t sb=0;
00070     {
00071         for (int32_t i=0; i<alen; i++)
00072         {
00073             ab+=avec[i]*bvec[i];
00074             sa+=pow(fabs(avec[i]),2);
00075             sb+=pow(fabs(bvec[i]),2);
00076         }
00077     }
00078 
00079     ((CRealFeatures*) lhs)->free_feature_vector(avec, idx_a, afree);
00080     ((CRealFeatures*) rhs)->free_feature_vector(bvec, idx_b, bfree);
00081     
00082     s=sqrt(sa)*sqrt(sb);
00083     
00084     // trap division by zero
00085     if(s==0)
00086         return 0;
00087 
00088     s=1-ab/s;
00089     if(s<0)
00090         return 0;
00091     else
00092         return s ;
00093 }

SHOGUN Machine Learning Toolbox - Documentation