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


Java RealMatrix类代码示例

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


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

示例1: getTruncatedSVD

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
/**
 * truncated SVD as taken from http://stackoverflow.com/questions/19957076/best-way-to-compute-a-truncated-singular-value-decomposition-in-java
 */
static double[][] getTruncatedSVD(double[][] matrix, final int k) {
  SingularValueDecomposition svd = new SingularValueDecomposition(MatrixUtils.createRealMatrix(matrix));

  double[][] truncatedU = new double[svd.getU().getRowDimension()][k];
  svd.getU().copySubMatrix(0, truncatedU.length - 1, 0, k - 1, truncatedU);

  double[][] truncatedS = new double[k][k];
  svd.getS().copySubMatrix(0, k - 1, 0, k - 1, truncatedS);

  double[][] truncatedVT = new double[k][svd.getVT().getColumnDimension()];
  svd.getVT().copySubMatrix(0, k - 1, 0, truncatedVT[0].length - 1, truncatedVT);

  RealMatrix approximatedSvdMatrix = (MatrixUtils.createRealMatrix(truncatedU)).multiply(
      MatrixUtils.createRealMatrix(truncatedS)).multiply(MatrixUtils.createRealMatrix(truncatedVT));

  return approximatedSvdMatrix.getData();
}
 
开发者ID:tteofili,项目名称:par2hier,代码行数:21,代码来源:Par2HierUtils.java

示例2: apacheCommonsExample

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
public void apacheCommonsExample() {
    double[][] A = {
        {0.1950, 0.0311},
        {0.3588, 0.2203},
        {0.1716, 0.5931},
        {0.2105, 0.3242}};

    double[][] B = {
        {0.0502, 0.9823, 0.9472},
        {0.5732, 0.2694, 0.916}};

    RealMatrix aRealMatrix = new Array2DRowRealMatrix(A);
    RealMatrix bRealMatrix = new Array2DRowRealMatrix(B);

    RealMatrix cRealMatrix = aRealMatrix.multiply(bRealMatrix);
    System.out.println();
    for (int i = 0; i < cRealMatrix.getRowDimension(); i++) {
        System.out.println(cRealMatrix.getRowVector(i));
    }
}
 
开发者ID:PacktPublishing,项目名称:Machine-Learning-End-to-Endguide-for-Java-developers,代码行数:21,代码来源:MathExamples.java

示例3: testRealMatrixUpdates

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
@Test()
public void testRealMatrixUpdates() {
    final DataFrame<String,String> frame = TestDataFrames.random(double.class, 100, 100);
    final RealMatrix matrix = frame.export().asApacheMatrix();
    Assert.assertEquals(frame.rowCount(), matrix.getRowDimension(), "Row count matches");
    Assert.assertEquals(frame.colCount(), matrix.getColumnDimension(), "Column count matches");
    for (int i=0; i<frame.rowCount(); ++i) {
        for (int j = 0; j<frame.colCount(); ++j) {
            matrix.setEntry(i, j, Math.random());
        }
    }
    for (int i=0; i<frame.rowCount(); ++i) {
        for (int j = 0; j<frame.colCount(); ++j) {
            final double v1 = frame.data().getDouble(i, j);
            final double v2 = matrix.getEntry(i, j);
            Assert.assertEquals(v1, v2, "Values match at " + i + "," + j);
        }
    }
}
 
开发者ID:zavtech,项目名称:morpheus-core,代码行数:20,代码来源:ExportTests.java

示例4: createX

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
/**
 * Creates the X design matrix for this regression model
 * @return  the X design matrix
 */
RealMatrix createX() {
    final int n = frame.rows().count();
    final int offset = hasIntercept() ? 1 : 0;
    final int p = hasIntercept() ? regressors.size() + 1 : regressors.size();
    final int[] colIndexes = regressors.stream().mapToInt(k -> frame.cols().ordinalOf(k)).toArray();
    final RealMatrix x = new Array2DRowRealMatrix(n, p);
    for (int i = 0; i < n; ++i) {
        x.setEntry(i, 0, 1d);
        for (int j = offset; j < p; ++j) {
            final double value = frame.data().getDouble(i, colIndexes[j - offset]);
            x.setEntry(i, j, value);
        }
    }
    return x;
}
 
开发者ID:zavtech,项目名称:morpheus-core,代码行数:20,代码来源:XDataFrameLeastSquares.java

示例5: testPseudoInverse

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
@Test(dataProvider = "styles")
public void testPseudoInverse(DataFrameAlgebra.Lib lib, boolean parallel) {
    DataFrameAlgebra.LIBRARY.set(lib);
    final DataFrame<Integer,String> source = DataFrame.read().csv("./src/test/resources/pca/svd/poppet-svd-eigenvectors.csv");
    Array.of(20, 77, 95, 135, 233, 245).forEach(count -> {
        final DataFrame<Integer,String> frame = source.cols().select(col -> col.ordinal() < count);
        final DataFrame<Integer,Integer> inverse = frame.inverse();
        final RealMatrix matrix = new QRDecomposition(toMatrix(frame)).getSolver().getInverse();
        assertEquals(inverse, matrix);
    });
}
 
