当前位置: 首页>>代码示例>>Java>>正文


Java RealMatrix类代码示例

本文整理汇总了Java中org.apache.commons.math.linear.RealMatrix的典型用法代码示例。如果您正苦于以下问题:Java RealMatrix类的具体用法?Java RealMatrix怎么用?Java RealMatrix使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


RealMatrix类属于org.apache.commons.math.linear包,在下文中一共展示了RealMatrix类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getPower

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
/**
 * Returns a real matrix raised to some real power 
 * Currently this method is limited to symmetric matrices only as Commons Math does not support the diagonalization of asymmetric matrices  
 * @param m The <strong>symmetric</strong> matrix to take the power of. 
 * @param p The power to raise to matrix to
 * @return The result
 */
@Override
public DoubleMatrix2D getPower(final Matrix<?> m, final double p) {
  if (m instanceof DoubleMatrix2D) {
    final RealMatrix temp = CommonsMathWrapper.wrap((DoubleMatrix2D) m);
    final EigenDecomposition eigen = new EigenDecompositionImpl(temp, 0.0);
    final double[] rEigenValues = eigen.getRealEigenvalues();
    final double[] iEigenValues = eigen.getImagEigenvalues();
    final int n = rEigenValues.length;
    final double[][] d = new double[n][n];
    for (int i = n - 1; i >= 0; --i) {
      d[i][i] = Math.pow(rEigenValues[i], p);
      if (iEigenValues[i] != 0.0) {
        throw new NotImplementedException("Cannot handle complex eigenvalues in getPower");
      }
    }
    final RealMatrix res = eigen.getV().multiply((new Array2DRowRealMatrix(d)).multiply(eigen.getVT()));
    return CommonsMathWrapper.unwrap(res);
  }
  throw new IllegalArgumentException("Can only find pow of DoubleMatrix2D; have " + m.getClass());
}
 
开发者ID:DevStreet,项目名称:FinanceAnalytics,代码行数:28,代码来源:CommonsMatrixAlgebra.java

示例2: multiply

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
/**
 * {@inheritDoc}
 * The following combinations of input matrices m1 and m2 are allowed:
 * <ul>
 * <li> m1 = 2-D matrix, m2 = 2-D matrix, returns $\mathbf{C} = \mathbf{AB}$
 * <li> m1 = 2-D matrix, m2 = 1-D matrix, returns $\mathbf{C} = \mathbf{A}b$
 * </ul>
 */
@Override
public Matrix<?> multiply(final Matrix<?> m1, final Matrix<?> m2) {
  Validate.notNull(m1, "m1");
  Validate.notNull(m2, "m2");
  Validate.isTrue(!(m1 instanceof DoubleMatrix1D), "Cannot have 1D matrix as first argument");
  if (m1 instanceof DoubleMatrix2D) {
    final RealMatrix t1 = CommonsMathWrapper.wrap((DoubleMatrix2D) m1);
    RealMatrix t2;
    if (m2 instanceof DoubleMatrix1D) {
      t2 = CommonsMathWrapper.wrapAsMatrix((DoubleMatrix1D) m2);
    } else if (m2 instanceof DoubleMatrix2D) {
      t2 = CommonsMathWrapper.wrap((DoubleMatrix2D) m2);
    } else {
      throw new IllegalArgumentException("Can only have 1D or 2D matrix as second argument");
    }
    return CommonsMathWrapper.unwrap(t1.multiply(t2));
  }
  throw new IllegalArgumentException("Can only multiply 2D and 1D matrices");
}
 
开发者ID:DevStreet,项目名称:FinanceAnalytics,代码行数:28,代码来源:CommonsMatrixAlgebra.java

示例3: getResult

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
/**
 * Get the covariance matrix.
 * @return covariance matrix
 */
