Example usage for org.apache.commons.math3.linear RealMatrix getRowDimension

List of usage examples for org.apache.commons.math3.linear RealMatrix getRowDimension

Introduction

In this page you can find the example usage for org.apache.commons.math3.linear RealMatrix getRowDimension.

Prototype

int getRowDimension();

Source Link

Document

Returns the number of rows in the matrix.

Usage

From source file:com.clust4j.algo.preprocess.MeanCenterer.java

@Override
public MeanCenterer fit(RealMatrix data) {
    synchronized (fitLock) {
        final int m = data.getRowDimension();
        final int n = data.getColumnDimension();

        // need to mean center...
        this.means = new double[n];
        final double[][] y = data.getData();

        // First pass, compute mean...
        for (int j = 0; j < n; j++) {
            for (int i = 0; i < m; i++) {
                means[j] += y[i][j];/*  w w  w  .  j  a  va  2  s  .c o  m*/

                // if last:
                if (i == m - 1) {
                    means[j] /= (double) m;
                }
            }
        }

        return this;
    }
}

From source file:com.clust4j.algo.preprocess.MinMaxScaler.java

@Override
public MinMaxScaler fit(RealMatrix X) {
    synchronized (fitLock) {
        final int m = X.getRowDimension();
        final int n = X.getColumnDimension();

        this.mins = new double[n];
        this.maxes = new double[n];
        double[][] data = X.getData();

        for (int col = 0; col < n; col++) {
            double mn = Double.POSITIVE_INFINITY, mx = Double.NEGATIVE_INFINITY;

            for (int row = 0; row < m; row++) {
                mn = FastMath.min(mn, data[row][col]);
                mx = FastMath.max(mx, data[row][col]);
            }//from  w w  w. j  av a 2  s. c o  m

            this.mins[col] = mn;
            this.maxes[col] = mx;
        }

        return this;
    }
}

From source file:edu.cudenver.bios.matrix.test.TestMatrixOrthonormalization.java

/**
 * Verify that the A = QxR for the Q, R matrices produced by the
 * orthonormalization//from  w w w.  ja v a  2s  . c o m
 */
public void testQRshouldBeA() {
    RealMatrix Q = norm.getQ();
    RealMatrix R = norm.getR();

    // verify that QR = A
    RealMatrix shouldBeOriginalMatrix = Q.multiply(R);
    // Make sure that QR has same dimension as original A matrix
    if (shouldBeOriginalMatrix.getRowDimension() != data.length
            || shouldBeOriginalMatrix.getColumnDimension() != data[0].length) {
        fail();
    }
    // make sure elements of QR match elements of A (within tolerance)
    for (int r = 0; r < shouldBeOriginalMatrix.getRowDimension(); r++) {
        for (int c = 0; c < shouldBeOriginalMatrix.getColumnDimension(); c++) {
            if (Precision.compareTo(shouldBeOriginalMatrix.getEntry(r, c), data[r][c], TOLERANCE) != 0)
                fail();
        }
    }

    assertTrue(true);
}

From source file:com.clust4j.algo.AbstractPartitionalClusterer.java

public AbstractPartitionalClusterer(RealMatrix data, BaseClustererParameters planner, final int k) {
    super(data, planner);

    if (k < 1)
        error(new IllegalArgumentException("k must exceed 0"));
    if (k > data.getRowDimension())
        error(new IllegalArgumentException("k exceeds number of records"));

    this.k = this.singular_value ? 1 : k;
    if (this.singular_value && k != 1) {
        warn("coerced k to 1 due to equality of all elements in input matrix");
    }/*from w ww  . jav a  2  s.c o m*/
}

From source file:eagle.security.userprofile.model.kde.UserProfileKDEModeler.java

