/** * 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(); }
/** * Singular Value Decomposition (SVD) based naive scoring. */ private double computeScoreSVD(@Nonnull final RealMatrix H, @Nonnull final RealMatrix G) { SingularValueDecomposition svdH = new SingularValueDecomposition(H); RealMatrix UT = svdH.getUT(); SingularValueDecomposition svdG = new SingularValueDecomposition(G); RealMatrix Q = svdG.getU(); // find the largest singular value for the r principal components RealMatrix UTQ = UT.getSubMatrix(0, r - 1, 0, window - 1).multiply( Q.getSubMatrix(0, window - 1, 0, r - 1)); SingularValueDecomposition svdUTQ = new SingularValueDecomposition(UTQ); double[] s = svdUTQ.getSingularValues(); return 1.d - s[0]; }
@Test public void testPower1() { RealMatrix A = new Array2DRowRealMatrix(new double[][] {new double[] {1, 2, 3}, new double[] {4, 5, 6}}); double[] x = new double[3]; x[0] = Math.random(); x[1] = Math.random(); x[2] = Math.random(); double[] u = new double[2]; double[] v = new double[3]; double s = MatrixUtils.power1(A, x, 2, u, v); SingularValueDecomposition svdA = new SingularValueDecomposition(A); Assert.assertArrayEquals(svdA.getU().getColumn(0), u, 0.001d); Assert.assertArrayEquals(svdA.getV().getColumn(0), v, 0.001d); Assert.assertEquals(svdA.getSingularValues()[0], s, 0.001d); }
/** * Find the center of the ellipsoid. * * @param a the algebraic from of the polynomial. * @return a vector containing the center of the ellipsoid. */ private RealVector findCenter(RealMatrix a) { RealMatrix subA = a.getSubMatrix(0, 2, 0, 2); for (int q = 0; q < subA.getRowDimension(); q++) { for (int s = 0; s < subA.getColumnDimension(); s++) { subA.multiplyEntry(q, s, -1.0); } } RealVector subV = a.getRowVector(3).getSubVector(0, 3); // inv (dtd) DecompositionSolver solver = new SingularValueDecomposition(subA) .getSolver(); RealMatrix subAi = solver.getInverse(); return subAi.operate(subV); }
/** * Find the center of the ellipsoid. * * @param a * the algebraic from of the polynomial. * @return a vector containing the center of the ellipsoid. */ private RealVector findCenter(RealMatrix a) { RealMatrix subA = a.getSubMatrix(0, 2, 0, 2); for (int q = 0; q < subA.getRowDimension(); q++) { for (int s = 0; s < subA.getColumnDimension(); s++) { subA.multiplyEntry(q, s, -1.0); } } RealVector subV = a.getRowVector(3).getSubVector(0, 3); // inv (dtd) DecompositionSolver solver = new SingularValueDecomposition(subA) .getSolver(); RealMatrix subAi = solver.getInverse(); return subAi.operate(subV); }
/** * * @param aif * low-triangular shifted matrix * @return the aif's pseudo-inverse by SVD */ public static double[][] pInvMon(double[][] aif) { RealMatrix trunUTrans, trunS, trunV; SingularValueDecomposition svd = new SingularValueDecomposition( new Array2DRowRealMatrix(aif, false)); int rank = svd.getRank(); /* * double [] sinV = svd.getSingularValues(); double [] cag = new * double[rank]; for (int i = 0; i < rank; i++) cag[i] = sinV[i]; */ trunS = svd.getS().getSubMatrix(0, rank - 1, 0, rank - 1); trunV = svd.getV().getSubMatrix(0, aif[0].length - 1, 0, rank - 1); trunUTrans = svd.getUT() .getSubMatrix(0, rank - 1, 0, aif[0].length - 1); // IJ.showMessage(" " +interBad(cag) / // interBad(svd.getSingularValues())); return trunV.multiply(trunS).multiply(trunUTrans).getData(); /* * return new SingularValueDecomposition(new Array2DRowRealMatrix(aif, * false)).getSolver().getInverse().getData(); */ }
static double[][] getTruncatedVT(INDArray matrix, int k) { double[][] data = getDoubles(matrix); SingularValueDecomposition svd = new SingularValueDecomposition(MatrixUtils.createRealMatrix(data)); double[][] truncatedVT = new double[k][svd.getVT().getColumnDimension()]; svd.getVT().copySubMatrix(0, k - 1, 0, truncatedVT[0].length - 1, truncatedVT); return truncatedVT; }
static double[][] getTruncatedUT(INDArray matrix, int k) { double[][] data = getDoubles(matrix); SingularValueDecomposition svd = new SingularValueDecomposition(MatrixUtils.createRealMatrix(data)); double[][] truncatedU = new double[svd.getU().getRowDimension()][k]; svd.getU().copySubMatrix(0, truncatedU.length - 1, 0, k - 1, truncatedU); return truncatedU; }
private void printSVD(SingularValueDecomposition svd) { RealMatrix U = svd.getU(); RealMatrix S = svd.getS(); RealMatrix V = svd.getV(); System.out.println("------ SVD ---------------"); System.out.println("U = " + Matrix.toString(U.getData())); System.out.println("S = " + Matrix.toString(S.getData())); System.out.println("V = " + Matrix.toString(V.getData())); System.out.println("--------------------------"); }
@Override public void fit(List<double[]> X, List<double[]> Y) { // fits n-dimensional data sets with affine model if (X.size() != Y.size()) throw new IllegalArgumentException("point sequences X, Y must have same length"); this.m = X.size(); this.n = X.get(0).length; RealMatrix M = MatrixUtils.createRealMatrix(2 * m, 2 * (n + 1)); RealVector b = new ArrayRealVector(2 * m); // mount matrix M: int row = 0; for (double[] x : X) { for (int j = 0; j < n; j++) { M.setEntry(row, j, x[j]); M.setEntry(row, n, 1); row++; } for (int j = 0; j < n; j++) { M.setEntry(row, j + n + 1, x[j]); M.setEntry(row, 2 * n + 1, 1); row++; } } // mount vector b row = 0; for (double[] y : Y) { for (int j = 0; j < n; j++) { b.setEntry(row, y[j]); row++; } } SingularValueDecomposition svd = new SingularValueDecomposition(M); DecompositionSolver solver = svd.getSolver(); RealVector a = solver.solve(b); A = makeTransformationMatrix(a); }
/** * Constructor for more than 4 point pairs, finds a least-squares solution * for the homography parameters. * NOTE: this is UNFINISHED code! * @param P sequence of points (source) * @param Q sequence of points (target) * @param dummy unused (only to avoid duplicate signature) */ public ProjectiveMapping(Point2D[] P, Point2D[] Q, boolean dummy) { final int n = P.length; double[] ba = new double[2 * n]; double[][] Ma = new double[2 * n][]; for (int i = 0; i < n; i++) { double x = P[i].getX(); double y = P[i].getY(); double u = Q[i].getX(); double v = Q[i].getY(); ba[2 * i + 0] = u; ba[2 * i + 1] = v; Ma[2 * i + 0] = new double[] { x, y, 1, 0, 0, 0, -u * x, -u * y }; Ma[2 * i + 1] = new double[] { 0, 0, 0, x, y, 1, -v * x, -v * y }; } RealMatrix M = MatrixUtils.createRealMatrix(Ma); RealVector b = MatrixUtils.createRealVector(ba); DecompositionSolver solver = new SingularValueDecomposition(M).getSolver(); RealVector h = solver.solve(b); a00 = h.getEntry(0); a01 = h.getEntry(1); a02 = h.getEntry(2); a10 = h.getEntry(3); a11 = h.getEntry(4); a12 = h.getEntry(5); a20 = h.getEntry(6); a21 = h.getEntry(7); a22 = 1; }
/** * Constructor * @param x the input matrix */ XSVD(RealMatrix x) { final SingularValueDecomposition svd = new SingularValueDecomposition(x); this.rank = svd.getRank(); this.u = toDataFrame(svd.getU()); this.v = toDataFrame(svd.getV()); this.s = toDataFrame(svd.getS()); this.singularValues = Array.of(svd.getSingularValues()); }
private double computeL(double mu) { double LPenalty = lpenalty * mu; SingularValueDecomposition svd = new SingularValueDecomposition(X.subtract(S)); double[] penalizedD = softThreshold(svd.getSingularValues(), LPenalty); RealMatrix D_matrix = MatrixUtils.createRealDiagonalMatrix(penalizedD); L = svd.getU().multiply(D_matrix).multiply(svd.getVT()); return sum(penalizedD) * LPenalty; }
/** * pdf(x, x_hat) = exp(-0.5 * (x-x_hat) * inv(Σ) * (x-x_hat)T) / ( 2π^0.5d * det(Σ)^0.5) * * @return value of probabilistic density function * @link https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Density_function */ public static double pdf(@Nonnull final RealVector x, @Nonnull final RealVector x_hat, @Nonnull final RealMatrix sigma) { final int dim = x.getDimension(); Preconditions.checkArgument(x_hat.getDimension() == dim, "|x| != |x_hat|, |x|=" + dim + ", |x_hat|=" + x_hat.getDimension()); Preconditions.checkArgument(sigma.getRowDimension() == dim, "|x| != |sigma|, |x|=" + dim + ", |sigma|=" + sigma.getRowDimension()); Preconditions.checkArgument(sigma.isSquare(), "Sigma is not square matrix"); LUDecomposition LU = new LUDecomposition(sigma); final double detSigma = LU.getDeterminant(); double denominator = Math.pow(2.d * Math.PI, 0.5d * dim) * Math.pow(detSigma, 0.5d); if (denominator == 0.d) { // avoid divide by zero return 0.d; } final RealMatrix invSigma; DecompositionSolver solver = LU.getSolver(); if (solver.isNonSingular() == false) { SingularValueDecomposition svd = new SingularValueDecomposition(sigma); invSigma = svd.getSolver().getInverse(); // least square solution } else { invSigma = solver.getInverse(); } //EigenDecomposition eigen = new EigenDecomposition(sigma); //double detSigma = eigen.getDeterminant(); //RealMatrix invSigma = eigen.getSolver().getInverse(); RealVector diff = x.subtract(x_hat); RealVector premultiplied = invSigma.preMultiply(diff); double sum = premultiplied.dotProduct(diff); double numerator = Math.exp(-0.5d * sum); return numerator / denominator; }
@Nonnull public static RealMatrix inverse(@Nonnull final RealMatrix m, final boolean exact) throws SingularMatrixException { LUDecomposition LU = new LUDecomposition(m); DecompositionSolver solver = LU.getSolver(); final RealMatrix inv; if (exact || solver.isNonSingular()) { inv = solver.getInverse(); } else { SingularValueDecomposition SVD = new SingularValueDecomposition(m); inv = SVD.getSolver().getInverse(); } return inv; }
/** * L = A x R * * @return a matrix A that minimizes A x R - L */ @Nonnull public static RealMatrix solve(@Nonnull final RealMatrix L, @Nonnull final RealMatrix R, final boolean exact) throws SingularMatrixException { LUDecomposition LU = new LUDecomposition(R); DecompositionSolver solver = LU.getSolver(); final RealMatrix A; if (exact || solver.isNonSingular()) { A = LU.getSolver().solve(L); } else { SingularValueDecomposition SVD = new SingularValueDecomposition(R); A = SVD.getSolver().solve(L); } return A; }
public void updateCoefficients(double l2penalty) { if (this.X_svd == null) { this.X_svd = new SingularValueDecomposition(X); } RealMatrix V = this.X_svd.getV(); double[] s = this.X_svd.getSingularValues(); RealMatrix U = this.X_svd.getU(); for (int i = 0; i < s.length; i++) { s[i] = s[i] / (s[i]*s[i] + l2penalty); } RealMatrix S = MatrixUtils.createRealDiagonalMatrix(s); RealMatrix Z = V.multiply(S).multiply(U.transpose()); this.coefficients = Z.operate(this.Y); this.fitted = this.X.operate(this.coefficients); double errorVariance = 0; for (int i = 0; i < residuals.length; i++) { this.residuals[i] = this.Y[i] - this.fitted[i]; errorVariance += this.residuals[i] * this.residuals[i]; } errorVariance = errorVariance / (X.getRowDimension() - X.getColumnDimension()); RealMatrix errorVarianceMatrix = MatrixUtils.createRealIdentityMatrix(this.Y.length).scalarMultiply(errorVariance); RealMatrix coefficientsCovarianceMatrix = Z.multiply(errorVarianceMatrix).multiply(Z.transpose()); this.standarderrors = getDiagonal(coefficientsCovarianceMatrix); }
/** Compute the plane containing origin that best fits viewing directions point cloud. * @param sensor line sensor * @param minLine minimum line number * @param maxLine maximum line number * <p> * The normal is oriented such that traversing pixels in increasing indices * order corresponds to trigonometric order (i.e. counterclockwise). * </p> * @return normal of the mean plane * @exception RuggedException if mid date cannot be handled */ private static Vector3D computeMeanPlaneNormal(final LineSensor sensor, final int minLine, final int maxLine) throws RuggedException { final AbsoluteDate midDate = sensor.getDate(0.5 * (minLine + maxLine)); // build a centered data matrix // (for each viewing direction, we add both the direction and its // opposite, thus ensuring the plane will contain origin) final RealMatrix matrix = MatrixUtils.createRealMatrix(3, 2 * sensor.getNbPixels()); for (int i = 0; i < sensor.getNbPixels(); ++i) { final Vector3D l = sensor.getLos(midDate, i); matrix.setEntry(0, 2 * i, l.getX()); matrix.setEntry(1, 2 * i, l.getY()); matrix.setEntry(2, 2 * i, l.getZ()); matrix.setEntry(0, 2 * i + 1, -l.getX()); matrix.setEntry(1, 2 * i + 1, -l.getY()); matrix.setEntry(2, 2 * i + 1, -l.getZ()); } // compute Singular Value Decomposition final SingularValueDecomposition svd = new SingularValueDecomposition(matrix); // extract the left singular vector corresponding to least singular value // (i.e. last vector since Apache Commons Math returns the values // in non-increasing order) final Vector3D singularVector = new Vector3D(svd.getU().getColumn(2)).normalize(); // check rotation order final Vector3D first = sensor.getLos(midDate, 0); final Vector3D last = sensor.getLos(midDate, sensor.getNbPixels() - 1); if (Vector3D.dotProduct(singularVector, Vector3D.crossProduct(first, last)) >= 0) { return singularVector; } else { return singularVector.negate(); } }
/** * Calculates the compact Singular Value Decomposition of a matrix. The * Singular Value Decomposition of matrix A is a set of three matrices: U, Σ * and V such that A = U × Σ × VT. Let A be a m × n matrix, then U is a m × * p orthogonal matrix, Σ is a p × p diagonal matrix with positive or null * elements, V is a p × n orthogonal matrix (hence VT is also orthogonal) * where p=min(m,n). * * @param a Given matrix. * @return Result U/S/V arrays. */ public static Array[] svd(Array a) { int m = a.getShape()[0]; int n = a.getShape()[1]; int k = Math.min(m, n); Array Ua = Array.factory(DataType.DOUBLE, new int[]{m, k}); Array Va = Array.factory(DataType.DOUBLE, new int[]{k, n}); Array Sa = Array.factory(DataType.DOUBLE, new int[]{k}); double[][] aa = (double[][]) ArrayUtil.copyToNDJavaArray(a); RealMatrix matrix = new Array2DRowRealMatrix(aa, false); SingularValueDecomposition decomposition = new SingularValueDecomposition(matrix); RealMatrix U = decomposition.getU(); RealMatrix V = decomposition.getVT(); double[] sv = decomposition.getSingularValues(); for (int i = 0; i < m; i++) { for (int j = 0; j < k; j++) { Ua.setDouble(i * k + j, U.getEntry(i, j)); } } for (int i = 0; i < k; i++) { for (int j = 0; j < n; j++) { Va.setDouble(i * n + j, V.getEntry(i, j)); } } for (int i = 0; i < k; i++) { Sa.setDouble(i, sv[i]); } return new Array[]{Ua, Sa, Va}; }
/** * Performs Singular Value Decomposition. Calls Apache Commons Math SVD. * X = U * Sigma * Vt, where X is the input matrix, * U is the left singular matrix, Sigma is the singular values matrix returned as a * column matrix and Vt is the transpose of the right singular matrix V. * However, the returned array has { U, Sigma, V} * * @param in Input matrix * @return An array containing U, Sigma & V * @throws DMLRuntimeException */ private static MatrixBlock[] computeSvd(MatrixObject in) throws DMLRuntimeException { Array2DRowRealMatrix matrixInput = DataConverter.convertToArray2DRowRealMatrix(in); SingularValueDecomposition svd = new SingularValueDecomposition(matrixInput); double[] sigma = svd.getSingularValues(); RealMatrix u = svd.getU(); RealMatrix v = svd.getV(); MatrixBlock U = DataConverter.convertToMatrixBlock(u.getData()); MatrixBlock Sigma = DataConverter.convertToMatrixBlock(sigma, true); Sigma = LibMatrixReorg.diag(Sigma, new MatrixBlock(Sigma.rlen, Sigma.rlen, true)); MatrixBlock V = DataConverter.convertToMatrixBlock(v.getData()); return new MatrixBlock[] { U, Sigma, V }; }
public SVDAlgorithmWrapper(List<SparseWeightableVector> matrix) { int n = matrix.size(); int d = matrix.get(0).getDimension(); final OpenMapRealMatrix realMatrix = new OpenMapRealMatrix(n, d); int idx = 0; for (SparseWeightableVector vector : matrix) { realMatrix.setRowVector(idx++, vector); } this.svd = new SingularValueDecomposition(realMatrix); }
private void updateInverseCovariance() { try { inverseCov = new LUDecomposition(cov).getSolver().getInverse(); } catch (SingularMatrixException e) { singularCovariances.inc(); inverseCov = new SingularValueDecomposition(cov).getSolver().getInverse(); } }
public RealMatrix SVD(){ SingularValueDecomposition svd = new SingularValueDecomposition(matrix); /*RealMatrix u = svd.getU(); RealMatrix s = svd.getS(); RealMatrix v = svd.getV();*/ return svd.getU(); }
/** Create a SVD instance using Apache Commons Math. * * @param m matrix that is not {@code null} * @return SVD instance that is never {@code null} */ @Override public SVD createSVD(final RealMatrix m) { Utils.nonNull(m, "Cannot create SVD on a null matrix."); final SingularValueDecomposition svd = new SingularValueDecomposition(m); final RealMatrix pinv = svd.getSolver().getInverse(); return new SimpleSVD(svd.getU(), svd.getSingularValues(), svd.getV(), pinv); }
@Test public void testSVD() { double[][] testData = { { 36, 49, 47, 11 }, { 2, 68, 27, 42 }, { 42, 25, 38, 3 } }; RealMatrix matrix = MatrixUtils.createRealMatrix(testData); SingularValueDecomposition svd = new SingularValueDecomposition(matrix); System.out.println(svd.getU()); System.out.println(svd.getS()); System.out.println(svd.getV()); DoubleMatrix[] usv = Singular.fullSVD(new DoubleMatrix(testData)); System.out.println(usv[0]); System.out.println(usv[1]); System.out.println(usv[2]); DoubleMatrix U = usv[0]; DoubleMatrix S = usv[1]; DoubleMatrix V = usv[2]; DoubleMatrix mt = new DoubleMatrix(3, 4); for (int i = 0; i < S.length; i++) { mt.put(i, i, S.get(i)); } System.out.println(mt.toString().replace(";", "\n")); DoubleMatrix src = U.mmul(mt).mmul(V.transpose()); System.out.println(src.toString().replace(";", "\n")); mt = Solve.pinv(mt); System.out.println(mt.toString().replace(";", "\n")); }
@Override public double getCondition(Matrix m) { ArgChecker.notNull(m, "m"); if (m instanceof DoubleMatrix) { RealMatrix temp = CommonsMathWrapper.wrap((DoubleMatrix) m); SingularValueDecomposition svd = new SingularValueDecomposition(temp); return svd.getConditionNumber(); } throw new IllegalArgumentException("Can only find condition number of DoubleMatrix; have " + m.getClass()); }
@Override public DoubleMatrix getInverse(Matrix m) { ArgChecker.notNull(m, "matrix was null"); if (m instanceof DoubleMatrix) { RealMatrix temp = CommonsMathWrapper.wrap((DoubleMatrix) m); SingularValueDecomposition sv = new SingularValueDecomposition(temp); RealMatrix inv = sv.getSolver().getInverse(); return CommonsMathWrapper.unwrap(inv); } throw new IllegalArgumentException("Can only find inverse of DoubleMatrix; have " + m.getClass()); }
@Override public SVDecompositionResult apply(DoubleMatrix x) { ArgChecker.notNull(x, "x"); MatrixValidate.notNaNOrInfinite(x); RealMatrix commonsMatrix = CommonsMathWrapper.wrap(x); SingularValueDecomposition svd = new SingularValueDecomposition(commonsMatrix); return new SVDecompositionCommonsResult(svd); }
/** * Creates an instance. * * @param svd The result of the SV decomposition, not null */ 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(); }
/** * Build the SVD model. * * @return A singular value decomposition recommender model. */ @Override public SVDModel get() { // Create index mappings of user and item IDs. // You can use these to find row and columns in the matrix based on user/item IDs. IdIndexMapping userMapping = IdIndexMapping.create(userDAO.getUserIds()); logger.debug("indexed {} users", userMapping.size()); IdIndexMapping itemMapping = IdIndexMapping.create(itemDAO.getItemIds()); logger.debug("indexed {} items", itemMapping.size()); // We have to do 2 things: // First, prepare a matrix containing the rating data. RealMatrix matrix = createRatingMatrix(userMapping, itemMapping); // Second, compute its factorization // All the work is done in the constructor SingularValueDecomposition svd = new SingularValueDecomposition(matrix); // Third, truncate the decomposed matrix SVDModel svdModel = new SVDModel(userMapping, itemMapping, svd.getU().getSubMatrix(0, userMapping.size() - 1, 0, featureCount - 1), svd.getV().getSubMatrix(0, itemMapping.size() - 1, 0, featureCount - 1), svd.getS().getSubMatrix(0, featureCount - 1, 0, featureCount - 1)); return svdModel; }
public PacioliList svdNonZero() throws MVMException { NonZeroSubMatrix sub = new NonZeroSubMatrix(numbers); int m = sub.numbers.getRowDimension(); int n = sub.numbers.getColumnDimension(); int p = Math.min(m, n); SingularValueDecomposition decomposition = new SingularValueDecomposition(sub.numbers); RealMatrix numbersU = decomposition.getU(); RealMatrix numbersS = decomposition.getS(); RealMatrix numbersV = decomposition.getV(); List<PacioliValue> svs = new ArrayList<PacioliValue>(); for (int i = 0; i < p; i++) { List<PacioliValue> items = new ArrayList<PacioliValue>(); Matrix matrixS = new Matrix(shape.getFactor()); Matrix matrixU = new Matrix(shape.rowUnits()); Matrix matrixV = new Matrix(shape.columnUnits()); matrixS.numbers.setEntry(0, 0, numbersS.getEntry(i, i)); for (int j = 0; j < m; j++) { matrixU.numbers.setEntry(sub.originalRow(j), 0, numbersU.getEntry(j, i)); } for (int j = 0; j < n; j++) { matrixV.numbers.setEntry(sub.originalColumn(j), 0, numbersV.getEntry(j, i)); } items.add(matrixS); items.add(matrixU); items.add(matrixV); svs.add(new PacioliTuple(items)); } return new PacioliList(svs); }
public PacioliList svd() throws MVMException { int m = shape.rowDimension().size(); int n = shape.columnDimension().size(); int p = Math.min(m, n); SingularValueDecomposition decomposition = new SingularValueDecomposition(numbers); RealMatrix numbersU = decomposition.getU(); RealMatrix numbersS = decomposition.getS(); RealMatrix numbersV = decomposition.getV(); List<PacioliValue> svs = new ArrayList<PacioliValue>(); for (int i = 0; i < p; i++) { List<PacioliValue> items = new ArrayList<PacioliValue>(); Matrix matrixS = new Matrix(shape.getFactor()); Matrix matrixU = new Matrix(shape.rowUnits()); Matrix matrixV = new Matrix(shape.columnUnits()); matrixS.numbers.setEntry(0, 0, numbersS.getEntry(i, i)); for (int j = 0; j < m; j++) { matrixU.numbers.setEntry(j, 0, numbersU.getEntry(j, i)); } for (int j = 0; j < n; j++) { matrixV.numbers.setEntry(j, 0, numbersV.getEntry(j, i)); } items.add(matrixS); items.add(matrixU); items.add(matrixV); svs.add(new PacioliTuple(items)); } return new PacioliList(svs); }
/** * @param a * @return array of singular values */ public static double[] calcSingularValues(Dataset a) { SingularValueDecomposition svd = new SingularValueDecomposition(createRealMatrix(a)); return svd.getSingularValues(); }
/** * Calculate singular value decomposition A = U S V^T * @param a * @return array of U - orthogonal matrix, s - singular values vector, V - orthogonal matrix */ public static Dataset[] calcSingularValueDecomposition(Dataset a) { SingularValueDecomposition svd = new SingularValueDecomposition(createRealMatrix(a)); return new Dataset[] {createDataset(svd.getU()), DatasetFactory.createFromObject(svd.getSingularValues()), createDataset(svd.getV())}; }