public RealMatrix getResult() {

    int dimension = sums.length;
    RealMatrixImpl result = new RealMatrixImpl(dimension, dimension);

    if (n > 1) {
        double[][] resultData = result.getDataRef();
        double c = 1.0 / (n * (isBiasCorrected ? (n - 1) : n));
        int k = 0;
        for (int i = 0; i < dimension; ++i) {
            for (int j = 0; j <= i; ++j) {
                double e = c * (n * productsSums[k++] - sums[i] * sums[j]);
                resultData[i][j] = e;
                resultData[j][i] = e;
            }
        }
    }

    return result;

}
 
开发者ID:cacheonix,项目名称:cacheonix-core,代码行数:26,代码来源:VectorialCovariance.java

示例4: CorrelatedRandomVectorGenerator

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
/** Simple constructor.
 * <p>Build a correlated random vector generator from its mean
 * vector and covariance matrix.</p>
 * @param mean expected mean values for all components
 * @param covariance covariance matrix
 * @param small diagonal elements threshold under which  column are
 * considered to be dependent on previous ones and are discarded
 * @param generator underlying generator for uncorrelated normalized
 * components
 * @exception IllegalArgumentException if there is a dimension
 * mismatch between the mean vector and the covariance matrix
 * @exception NotPositiveDefiniteMatrixException if the
 * covariance matrix is not strictly positive definite
 * @exception DimensionMismatchException if the mean and covariance
 * arrays dimensions don't match
 */
public CorrelatedRandomVectorGenerator(double[] mean,
                                       RealMatrix covariance, double small,
                                       NormalizedRandomGenerator generator)
throws NotPositiveDefiniteMatrixException, DimensionMismatchException {

    int order = covariance.getRowDimension();
    if (mean.length != order) {
        throw new DimensionMismatchException(mean.length, order);
    }
    this.mean = (double[]) mean.clone();

    decompose(covariance, small);

    this.generator = generator;
    normalized = new double[rank];

}
 
开发者ID:cacheonix,项目名称:cacheonix-core,代码行数:34,代码来源:CorrelatedRandomVectorGenerator.java

示例5: testBasicStats

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
public void testBasicStats() throws DimensionMismatchException {

        VectorialCovariance stat = new VectorialCovariance(points[0].length, true);
        for (int i = 0; i < points.length; ++i) {
            stat.increment(points[i]);
        }

        assertEquals(points.length, stat.getN());

        RealMatrix c = stat.getResult();
        double[][] refC    = new double[][] {
                { 8.0470, -1.9195, -3.4445},
                {-1.9195,  1.0470,  3.2795},
                {-3.4445,  3.2795, 12.2070}
        };

        for (int i = 0; i < c.getRowDimension(); ++i) {
            for (int j = 0; j <= i; ++j) {
                assertEquals(refC[i][j], c.getEntry(i, j), 1.0e-12);
            }
        }

    }
 
开发者ID:cacheonix,项目名称:cacheonix-core,代码行数:24,代码来源:VectorialCovarianceTest.java

示例6: testMeanAndCovariance

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
public void testMeanAndCovariance() throws DimensionMismatchException {

        VectorialMean meanStat = new VectorialMean(mean.length);
        VectorialCovariance covStat = new VectorialCovariance(mean.length, true);
        for (int i = 0; i < 5000; ++i) {
            double[] v = generator.nextVector();
            meanStat.increment(v);
            covStat.increment(v);
        }

        double[] estimatedMean = meanStat.getResult();
        RealMatrix estimatedCovariance = covStat.getResult();
        for (int i = 0; i < estimatedMean.length; ++i) {
            assertEquals(mean[i], estimatedMean[i], 0.07);
            for (int j = 0; j <= i; ++j) {
                assertEquals(covariance.getEntry(i, j),
                        estimatedCovariance.getEntry(i, j),
                        0.1 * (1.0 + Math.abs(mean[i])) * (1.0 + Math.abs(mean[j])));
            }
        }

    }
 
开发者ID:cacheonix,项目名称:cacheonix-core,代码行数:23,代码来源:CorrelatedRandomVectorGeneratorTest.java