private void computeProbabilityDensityEstimation(RealMatrix inputMat) {

    probabilityEstimation = new double[inputMat.getRowDimension()];
    for (int i = 0; i < probabilityEstimation.length; i++)
        probabilityEstimation[i] = 1.0;/*from www. j  av  a  2 s  .  co  m*/

    for (int i = 0; i < inputMat.getRowDimension(); i++) {
        for (int j = 0; j < inputMat.getColumnDimension(); j++) {
            if (statistics[j].getStddev() > 0) {
                double stddev = statistics[j].getStddev();
                double mean = statistics[j].getMean();
                double sqrt2PI = Math.sqrt(2.0 * Math.PI);
                double denominatorFirstPart = sqrt2PI * stddev;
                double squareMeanNormal = Math.pow((inputMat.getEntry(i, j) - mean), 2);
                double twoPowStandardDev = Math.pow(stddev, 2);
                double twoTimesTwoPowStandardDev = 2.0 * twoPowStandardDev;
                probabilityEstimation[i] *= ((1.00 / denominatorFirstPart)
                        * (Math.exp(-(squareMeanNormal / twoTimesTwoPowStandardDev))));
            }
        }
    }

    java.util.List<Double> listProb = new ArrayList<Double>();
    for (int i = 0; i < probabilityEstimation.length; i++) {
        probabilityEstimation[i] = Math.log10(probabilityEstimation[i]);
        listProb.add(probabilityEstimation[i]);
    }

    Collections.sort(listProb);
    int i = 0;
    for (double d : listProb)
        probabilityEstimation[i++] = d;

    minProbabilityEstimate = probabilityEstimation[probabilityEstimation.length - 1];
    maxProbabilityEstimate = probabilityEstimation[0];

    int len = probabilityEstimation.length;
    int nintyFivePercentIndex = (int) Math.round(0.05 * len);
    int medianPercentIndex = (int) Math.round(0.5 * len);
    if (medianPercentIndex >= len)
        medianProbabilityEstimate = probabilityEstimation[medianPercentIndex - 1];
    else
        medianProbabilityEstimate = probabilityEstimation[medianPercentIndex];
    nintyFivePercentileEstimate = probabilityEstimation[nintyFivePercentIndex];
}

From source file:fi.smaa.jsmaa.model.MultivariateGaussianCriterionMeasurement.java