开发者ID:zavtech,项目名称:morpheus-core,代码行数:12,代码来源:AlgebraTests.java

示例6: multiplyElementWise

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
public static RealMatrix multiplyElementWise(final RealMatrix matrix1,
        final RealMatrix matrix2) {
    if (matrix1.getRowDimension() != matrix2.getRowDimension() || matrix1
            .getColumnDimension() != matrix2.getColumnDimension()) {
        throw new IllegalArgumentException(
                "The matrices must be of the same dimensions!");
    }

    final RealMatrix result = matrix1.createMatrix(
            matrix1.getRowDimension(), matrix1.getColumnDimension());

    for (int r = 0; r < matrix1.getRowDimension(); r++) {
        for (int c = 0; c < matrix1.getColumnDimension(); c++) {
            result.setEntry(r, c,
                    matrix1.getEntry(r, c) * matrix2.getEntry(r, c));
        }
    }

    return result;
}
 
开发者ID:knime,项目名称:knime-activelearning,代码行数:21,代码来源:MatrixFunctions.java

示例7: calculateRowVectorDistances

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
public static double[]
        calculateRowVectorDistances(final RealMatrix matrix) {
    final double[] distances = new double[matrix.getRowDimension()
            * (matrix.getRowDimension() - 1) / 2];
    int count = 1;
    int iterator = 0;
    for (int r1 = 0; r1 < matrix.getRowDimension(); r1++) {
        for (int r2 = count; r2 < matrix.getRowDimension(); r2++) {
            distances[iterator++] = matrix.getRowVector(r1)
                    .getDistance(matrix.getRowVector(r2));
        }
        count++;
    }

    return distances;
}
 
开发者ID:knime,项目名称:knime-activelearning,代码行数:17,代码来源:MatrixFunctions.java

示例8: centerKernelMatrix

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
private static RealMatrix
        centerKernelMatrix(final RealMatrix kernelMatrix) {
    // get size of kernelMatrix
    final int n = kernelMatrix.getRowDimension();

    // get mean values for each row/column
    final RealVector columnMeans =
            MatrixFunctions.columnMeans(kernelMatrix);
    final double matrixMean = MatrixFunctions.mean(kernelMatrix);

    RealMatrix centeredKernelMatrix = kernelMatrix.copy();

    for (int k = 0; k < n; k++) {
        centeredKernelMatrix.setRowVector(k,
                centeredKernelMatrix.getRowVector(k).subtract(columnMeans));
        centeredKernelMatrix.setColumnVector(k, centeredKernelMatrix
                .getColumnVector(k).subtract(columnMeans));
    }

    centeredKernelMatrix = centeredKernelMatrix.scalarAdd(matrixMean);

    return centeredKernelMatrix;
}
 
开发者ID:knime,项目名称:knime-activelearning,代码行数:24,代码来源:KNFST.java

示例9: makeDataMatrix

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
private RealMatrix makeDataMatrix(List<double[]> X, double[] meanX) {
	if (meanX == null) {
		return makeDataMatrix(X);
	}
	final int m = X.size();
	final int n = X.get(0).length;
	RealMatrix M = MatrixUtils.createRealMatrix(n, m);
	RealVector mean = MatrixUtils.createRealVector(meanX);
	int i = 0;
	for (double[] x : X) {
		RealVector xi = MatrixUtils.createRealVector(x).subtract(mean);
		M.setColumnVector(i, xi);
		i++;
	}
	return M;
}
 
开发者ID:imagingbook,项目名称:imagingbook-common,代码行数:17,代码来源:ProcrustesFit.java

示例10: main

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
public static void main(String[] args) {
  // test wishart
  double[][] s = {{2.0,1.0,0.0},{1.0,2.0,1.0},{0.0,1.0,2.0}};
  RealMatrix S = new Array2DRowRealMatrix(s);
  Cholesky C = new Cholesky(S);
  double df = 2.4;
  RealMatrix sum = new Array2DRowRealMatrix(3,3);
  for (int i=0; i<100000; i++) {
    RealMatrix sample = generator.nextWishart(df, C);
    sum = sum.add(sample);
  }
  sum = sum.scalarMultiply(1.0/100000.0);
  System.out.println(sum.getRowVector(0));
  System.out.println(sum.getRowVector(1));
  System.out.println(sum.getRowVector(2));
}
 
开发者ID:BigBayes,项目名称:BNPMix.java,代码行数:17,代码来源:Generator.java

示例11: MixModel

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
public MixModel(MethyModel tumor, MethyModel normal, RealVector thetas, int nBetas, int MYTHREADS) throws InterruptedException {
	int nFeatures=tumor.getNaRatio().getDimension();
	this.nBetas = nBetas;
	RealVector betas = new ArrayRealVector(nBetas);
	for (int i=0; i<nBetas; i++) {
		betas.setEntry(i,i/(nBetas-1.0));
	}
	mixDens = new RealMatrix[nFeatures];
	ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);

	for(int i = 0; i < nFeatures; i++) {
		double tumorAlpha = tumor.getAlpha().getEntry(i);
		double tumorBeta = tumor.getBeta().getEntry(i);
		BetaDistribution tumorDist = new BetaDistribution(tumorAlpha,tumorBeta);
		double normalAlpha = normal.getAlpha().getEntry(i);
		double normalBeta = normal.getBeta().getEntry(i);
		BetaDistribution normalDist = new BetaDistribution(normalAlpha,normalBeta);
		Runnable worker = new CalMixDens(tumorDist,normalDist,thetas,betas,nPoints,i,mixDens);
		executor.execute(worker);
	}
	executor.shutdown();
	while (!executor.isTerminated()) {
		Thread.sleep(10000);
	}
}
 
开发者ID:jasminezhoulab,项目名称:CancerLocator,代码行数:26,代码来源:MixModel.java

示例12: selectFeature

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
public MixModel selectFeature(boolean[] selectedFeatures) {
	MixModel newModel = new MixModel();
	int nSelectedFeature = 0;
	for (boolean select:selectedFeatures) {
		if (select) {nSelectedFeature++;}
	}
	RealMatrix[] newMixDens = new RealMatrix[nSelectedFeature];
	int j = 0;
	for(int i=0; i<selectedFeatures.length; i++) {
		if (selectedFeatures[i]) {
			newMixDens[j] = this.mixDens[i];
			j++;
		}
	}
	newModel.setMixDens(newMixDens);
	return newModel;
}
 
开发者ID:jasminezhoulab,项目名称:CancerLocator,代码行数:18,代码来源:MixModel.java

示例13: correlation2Distance

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
public static RealMatrix correlation2Distance(RealMatrix rMat) {

        // Copy to retain Dimensions
        RealMatrix dMat = rMat.copy();

        for (int row = 0; row < rMat.getRowDimension(); row++) {
            for (int col = 0; col < rMat.getColumnDimension(); col++) {
                double r = rMat.getEntry(row, col);

                //Apply cosine theorem:
                //https://stats.stackexchange.com/questions/165194/using-correlation-as-distance-metric-for-hierarchical-clustering
                double d = Math.sqrt(2*(1-r));
                dMat.setEntry(row, col, d);
            }
        }

        return dMat;
    }
 
开发者ID:jmueller95,项目名称:CORNETTO,代码行数:19,代码来源:AnalysisData.java

示例14: testCorrelation

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
@Test
public void testCorrelation() throws Exception {
    TreeParser parser = new TreeParser();
    parser.parseTree("./res/nodes.dmp", "./res/names.dmp");
    TaxonId2CountCSVParser csvParser = new TaxonId2CountCSVParser(parser.getTaxonTree());
    ArrayList<Sample> samples = new ArrayList<>();
    samples.addAll(csvParser.parse("./res/testFiles/megan_examples/core1_activelayer_day2-ID2Count.txt"));
    samples.addAll(csvParser.parse("./res/testFiles/megan_examples/core1_activelayer_day7-ID2Count.txt"));
    samples.addAll(csvParser.parse("./res/testFiles/megan_examples/core1_activelayer_frozen-ID2Count.txt"));


    RealMatrix correlationMatrix = SampleComparison.getCorrelationMatrixOfSamples();
    System.out.println("Correlation Matrix:");
    printMatrix(correlationMatrix);
    System.out.println();

    RealMatrix correlationPValues = SampleComparison.getCorrelationPValuesOfSamples();
    System.out.println("P-Value matrix:");
    printMatrix(correlationPValues);
}
 
开发者ID:jmueller95,项目名称:CORNETTO,代码行数:21,代码来源:SampleComparisonTest.java

示例15: getWhiteningTransformation

import org.apache.commons.math3.linear.RealMatrix; //导入依赖的package包/类
/**
 * Returns the 'root' (U) of the inverse covariance matrix S^{-1},
 * such that S^{-1} = U^T . U
 * This matrix can be used to pre-transform the original sample
 * vectors X (by X &#8594; U . X) to a space where distance measurement (in the Mahalanobis
 * sense) can be calculated with the usual Euclidean norm.
 * The matrix U is invertible in case the reverse mapping is required.
 * 
 * @return The matrix for pre-transforming the original sample vectors.
 */
public double[][] getWhiteningTransformation() {
	IJ.log("in whitening");
	double relativeSymmetryThreshold = 1.0E-6; 		// CholeskyDecomposition.DEFAULT_RELATIVE_SYMMETRY_THRESHOLD == 1.0E-15; too small!
       double absolutePositivityThreshold = 1.0E-10;	// CholeskyDecomposition.DEFAULT_ABSOLUTE_POSITIVITY_THRESHOLD == 1.0E-10;
	CholeskyDecomposition cd = 
			new CholeskyDecomposition(MatrixUtils.createRealMatrix(iCov),
					relativeSymmetryThreshold, absolutePositivityThreshold);
	RealMatrix U = cd.getLT();
	return U.getData();
}
 
开发者ID:imagingbook,项目名称:imagingbook-common,代码行数:21,代码来源:MahalanobisDistance.java


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