示例7: testMeanAndCorrelation

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
public void testMeanAndCorrelation() throws DimensionMismatchException {

        VectorialMean meanStat = new VectorialMean(mean.length);
        VectorialCovariance covStat = new VectorialCovariance(mean.length, true);
        for (int i = 0; i < 10000; ++i) {
            double[] v = generator.nextVector();
            meanStat.increment(v);
            covStat.increment(v);
        }

        double[] estimatedMean = meanStat.getResult();
        double scale;
        RealMatrix estimatedCorrelation = covStat.getResult();
        for (int i = 0; i < estimatedMean.length; ++i) {
            assertEquals(mean[i], estimatedMean[i], 0.07);
            for (int j = 0; j < i; ++j) {
                scale = standardDeviation[i] * standardDeviation[j];
                assertEquals(0, estimatedCorrelation.getEntry(i, j) / scale, 0.03);
            }
            scale = standardDeviation[i] * standardDeviation[i];
            assertEquals(1, estimatedCorrelation.getEntry(i, i) / scale, 0.025);
        }

    }
 
开发者ID:cacheonix,项目名称:cacheonix-core,代码行数:25,代码来源:UncorrelatedRandomVectorGeneratorTest.java

示例8: computeUserFoldInMatrix

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
/**
  * http://www.slideshare.net/fullscreen/srowen/matrix-factorization/16 
  * @param recentitemInteractions
  * @param productFeaturesInverse
  * @param idMap
  * @return
  */
 private double[][] computeUserFoldInMatrix(double[][] itemFactors) 
 {
 	try
 	{
 		RealMatrix Y = new Array2DRowRealMatrix(itemFactors);
 		RealMatrix YTY = Y.transpose().multiply(Y);
 		RealMatrix YTYInverse = new LUDecompositionImpl(YTY).getSolver().getInverse();

 		return Y.multiply(YTYInverse).getData();
 	}
 	catch (InvalidMatrixException e)
 	{
 		logger.warn("Failed to create inverse of products feature matrix",e);
 		return null;
 	}
}
 
开发者ID:SeldonIO,项目名称:seldon-server,代码行数:24,代码来源:MfFeaturesManager.java

示例9: getResult

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
/**
 * Get the covariance matrix.
 * @return covariance matrix
 */
public RealMatrix getResult() {

    int dimension = sums.length;
    RealMatrix result = MatrixUtils.createRealMatrix(dimension, dimension);

    if (n > 1) {
        double c = 1.0 / (n * (isBiasCorrected ? (n - 1) : n));
        int k = 0;
        for (int i = 0; i < dimension; ++i) {
            for (int j = 0; j <= i; ++j) {
                double e = c * (n * productsSums[k++] - sums[i] * sums[j]);
                result.setEntry(i, j, e);
                result.setEntry(j, i, e);
            }
        }
    }

    return result;

}
 
开发者ID:SpoonLabs,项目名称:astor,代码行数:25,代码来源:VectorialCovariance.java

示例10: testCovarianceConsistency

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
/**
 * Verify that creating correlation from covariance gives same results as
 * direct computation from the original matrix
 */
public void testCovarianceConsistency() throws Exception {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); 
    Covariance covInstance = new Covariance(matrix);
    PearsonsCorrelation corrFromCovInstance = new PearsonsCorrelation(covInstance);
    TestUtils.assertEquals("correlation values", corrInstance.getCorrelationMatrix(),
            corrFromCovInstance.getCorrelationMatrix(), 10E-15);
    TestUtils.assertEquals("p values", corrInstance.getCorrelationPValues(),
            corrFromCovInstance.getCorrelationPValues(), 10E-15);
    TestUtils.assertEquals("standard errors", corrInstance.getCorrelationStandardErrors(),
            corrFromCovInstance.getCorrelationStandardErrors(), 10E-15);
    
    PearsonsCorrelation corrFromCovInstance2 = 
        new PearsonsCorrelation(covInstance.getCovarianceMatrix(), 16);
    TestUtils.assertEquals("correlation values", corrInstance.getCorrelationMatrix(),
            corrFromCovInstance2.getCorrelationMatrix(), 10E-15);
    TestUtils.assertEquals("p values", corrInstance.getCorrelationPValues(),
            corrFromCovInstance2.getCorrelationPValues(), 10E-15);
    TestUtils.assertEquals("standard errors", corrInstance.getCorrelationStandardErrors(),
            corrFromCovInstance2.getCorrelationStandardErrors(), 10E-15);
}
 
开发者ID:SpoonLabs,项目名称:astor,代码行数:26,代码来源:PearsonsCorrelationTest.java

示例11: CorrelatedRandomVectorGenerator

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
/** Simple constructor.
 * <p>Build a null mean random correlated vector generator from its
 * covariance matrix.</p>
 * @param covariance covariance matrix
 * @param small diagonal elements threshold under which  column are
 * considered to be dependent on previous ones and are discarded
 * @param generator underlying generator for uncorrelated normalized
 * components
 * @exception NotPositiveDefiniteMatrixException if the
 * covariance matrix is not strictly positive definite
 */
public CorrelatedRandomVectorGenerator(RealMatrix covariance, double small,
                                       NormalizedRandomGenerator generator)
throws NotPositiveDefiniteMatrixException {

    int order = covariance.getRowDimension();
    mean = new double[order];
    for (int i = 0; i < order; ++i) {
        mean[i] = 0;
    }

    decompose(covariance, small);

    this.generator = generator;
    normalized = new double[rank];

}
 
开发者ID:SpoonLabs,项目名称:astor,代码行数:28,代码来源:CorrelatedRandomVectorGenerator.java

示例12: testLongly

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
/**
 * Test Longley dataset against R.
 */
@Override
public void testLongly() throws Exception {
    RealMatrix matrix = createRealMatrix(longleyData, 16, 7);
    SpearmansCorrelation corrInstance = new SpearmansCorrelation(matrix);
    RealMatrix correlationMatrix = corrInstance.getCorrelationMatrix();
    double[] rData = new double[] {
            1, 0.982352941176471, 0.985294117647059, 0.564705882352941, 0.2264705882352941, 0.976470588235294,
            0.976470588235294, 0.982352941176471, 1, 0.997058823529412, 0.664705882352941, 0.2205882352941176,
            0.997058823529412, 0.997058823529412, 0.985294117647059, 0.997058823529412, 1, 0.638235294117647,
            0.2235294117647059, 0.9941176470588236, 0.9941176470588236, 0.564705882352941, 0.664705882352941,
            0.638235294117647, 1, -0.3411764705882353, 0.685294117647059, 0.685294117647059, 0.2264705882352941,
            0.2205882352941176, 0.2235294117647059, -0.3411764705882353, 1, 0.2264705882352941, 0.2264705882352941,
            0.976470588235294, 0.997058823529412, 0.9941176470588236, 0.685294117647059, 0.2264705882352941, 1, 1,
            0.976470588235294, 0.997058823529412, 0.9941176470588236, 0.685294117647059, 0.2264705882352941, 1, 1
    };
    TestUtils.assertEquals("Spearman's correlation matrix", createRealMatrix(rData, 7, 7), correlationMatrix, 10E-15);
}
 
开发者ID:SpoonLabs,项目名称:astor,代码行数:21,代码来源:SpearmansRankCorrelationTest.java

示例13: testOverdetermined

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
public void testOverdetermined() {
    final Random r    = new Random(5559252868205245l);
    int          p    = (7 * BlockRealMatrix.BLOCK_SIZE) / 4;
    int          q    = (5 * BlockRealMatrix.BLOCK_SIZE) / 4;
    RealMatrix   a    = createTestMatrix(r, p, q);
    RealMatrix   xRef = createTestMatrix(r, q, BlockRealMatrix.BLOCK_SIZE + 3);

    // build a perturbed system: A.X + noise = B
    RealMatrix b = a.multiply(xRef);
    final double noise = 0.001;
    b.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() {
        @Override
        public double visit(int row, int column, double value) {
            return value * (1.0 + noise * (2 * r.nextDouble() - 1));
        }
    });

    // despite perturbation, the least square solution should be pretty good
    RealMatrix x = new QRDecompositionImpl(a).getSolver().solve(b);
    assertEquals(0, x.subtract(xRef).getNorm(), 0.01 * noise * p * q);

}
 