private RealMatrix setCovarianceMatrixInternal(RealMatrix newValue) {
    if (newValue.getRowDimension() != alternatives.size()
            || newValue.getColumnDimension() != alternatives.size()) {
        throw new IllegalArgumentException(
                "Incorrect matrix size " + newValue.getRowDimension() + "x" + newValue.getColumnDimension()
                        + ", expected " + alternatives.size() + "x" + alternatives.size());
    }/*from   w ww . j  av a2s.  c o m*/
    try {
        mvgGenerator = random == null ? new MultivariateGaussianGenerator(meanVector, newValue, null)
                : random.createMultivariateGaussian(meanVector, newValue);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
    RealMatrix oldValue = covarianceMatrix;
    covarianceMatrix = newValue;
    return oldValue;
}

From source file:com.clust4j.algo.preprocess.StandardScaler.java

@Override
public StandardScaler fit(RealMatrix data) {
    synchronized (fitLock) {
        final int m = data.getRowDimension();
        final int n = data.getColumnDimension();

        if (m < 2)
            throw new IllegalArgumentException(
                    "cannot " + "meaningfully compute standard deviation " + "on fewer than two observations");

        // need to mean center...
        this.means = new double[n];
        this.stdevs = new double[n];

        final double[][] X = data.getData();

        for (int col = 0; col < n; col++) {
            double var, std, mn;
            double sumSq = 0.0;
            double sum = 0.0;

            for (int row = 0; row < m; row++) {
                sumSq += X[row][col] * X[row][col];
                sum += X[row][col];/*from   w  w  w . ja v a2 s.  co  m*/
            }

            /*
             * A naive algorithm to calculate the estimated variance (1M):
             * 
             * Let n = 0, Sum = 0, SumSq = 0 
             * For each datum x: 
             *   n = n + 1 
             *   Sum = Sum + x 
             *   SumSq = SumSq + x * x 
             * Var = (SumSq - (Sum * Sum) / n) / (n - 1)
             * 
             * @see https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
             */
            var = (sumSq - (sum * sum) / (double) m) / ((double) m - 1.0);
            std = m < 2 ? Double.NaN : FastMath.sqrt(var);
            mn = sum / (double) m;

            means[col] = mn;
            stdevs[col] = std;
        }

        return this;
    }
}

From source file:net.myrrix.online.factorizer.als.NegativeInputTest.java

@Test
public void testALS() throws Exception {

    FastByIDMap<FastByIDFloatMap> byRow = new FastByIDMap<FastByIDFloatMap>();
    FastByIDMap<FastByIDFloatMap> byCol = new FastByIDMap<FastByIDFloatMap>();

    // Octave: R = [ 1 1 1 0 ; 0 -1 1 1 ; -1 0 0 1 ]
    MatrixUtils.addTo(0, 0, 1.0f, byRow, byCol);
    MatrixUtils.addTo(0, 1, 1.0f, byRow, byCol);
    MatrixUtils.addTo(0, 2, 1.0f, byRow, byCol);
    MatrixUtils.addTo(1, 1, -1.0f, byRow, byCol);
    MatrixUtils.addTo(1, 2, 1.0f, byRow, byCol);
    MatrixUtils.addTo(1, 3, 1.0f, byRow, byCol);
    MatrixUtils.addTo(2, 0, -1.0f, byRow, byCol);
    MatrixUtils.addTo(2, 3, 1.0f, byRow, byCol);

    // Octave: Y = [ 0.1 0.2 ; 0.2 0.5 ; 0.3 0.1 ; 0.2 0.2 ];
    FastByIDMap<float[]> previousY = new FastByIDMap<float[]>();
    previousY.put(0L, new float[] { 0.1f, 0.2f });
    previousY.put(1L, new float[] { 0.2f, 0.5f });
    previousY.put(2L, new float[] { 0.3f, 0.1f });
    previousY.put(3L, new float[] { 0.2f, 0.2f });

    MatrixFactorizer als = new AlternatingLeastSquares(byRow, byCol, 2, 0.0001, 40);
    als.setPreviousY(previousY);/*from w w  w .  j a v a  2  s  .  co m*/
    als.call();

    RealMatrix product = MatrixUtils.multiplyXYT(als.getX(), als.getY());

    StringBuilder productString = new StringBuilder(100);
    for (int row = 0; row < product.getRowDimension(); row++) {
        productString.append('\n').append(Arrays.toString(doubleToFloatArray(product.getRow(row))));
    }
    log.info("{}", productString);

    assertArrayEquals(new float[] { 0.899032f, 0.900162f, 0.990150f, -0.026642f }, product.getRow(0));
    assertArrayEquals(new float[] { 0.181214f, 0.089988f, 0.787198f, 1.012226f }, product.getRow(1));
    assertArrayEquals(new float[] { -0.104165f, -0.178240f, 0.360391f, 0.825856f }, product.getRow(2));
}

From source file:com.joptimizer.functions.SDPLogarithmicBarrier.java

/**
 * Build the genaralized logarithmic barrier function for the constraint
 * <br>G + Sum[x_i * F_i(x),i] < 0,  F_i, G symmetric matrices
 * @param Fi symmetric matrices//  www.j a  va 2  s . c o  m
 * @param G symmetric matrix
 */
public SDPLogarithmicBarrier(List<double[][]> FiMatrixList, double[][] GMatrix) {
    int dim = FiMatrixList.size();
    this.Fi = new RealMatrix[dim];
    RealMatrix Gg = new Array2DRowRealMatrix(GMatrix);
    if (Gg.getRowDimension() != Gg.getColumnDimension()) {
        throw new IllegalArgumentException("All matrices must be symmetric");
    }
    this.G = Gg;
    int pp = G.getRowDimension();
    for (int i = 0; i < dim; i++) {
        double[][] FiMatrix = FiMatrixList.get(i);
        RealMatrix Fii = new Array2DRowRealMatrix(FiMatrix);
        if (Fii.getRowDimension() != Fii.getColumnDimension() || pp != Fii.getRowDimension()) {
            throw new IllegalArgumentException("All matrices must be symmetric and with the same dimensions");
        }
        this.Fi[i] = Fii;
    }
    this.dim = dim;
    this.p = pp;
}

From source file:eagle.security.userprofile.model.kde.UserProfileKDEModeler.java

@Override
public List<UserProfileKDEModel> generate(String site, String user, RealMatrix matrix) {
    LOG.info(String.format("Receive aggregated user activity matrix: %s size: %s x %s", user,
            matrix.getRowDimension(), matrix.getColumnDimension()));
    computeStats(matrix);//  www.j  a  v  a 2  s .co  m
    computeProbabilityDensityEstimation(matrix);
    UserProfileKDEModel userprofileKDEModel = new UserProfileKDEModel(System.currentTimeMillis(), site, user,
            statistics, minProbabilityEstimate, maxProbabilityEstimate, nintyFivePercentileEstimate,
            medianProbabilityEstimate);
    return Arrays.asList(userprofileKDEModel);
}