Example usage for org.apache.commons.math3.stat.correlation StorelessCovariance StorelessCovariance

List of usage examples for org.apache.commons.math3.stat.correlation StorelessCovariance StorelessCovariance

Introduction

In this page you can find the example usage for org.apache.commons.math3.stat.correlation StorelessCovariance StorelessCovariance.

Prototype

public StorelessCovariance(final int dim, final boolean biasCorrected) 

Source Link

Document

Create a covariance matrix with a given number of rows and columns and the indicated bias correction.

Usage

From source file:org.esa.snap.classification.gpf.maximumlikelihood.MaximumLikelihood.java

public void buildClassifier(Dataset data) {

    meanVector = new HashMap<>();
    invCov = new HashMap<>();
    determinant = new HashMap<>();

    // 1/[(2 PI)^(N/2)]
    constantTerm = 1.0 / (Math.pow(2.0 * Math.PI, (double) data.noAttributes() / 2.0));
    //SystemUtils.LOG.info("MaximumLikelihood: constantTerm = " + constantTerm);

    Map<Object, StorelessCovariance> covarianceMap = new HashMap<>();
    Map<Object, Integer> cntMap = new HashMap<>();
    for (Object o : data.classes()) {
        covarianceMap.put(o, new StorelessCovariance(data.noAttributes(), biasCorrected));
        meanVector.put(o, new double[data.noAttributes()]);
        cntMap.put(o, 0);//from w w w. ja va 2  s .  c o m
    }

    final double[] features = new double[data.noAttributes()];
    Object classVal;
    double featureVal;
    for (Instance i : data) {
        classVal = i.classValue();
        for (int j = 0; j < features.length; j++) {
            featureVal = i.value(j);
            features[j] = featureVal;
            meanVector.get(classVal)[j] += featureVal;
        }
        covarianceMap.get(classVal).increment(features);
        cntMap.replace(classVal, cntMap.get(classVal) + 1);
    }

    for (Object o : covarianceMap.keySet()) {
        for (int i = 0; i < data.noAttributes(); i++) {
            meanVector.get(o)[i] /= cntMap.get(o);
        }
        try {
            final RealMatrix m1 = covarianceMap.get(o).getCovarianceMatrix();
            final Jama.Matrix m2 = new Jama.Matrix(m1.getData());
            invCov.put(o, m2.inverse());
            determinant.put(o, Math.abs(m2.det()));
        } catch (Exception e) {
            SystemUtils.LOG
                    .info("MaximumLikelihood.buildClassifier: cannot classify " + o + ' ' + e.getMessage());
        }
    }
}