开发者ID:SpoonLabs,项目名称:astor,代码行数:23,代码来源:QRSolverTest.java

示例14: CorrelatedRandomVectorGenerator

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
/** Simple constructor.
 * <p>Build a correlated random vector generator from its mean
 * vector and covariance matrix.</p>
 * @param mean expected mean values for all components
 * @param covariance covariance matrix
 * @param small diagonal elements threshold under which  column are
 * considered to be dependent on previous ones and are discarded
 * @param generator underlying generator for uncorrelated normalized
 * components
 * @exception IllegalArgumentException if there is a dimension
 * mismatch between the mean vector and the covariance matrix
 * @exception NotPositiveDefiniteMatrixException if the
 * covariance matrix is not strictly positive definite
 * @exception DimensionMismatchException if the mean and covariance
 * arrays dimensions don't match
 */
public CorrelatedRandomVectorGenerator(double[] mean,
                                       RealMatrix covariance, double small,
                                       NormalizedRandomGenerator generator)
throws NotPositiveDefiniteMatrixException, DimensionMismatchException {

    int order = covariance.getRowDimension();
    if (mean.length != order) {
        throw new DimensionMismatchException(mean.length, order);
    }
    this.mean = mean.clone();

    decompose(covariance, small);

    this.generator = generator;
    normalized = new double[rank];

}
 
开发者ID:SpoonLabs,项目名称:astor,代码行数:34,代码来源:CorrelatedRandomVectorGenerator.java

示例15: testSwissFertility

import org.apache.commons.math.linear.RealMatrix; //导入依赖的package包/类
/**
 * Test R Swiss fertility dataset against R.
 */
public void testSwissFertility() throws Exception {
     RealMatrix matrix = createRealMatrix(swissData, 47, 5);
     PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix);
     RealMatrix correlationMatrix = corrInstance.getCorrelationMatrix();
     double[] rData = new double[] {
           1.0000000000000000, 0.3530791836199747, -0.6458827064572875, -0.6637888570350691,  0.4636847006517939,
             0.3530791836199747, 1.0000000000000000,-0.6865422086171366, -0.6395225189483201, 0.4010950530487398,
            -0.6458827064572875, -0.6865422086171366, 1.0000000000000000, 0.6984152962884830, -0.5727418060641666,
            -0.6637888570350691, -0.6395225189483201, 0.6984152962884830, 1.0000000000000000, -0.1538589170909148,
             0.4636847006517939, 0.4010950530487398, -0.5727418060641666, -0.1538589170909148, 1.0000000000000000
     };
     TestUtils.assertEquals("correlation matrix", createRealMatrix(rData, 5, 5), correlationMatrix, 10E-15);

     double[] rPvalues = new double[] {
             0.01491720061472623,
             9.45043734069043e-07, 9.95151527133974e-08,
             3.658616965962355e-07, 1.304590105694471e-06, 4.811397236181847e-08,
             0.001028523190118147, 0.005204433539191644, 2.588307925380906e-05, 0.301807756132683
     };
     RealMatrix rPMatrix = createLowerTriangularRealMatrix(rPvalues, 5);
     fillUpper(rPMatrix, 0d);
     TestUtils.assertEquals("correlation p values", rPMatrix, corrInstance.getCorrelationPValues(), 10E-15);
}
 
开发者ID:SpoonLabs,项目名称:astor,代码行数:27,代码来源:PearsonsCorrelationTest.java


注:本文中的org.apache.commons.math.linear.RealMatrix类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。