Commit dc9527be authored by Davis King's avatar Davis King

Added cosine_distance.

parent b5f77a0c
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
#include "function_objects_abstract.h" #include "function_objects_abstract.h"
#include "../matrix.h" #include "../matrix.h"
#include "../svm/sparse_vector.h"
#include <cmath> #include <cmath>
#include <limits> #include <limits>
...@@ -46,6 +47,24 @@ namespace dlib ...@@ -46,6 +47,24 @@ namespace dlib
} }
}; };
// ----------------------------------------------------------------------------------------
struct cosine_distance
{
template <typename sample_type>
double operator() (
const sample_type& a,
const sample_type& b
) const
{
const double temp = length(a)*length(b);
if (temp == 0)
return 0;
else
return 1-dot(a,b)/temp;
}
};
// ---------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------
struct use_weights_of_one struct use_weights_of_one
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
#include "../matrix.h" #include "../matrix.h"
#include <cmath> #include <cmath>
#include "../svm/sparse_vector_abstract.h"
namespace dlib namespace dlib
{ {
...@@ -57,6 +58,37 @@ namespace dlib ...@@ -57,6 +58,37 @@ namespace dlib
!*/ !*/
}; };
// ----------------------------------------------------------------------------------------
struct cosine_distance
{
/*!
WHAT THIS OBJECT REPRESENTS
This is a simple function object that the cosine of the angle between
two vectors and returns 1 - this quantity. Moreover, this object
works for both sparse and dense vectors.
!*/
template <typename sample_type>
double operator() (
const sample_type& a,
const sample_type& b
) const;
/*!
requires
- sample_type is a dense vector (e.g. a dlib::matrix) or a sparse
vector as defined at the top of dlib/svm/sparse_vector_abstract.h
ensures
- let theta = the angle between a and b.
- returns 1 - cos(theta)
(e.g. this function returns 0 when a and b have an angle of 0 between
each other, 1 if they have a 90 degree angle, and a maximum of 2 if the
vectors have a 180 degree angle between each other).
- zero length vectors are considered to have angles of 0 between all other
vectors.
!*/
};
// ---------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------
struct use_weights_of_one struct use_weights_of_one
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment