List of usage examples for org.apache.commons.math3.linear SingularValueDecomposition getS
public RealMatrix getS()
From source file:edu.oregonstate.eecs.mcplan.ml.MatrixAlgorithms.java
public static RealMatrix makePositiveDefinite(final RealMatrix M, final double eps) { assert (eps > 0.0); final SingularValueDecomposition svd = new SingularValueDecomposition(M); final RealMatrix Sigma = svd.getS().copy(); final int N = Math.min(Sigma.getColumnDimension(), Sigma.getRowDimension()); for (int i = 0; i < N; ++i) { final double lambda = Sigma.getEntry(i, i); System.out.println("lambda_" + i + " = " + lambda); if (Math.abs(lambda) < eps) { System.out.println("Corrected " + i); Sigma.setEntry(i, i, eps);//from w ww . j av a2s.com } else if (lambda < 0.0) { throw new NonPositiveDefiniteMatrixException(lambda, i, eps); } else { Sigma.setEntry(i, i, lambda); } } return svd.getU().multiply(Sigma).multiply(svd.getVT()); }
From source file:edu.oregonstate.eecs.mcplan.ml.MatrixAlgorithms.java
/** * Computes the inverse of a matrix using the singular value decomposition. * /*w w w . j ava 2s . com*/ * The input matrix M is assumed to be positive definite up to numerical * precision 'eps'. That is, for all eigenvalues lambda of M, it must be * the case that lambda + eps > 0. For eigenvalues with |lambda| < eps, the * eigenvalue is set to 'eps' before inverting. Throws an exception if * any lambda < -eps. * @param M * @param eps * @return */ public static RealMatrix robustInversePSD(final RealMatrix M, final double eps) { assert (eps > 0.0); final SingularValueDecomposition svd = new SingularValueDecomposition(M); final RealMatrix Sigma = svd.getS().copy(); final int N = Math.min(Sigma.getColumnDimension(), Sigma.getRowDimension()); for (int i = 0; i < N; ++i) { final double lambda = Sigma.getEntry(i, i); System.out.println("lambda_" + i + " = " + lambda); if (Math.abs(lambda) < eps) { System.out.println("Corrected " + i); Sigma.setEntry(i, i, 1.0 / eps); } else if (lambda < 0.0) { throw new IllegalArgumentException("Negative eigenvalue " + lambda); } else { Sigma.setEntry(i, i, 1.0 / lambda); } } return svd.getV().multiply(Sigma.transpose()).multiply(svd.getUT()); }
From source file:com.github.tteofili.p2h.Par2HierUtils.java
/** * truncated SVD as taken from http://stackoverflow.com/questions/19957076/best-way-to-compute-a-truncated-singular-value-decomposition-in-java *//* w w w . j a va2s . c o m*/ 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(); }
From source file:dataminning2.SVDDecomposition.java
public double[][] DecompositionS(double[][] Dataarraytest) { Array2DRowRealMatrix rmA = new Array2DRowRealMatrix(Dataarraytest); SingularValueDecomposition svdObj = new SingularValueDecomposition(rmA); double[][] Sobj = svdObj.getS().getData(); return Sobj;/*w w w . jav a 2 s. c om*/ }
From source file:edu.cmu.tetrad.util.MatrixUtils.java
public static double[][] pseudoInverse(double[][] x) { SingularValueDecomposition svd = new SingularValueDecomposition(new Matrix(x)); Matrix U = svd.getU();//w ww .ja v a 2 s . c o m Matrix V = svd.getV(); Matrix S = svd.getS(); for (int i = 0; i < S.getRowDimension(); i++) { for (int j = 0; j < S.getColumnDimension(); j++) { double v = S.get(i, j); S.set(i, j, v == 0 ? 0.0 : 1.0 / v); } } return V.times(S.times(U.transpose())).getArray(); }
From source file:edu.cmu.tetrad.util.MatrixUtils1.java
public static double[][] pseudoInverse(double[][] x) { SingularValueDecomposition svd = new SingularValueDecomposition(new BlockRealMatrix(x)); RealMatrix U = svd.getU();/*from w w w . j a v a 2s . c om*/ RealMatrix V = svd.getV(); RealMatrix S = svd.getS(); for (int i = 0; i < S.getRowDimension(); i++) { for (int j = 0; j < S.getColumnDimension(); j++) { double v = S.getEntry(i, j); S.setEntry(i, j, v == 0 ? 0.0 : 1.0 / v); } } return V.multiply(S.multiply(U.transpose())).getData(); }
From source file:de.andreasschoknecht.LS3.LSSMCalculator.java
/** * Calculation of the singular value decomposition and initialization of corresponding variables. * * @param tdMatrix The weighted Term-Document Matrix for decomposition */// w w w. j a v a 2s.c o m void calculateSVD(double[][] tdMatrix) { weightedTDMatrix = new Array2DRowRealMatrix(tdMatrix); // execute actual SVD SingularValueDecomposition svd = new SingularValueDecomposition(weightedTDMatrix); U = svd.getU(); S = svd.getS(); Vt = svd.getVT(); // set rank of SVD rank = svd.getRank(); }
From source file:com.opengamma.strata.math.impl.linearalgebra.SVDecompositionCommonsResult.java
/** * @param svd The result of the SV decomposition, not null *///from www.j a v a2 s. c o m public SVDecompositionCommonsResult(SingularValueDecomposition svd) { ArgChecker.notNull(svd, "svd"); _condition = svd.getConditionNumber(); _norm = svd.getNorm(); _rank = svd.getRank(); _s = CommonsMathWrapper.unwrap(svd.getS()); _singularValues = svd.getSingularValues(); _u = CommonsMathWrapper.unwrap(svd.getU()); _uTranspose = CommonsMathWrapper.unwrap(svd.getUT()); _v = CommonsMathWrapper.unwrap(svd.getV()); _vTranspose = CommonsMathWrapper.unwrap(svd.getVT()); _solver = svd.getSolver(); }
From source file:com.analog.lyric.dimple.solvers.sumproduct.customFactors.MutlivariateGaussianMatrixProduct.java
public MutlivariateGaussianMatrixProduct(double[][] A) { int i; //,m; M = A.length;// ww w.j a va 2 s .com N = A[0].length; /* Here we precompute and store matrices for future message computations. * First, compute an SVD of the matrix A using EigenDecompositions of A*A^T and A^T*A * This way, we get nullspaces for free along with regularized inverse. */ RealMatrix Amat = wrapRealMatrix(A); SingularValueDecomposition svd = new SingularValueDecomposition(Amat); RealMatrix tmp = svd.getVT(); tmp = svd.getS().multiply(tmp); tmp = svd.getU().multiply(tmp); A_clean = matrixGetDataRef(tmp); RealMatrix ST = svd.getS().transpose(); int numS = Math.min(ST.getColumnDimension(), ST.getRowDimension()); for (i = 0; i < numS; i++) { double d = ST.getEntry(i, i); if (d < eps) d = eps; else if (d > 1 / eps) d = 1 / eps; ST.setEntry(i, i, 1.0 / d); } A_pinv = matrixGetDataRef(svd.getV().multiply(ST.multiply(svd.getUT()))); }
From source file:net.semanticmetadata.lire.filter.LsaFilter.java
/** * @param results/*from w w w . j a v a 2 s . com*/ * @param query * @return the filtered results or null if error occurs. */ public ImageSearchHits filter(ImageSearchHits results, Document query) { // create a double[items][histogram] tempFeature = null; LinkedList<double[]> features = new LinkedList<double[]>(); try { tempFeature = (LireFeature) featureClass.newInstance(); } catch (Exception e) { logger.severe("Could not create feature " + featureClass.getName() + " (" + e.getMessage() + ")."); return null; } // get all features from the result set, take care of those that do not have the respective field. for (int i = 0; i < results.length(); i++) { Document d = results.doc(i); if (d.getField(fieldName) != null) { tempFeature.setByteArrayRepresentation(d.getField(fieldName).binaryValue().bytes, d.getField(fieldName).binaryValue().offset, d.getField(fieldName).binaryValue().length); features.add(tempFeature.getDoubleHistogram()); } } // now go for the query if (query.getField(fieldName) != null) { tempFeature.setByteArrayRepresentation(query.getField(fieldName).binaryValue().bytes, query.getField(fieldName).binaryValue().offset, query.getField(fieldName).binaryValue().length); } else { logger.severe("Query document is missing the given feature " + featureClass.getName() + "."); return null; } double[][] matrixData = new double[features.size() + 1][tempFeature.getDoubleHistogram().length]; System.arraycopy(tempFeature.getDoubleHistogram(), 0, matrixData[0], 0, tempFeature.getDoubleHistogram().length); int count = 1; for (Iterator<double[]> iterator = features.iterator(); iterator.hasNext();) { double[] next = iterator.next(); System.arraycopy(next, 0, matrixData[count], 0, next.length); count++; } for (int i = 0; i < matrixData.length; i++) { double[] doubles = matrixData[i]; for (int j = 0; j < doubles.length; j++) { if (Double.isNaN(doubles[j])) System.err.println("Value is NaN"); ; } } // create a matrix object and do the magic Array2DRowRealMatrix m = new Array2DRowRealMatrix(matrixData); long ms = System.currentTimeMillis(); SingularValueDecomposition svd = new SingularValueDecomposition(m); ms = System.currentTimeMillis() - ms; double[] singularValues = svd.getSingularValues(); RealMatrix s = svd.getS(); // if no number of dimensions is given reduce to a tenth. if (numberOfDimensions < 1) numberOfDimensions = singularValues.length / 10; for (int i = numberOfDimensions; i < singularValues.length; i++) { s.setEntry(i, i, 0); } RealMatrix mNew = svd.getU().multiply(s).multiply(svd.getVT()); double[][] data = mNew.getData(); // create the new result set TreeSet<SimpleResult> result = new TreeSet<SimpleResult>(); double maxDistance = 0; double[] queryData = data[0]; for (int i = 1; i < data.length; i++) { double[] doubles = data[i]; double distance = MetricsUtils.distL1(doubles, queryData); result.add(new SimpleResult((float) distance, results.doc(i - 1), i - 1)); maxDistance = Math.max(maxDistance, distance); } ImageSearchHits hits; hits = new SimpleImageSearchHits(result, (float) maxDistance); return hits; }