SHOGUN v0.9.0
|
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-2009 Christian Gehl 00008 * Copyright (C) 2008-2009 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/SimpleFeatures.h" 00017 00018 using namespace shogun; 00019 00020 CCosineDistance::CCosineDistance() 00021 : CSimpleDistance<float64_t>() 00022 { 00023 } 00024 00025 CCosineDistance::CCosineDistance(CSimpleFeatures<float64_t>* l, CSimpleFeatures<float64_t>* r) 00026 : CSimpleDistance<float64_t>() 00027 { 00028 init(l, r); 00029 } 00030 00031 CCosineDistance::~CCosineDistance() 00032 { 00033 cleanup(); 00034 } 00035 00036 bool CCosineDistance::init(CFeatures* l, CFeatures* r) 00037 { 00038 return CSimpleDistance<float64_t>::init(l,r); 00039 } 00040 00041 void CCosineDistance::cleanup() 00042 { 00043 } 00044 00045 float64_t CCosineDistance::compute(int32_t idx_a, int32_t idx_b) 00046 { 00047 int32_t alen, blen; 00048 bool afree, bfree; 00049 00050 float64_t* avec= 00051 ((CSimpleFeatures<float64_t>*) lhs)->get_feature_vector(idx_a, alen, afree); 00052 float64_t* bvec= 00053 ((CSimpleFeatures<float64_t>*) rhs)->get_feature_vector(idx_b, blen, bfree); 00054 00055 ASSERT(alen==blen); 00056 float64_t s=0; 00057 float64_t ab=0; 00058 float64_t sa=0; 00059 float64_t sb=0; 00060 { 00061 for (int32_t i=0; i<alen; i++) 00062 { 00063 ab+=avec[i]*bvec[i]; 00064 sa+=pow(fabs(avec[i]),2); 00065 sb+=pow(fabs(bvec[i]),2); 00066 } 00067 } 00068 00069 ((CSimpleFeatures<float64_t>*) lhs)->free_feature_vector(avec, idx_a, afree); 00070 ((CSimpleFeatures<float64_t>*) rhs)->free_feature_vector(bvec, idx_b, bfree); 00071 00072 s=sqrt(sa)*sqrt(sb); 00073 00074 // trap division by zero 00075 if(s==0) 00076 return 0; 00077 00078 s=1-ab/s; 00079 if(s<0) 00080 return 0; 00081 else 00082 return s ; 00083 }