nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dimensionalityreduction/PCA.java
public static INDArray[] covarianceMatrix(INDArray in) {
        long dlength = in.rows();
        long vlength = in.columns();

        INDArray sum = Nd4j.create(vlength);
        INDArray product = Nd4j.create(vlength, vlength);

        for (int i = 0; i < vlength; i++)
            sum.getColumn(i).assign(in.getColumn(i).sumNumber().doubleValue() / dlength);

        for (int i = 0; i < dlength; i++) {
            INDArray dx1 = in.getRow(i).sub(sum);
            product.addi(dx1.reshape(vlength, 1).mmul(dx1.reshape(1, vlength)));
        }
        product.divi(dlength);
        return new INDArray[] {product, sum};
    }
public static INDArray[] covarianceMatrix(INDArray in) {
        long dlength = in.rows();
        long vlength = in.columns();

        INDArray sum = Nd4j.create(vlength);
        INDArray product = Nd4j.create(vlength, vlength);

        for (int i = 0; i < vlength; i++)
            sum.getColumn(i).assign(in.getColumn(i).sumNumber().doubleValue() / dlength);

        for (int i = 0; i < dlength; i++) {
            INDArray dx1 = in.getRow(i).sub(sum);
            product.addi(dx1.reshape(vlength, 1).mmul(dx1.reshape(1, vlength)));
        }
        product.divi(dlength);
        return new INDArray[] {product, sum};
    }
public static INDArray [ ] covarianceMatrix ( INDArray in ) { long dlength = in . rows ( ) ; long vlength = in . columns ( ) ; INDArray sum = Nd4j . create ( vlength ) ; INDArray product = Nd4j . create ( vlength , vlength ) ; for ( int i = 0 ; i < vlength ; i ++ ) sum . getColumn ( i ) . assign ( in . getColumn ( i ) . sumNumber ( ) . doubleValue ( ) / dlength ) ; for ( int i = 0 ; i < dlength ; i ++ ) { INDArray dx1 = in . getRow ( i ) . sub ( sum ) ; product . addi ( dx1 . reshape ( vlength , 1 ) . mmul ( dx1 . reshape ( 1 , vlength ) ) ) ; } product . divi ( dlength ) ; return new INDArray [ ] { product , sum } ; }
Returns the covariance matrix of a data set of many records, each with N features.
It also returns the average values, which are usually going to be important since in this
version, all modes are centered around the mean.  It's a matrix that has elements that are
expressed as average dx_i * dx_j (used in procedure) or average x_i * x_j - average x_i * average x_j

@param in A matrix of vectors of fixed length N (N features) on each row
@return INDArray[2], an N x N covariance matrix is element 0, and the average values is element 1.
Returns the covariance matrix of a data set of many records each with N features . It also returns the average values which are usually going to be important since in this version all modes are centered around the mean . It s a matrix that has elements that are expressed as average dx_i * dx_j ( used in procedure ) or average x_i * x_j - average x_i * average x_j