import org.apache.commons.math3.linear.LUDecomposition; import org.apache.commons.math3.linear.MatrixUtils; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.stat.correlation.StorelessCovariance; import smile.math.distance.MahalanobisDistance; import java.util.Arrays; import static org.junit.Assert.assertEquals; /** * @Author xlj * @Date 2018/2/3 17:06 */ public class MatrixUtilsTest { private static RealMatrix invcov = null; public static void main(String[] args) { double[] a = {64, 580, 29}; double[] b = {66, 570, 33}; double[] c = {68, 590, 37}; double[] d = {69, 660, 46}; double[] e = {73, 600, 55}; double[][] dataset = {a, b, c, d, e}; double[] center = new double[]{68, 600, 40};//abcde平均值 double[] x = new double[]{66, 640, 44}; double distance = getDistance(dataset, center, x); System.out.println(distance); } public static double getDistance(double[][] dataset, double[] center, double[] x) { StorelessCovariance sc = new StorelessCovariance(3); // Feed the StorelessCovariance for (int i = 0; i < dataset.length; i++) sc.increment(dataset[i]); // Set the covariance value RealMatrix temp = sc.getCovarianceMatrix(); // But this matrix is always used inverted. Do it now. invcov = new LUDecomposition(temp).getSolver().getInverse(); return distance(center, x); } public static double distance(double[] centroid, double[] data) { // If the arrays are the same, the distance is 0.0 if (Arrays.equals(centroid, data)) { return 0.0; } // Create a new array with the difference between the two arrays double[] diff = new double[centroid.length]; for (int i = 0; i < centroid.length; i++) { diff[i] = centroid[i] - data[i]; } // Left-hand side of the equation: vector * invcov^-1 double[] left = invcov.preMultiply(diff); // Compute the dot product of both vectors double res = 0.0; for (int i = 0; i < diff.length; i++) { res += left[i] * diff[i]; } return Math.sqrt(res); } }
马氏距离
最新推荐文章于 2021-02-28 09:22:57 发布