SHOGUN  v3.0.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
CustomMahalanobisDistance.cpp
Go to the documentation of this file.
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 3 of the License, or
5  * (at your option) any later version.
6  *
7  * Written (W) 2013 Fernando J. Iglesias Garcia
8  * Copyright (C) 2013 Fernando J. Iglesias Garcia
9  */
10 
11 #ifdef HAVE_EIGEN3
12 
14 #include <Eigen/Dense>
15 
16 using namespace shogun;
17 using namespace Eigen;
18 
20 {
21 }
22 
24 : CRealDistance()
25 {
26  init();
27  CRealDistance::init(l, r);
28  m_mahalanobis_matrix = m;
29 }
30 
31 void CCustomMahalanobisDistance::init()
32 {
33  SG_ADD(&m_mahalanobis_matrix, "m_mahalanobis_matrix", "Mahalanobis matrix", MS_NOT_AVAILABLE)
34 }
35 
37 {
38  cleanup();
39 }
40 
42 {
43 }
44 
46 {
47  return "CustomMahalanobisDistance";
48 }
49 
51 {
52  return D_CUSTOMMAHALANOBIS;
53 }
54 
55 float64_t CCustomMahalanobisDistance::compute(int32_t idx_a, int32_t idx_b)
56 {
57  // Get feature vectors that will be used to compute the distance; casts
58  // are safe, features are checked to be dense in DenseDistance::init
59  SGVector<float64_t> avec = static_cast<CDenseFeatures<float64_t>*>(lhs)->get_feature_vector(idx_a);
60  SGVector<float64_t> bvec = static_cast<CDenseFeatures<float64_t>*>(rhs)->get_feature_vector(idx_b);
61 
62  REQUIRE(avec.vlen == bvec.vlen, "In CCustomMahalanobisDistance::compute the "
63  "feature vectors must have the same number of elements")
64 
65  // Compute the distance between the feature vectors
66 
67  // Compute the difference vector and wrap in Eigen vector
68  const VectorXd dvec = Map<const VectorXd>(avec, avec.vlen) - Map<const VectorXd>(bvec, bvec.vlen);
69  // Wrap Mahalanobis distance in Eigen matrix
70  Map<const MatrixXd> M(m_mahalanobis_matrix.matrix, m_mahalanobis_matrix.num_rows,
71  m_mahalanobis_matrix.num_cols);
72 
73  return dvec.transpose()*M*dvec;
74 }
75 
76 #endif /* HAVE_EIGEN3 */

SHOGUN Machine Learning Toolbox - Documentation