Source code: marf/Classification/Distance/MahalanobisDistance.java
1 package marf.Classification.Distance;
2
3 import marf.FeatureExtraction.IFeatureExtraction;
4 import marf.math.Matrix;
5 import marf.util.Debug;
6
7
8 /**
9 * <p>Mahalanobis Distance Classification Module.</p>
10 *
11 * <p><b>NOTE</b>: Implemented as equivalent to Euclidean Distance in 0.2.0, i.e.
12 * the Covariance matrix is always an Indentity one.</p>
13 *
14 * <p>$Id: MahalanobisDistance.java,v 1.21 2005/08/12 20:02:56 susan_fan Exp $</p>
15 *
16 * @author Serguei Mokhov
17 * @version $Revision: 1.21 $
18 * @since 0.2.0
19 */
20 public class MahalanobisDistance
21 extends Distance
22 {
23 /**
24 * For serialization versioning.
25 * When adding new members or make other structural
26 * changes regenerate this number with the
27 * <code>serialver</code> tool that comes with JDK.
28 * @since 0.3.0.4
29 */
30 private static final long serialVersionUID = -6720267386878796592L;
31
32 /**
33 * Covariance Matrix.
34 */
35 private Matrix oC = null;
36
37 /**
38 * MahalanobisDistance Constructor.
39 * @param poFeatureExtraction FeatureExtraction module reference
40 */
41 public MahalanobisDistance(IFeatureExtraction poFeatureExtraction)
42 {
43 super(poFeatureExtraction);
44
45 int iD = this.oFeatureExtraction.getFeaturesArray().length;
46
47 this.oC = new Matrix(iD, iD);
48
49 /*
50 * Make the default an indetity matrix rendering it at least
51 * equivalent to Euclidean distance. Will be fixed in 0.3.*
52 */
53 this.oC.makeIdentity();
54 }
55
56 /**
57 * Partial MahalanobisDistance implementation.
58 * @param paVector1 first vector to compare
59 * @param paVector2 second vector to compare
60 * @return Mahalanobis distance between two feature vectors
61 */
62 public final double distance(final double[] paVector1, final double[] paVector2)
63 {
64 Debug.debug
65 (
66 "MahalanobisDistance.distance() - WARNING: Mahalanobis distance is equivalent " +
67 "to Euclidean as there is no learning of the co-variance matrix."
68 );
69
70 double dDistance = 0.0;
71
72 Matrix oVector1 = new Matrix(paVector1);
73 Matrix oVector2 = new Matrix(paVector2);
74
75 Matrix oDifferenceVector = oVector1.minus(oVector2);
76
77 Matrix oTransposedVector = (Matrix)oDifferenceVector.clone();
78 oTransposedVector.transpose();
79
80 this.oC.inverse();
81
82 dDistance = Math.sqrt(oDifferenceVector.multiply(this.oC).multiply(oTransposedVector).getElement(0,0));
83
84 return dDistance;
85 }
86
87 /**
88 * Retrieves class' revision.
89 * @return revision string
90 * @since 0.3.0
91 */
92 public static String getMARFSourceCodeRevision()
93 {
94 return "$Revision: 1.21 $";
95 }
96 }
97
98 // EOF