马氏距离

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);

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值