[mlpack-svn] r15697 - mlpack/trunk/src/mlpack/core/kernels

fastlab-svn at coffeetalk-1.cc.gatech.edu fastlab-svn at coffeetalk-1.cc.gatech.edu
Sun Sep 1 23:21:35 EDT 2013


Author: rcurtin
Date: Sun Sep  1 23:21:35 2013
New Revision: 15697

Log:
Handle corner case where ||a|| or ||b|| is equal to 0 (and prevent division by
zero).


Modified:
   mlpack/trunk/src/mlpack/core/kernels/cosine_distance_impl.hpp

Modified: mlpack/trunk/src/mlpack/core/kernels/cosine_distance_impl.hpp
==============================================================================
--- mlpack/trunk/src/mlpack/core/kernels/cosine_distance_impl.hpp	(original)
+++ mlpack/trunk/src/mlpack/core/kernels/cosine_distance_impl.hpp	Sun Sep  1 23:21:35 2013
@@ -15,8 +15,16 @@
 template<typename VecType>
 double CosineDistance::Evaluate(const VecType& a, const VecType& b)
 {
-  // Since we are using the L2 inner product, this is easy.
-  return dot(a, b) / (norm(a, 2) * norm(b, 2));
+  // Since we are using the L2 inner product, this is easy.  But we have to make
+  // sure we aren't dividing by zero (if we are, then the cosine similarity is
+  // 0: we reason this value because the cosine distance is just a normalized
+  // dot product; take away the normalization, and if ||a|| or ||b|| is equal to
+  // 0, then a^T b is zero too).
+  const double denominator = norm(a, 2) * norm(b, 2);
+  if (denominator == 0.0)
+    return 0;
+  else
+    return dot(a, b) / denominator;
 }
 
 }; // namespace kernel



More information about the mlpack-svn mailing list