0

有没有办法计算马氏距离省略org.apache.mahout使用(仅使用org.apache.commons.math3)?

4

1 回答 1

0

仅使用org.apache.commons.math3方法的方法如下:

import org.apache.commons.math3.linear.ArrayRealVector;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.RealVector;

...

double[][] data = new double[][]{
...
};


RealMatrix covarianceMatrix = new Covariance(data, false).getCovarianceMatrix();
RealMatrix inverseCovarianceMatrix = MatrixUtils.inverse(covarianceMatrix);

VectorialMean Mean = new VectorialMean(covarianceMatrix.getColumnDimension());
Arrays.stream(data).forEach(x -> Mean.increment(x));
RealVector meanVector = new ArrayRealVector(Mean.getResult());


//Calculate Mahalanobis distance for first row
RealVector v = new ArrayRealVector(data[0]);

double distance = Math.sqrt(v.minus(meanVector).dot(Algebra.mult(inverseCovarianceMatrix, v.minus(meanVector))));

要使用的类,而不是org.apache.mahout.common.distance.MahalanobisDistanceMeasure

package Demo;

import org.apache.commons.math3.linear.MatrixUtils;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.RealVector;

public class MahalanobisDistanceMeasure {

    RealMatrix inverseCovarianceMatrix;

    RealVector meanVector;

    public void setCovarianceMatrix(RealMatrix covarianceMatrix) {
        this.inverseCovarianceMatrix = MatrixUtils.inverse(covarianceMatrix);
    }

    public void setMeanVector(RealVector meanVector) {
        this.meanVector = meanVector;
    }

    public double distance(RealVector vector) {
        RealVector subtract = vector.subtract(meanVector);

        return Math.sqrt(subtract.dotProduct(inverseCovarianceMatrix.operate(subtract)));
    }
}

类的用法:

MahalanobisDistanceMeasure measure = new MahalanobisDistanceMeasure();
measure.setCovarianceMatrix(covarianceMatrix);
measure.setMeanVector(meanVector);

double distance = measure.distance(vector);
于 2021-09-18T10:39:03.353 回答