SHOGUN  3.2.1
 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  register_params();
22 }
23 
25 : CRealDistance()
26 {
27  register_params();
28  CRealDistance::init(l, r);
29  m_mahalanobis_matrix = m;
30 }
31 
32 void CCustomMahalanobisDistance::register_params()
33 {
34  SG_ADD(&m_mahalanobis_matrix, "m_mahalanobis_matrix", "Mahalanobis matrix", MS_NOT_AVAILABLE)
35 }
36 
38 {
39  cleanup();
40 }
41 
43 {
44 }
45 
47 {
48  return "CustomMahalanobisDistance";
49 }
50 
52 {
53  return D_CUSTOMMAHALANOBIS;
54 }
55 
56 float64_t CCustomMahalanobisDistance::compute(int32_t idx_a, int32_t idx_b)
57 {
58  // Get feature vectors that will be used to compute the distance; casts
59  // are safe, features are checked to be dense in DenseDistance::init
60  SGVector<float64_t> avec = static_cast<CDenseFeatures<float64_t>*>(lhs)->get_feature_vector(idx_a);
61  SGVector<float64_t> bvec = static_cast<CDenseFeatures<float64_t>*>(rhs)->get_feature_vector(idx_b);
62 
63  REQUIRE(avec.vlen == bvec.vlen, "In CCustomMahalanobisDistance::compute the "
64  "feature vectors must have the same number of elements")
65 
66  // Compute the distance between the feature vectors
67 
68  // Compute the difference vector and wrap in Eigen vector
69  const VectorXd dvec = Map<const VectorXd>(avec, avec.vlen) - Map<const VectorXd>(bvec, bvec.vlen);
70  // Wrap Mahalanobis distance in Eigen matrix
71  Map<const MatrixXd> M(m_mahalanobis_matrix.matrix, m_mahalanobis_matrix.num_rows,
72  m_mahalanobis_matrix.num_cols);
73 
74  return dvec.transpose()*M*dvec;
75 }
76 
77 #endif /* HAVE_EIGEN3 */

SHOGUN Machine Learning Toolbox - Documentation