List of usage examples for org.apache.commons.math3.linear RealMatrix getSubMatrix
RealMatrix getSubMatrix(int startRow, int endRow, int startColumn, int endColumn) throws OutOfRangeException, NumberIsTooSmallException;
From source file:movierecommend.MovieRecommend.java
public static void main(String[] args) throws ClassNotFoundException, SQLException { String url = "jdbc:sqlserver://localhost;databaseName=MovieDB;integratedSecurity=true"; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(url); Statement stm = conn.createStatement(); ResultSet rsRecnik = stm.executeQuery("SELECT Recnik FROM Recnik WHERE (ID_Zanra = 1)"); //citam recnik iz baze za odredjeni zanr String recnik[] = null;// www.j av a 2s. c o m while (rsRecnik.next()) { recnik = rsRecnik.getString("Recnik").split(","); //delim recnik na reci } ResultSet rsFilmovi = stm.executeQuery( "SELECT TOP (200) Naziv_Filma, LemmaPlots, " + "ID_Filma FROM Film WHERE (ID_Zanra = 1)"); List<Film> listaFilmova = new ArrayList<>(); Film f = null; int rb = 0; while (rsFilmovi.next()) { f = new Film(rb, Integer.parseInt(rsFilmovi.getString("ID_Filma")), rsFilmovi.getString("Naziv_Filma"), rsFilmovi.getString("LemmaPlots")); listaFilmova.add(f); rb++; } //kreiranje vektorskog modela M = MatrixUtils.createRealMatrix(recnik.length, listaFilmova.size()); System.out.println("Prva tezinska matrica"); for (int i = 0; i < recnik.length; i++) { String recBaza = recnik[i]; for (Film film : listaFilmova) { for (String lemmaRec : film.getPlotLema()) { if (recBaza.equals(lemmaRec)) { M.setEntry(i, film.getRb(), M.getEntry(i, film.getRb()) + 1); } } } } //racunanje tf-idf System.out.println("td-idf"); M = LSA.calculateTfIdf(M); System.out.println("SVD"); //SVD SingularValueDecomposition svd = new SingularValueDecomposition(M); RealMatrix V = svd.getV(); RealMatrix Vk = V.getSubMatrix(0, V.getRowDimension() - 1, 0, brojDimenzija - 1); //dimenzija je poslednji argument //kosinusna slicnost System.out.println("Cosin simmilarity"); CallableStatement stmTop = conn.prepareCall("{call Dodaj_TopList(?,?,?)}"); for (int j = 0; j < listaFilmova.size(); j++) { Film fl = listaFilmova.get(j); List<Film> lFilmova1 = new ArrayList<>(); lFilmova1.add(listaFilmova.get(j)); double sim = 0.0; for (int k = 0; k < listaFilmova.size(); k++) { // System.out.println(listaFilmova.size()); sim = LSA.cosinSim(j, k, Vk.transpose()); listaFilmova.get(k).setSimilarity(sim); lFilmova1.add(listaFilmova.get(k)); } Collections.sort(lFilmova1); for (int k = 2; k < 13; k++) { stmTop.setString(1, fl.getID() + ""); stmTop.setString(2, lFilmova1.get(k).getID() + ""); stmTop.setString(3, lFilmova1.get(k).getSimilarity() + ""); stmTop.execute(); } } stm.close(); rsRecnik.close(); rsFilmovi.close(); conn.close(); }
From source file:ch.zhaw.iamp.rct.weights.Weights.java
/** * Calculates a pseudo-inverse using the values in the given files. They are * first read, then converted to a matrix, and finally used for the * calculation of the inverse, using Singular value decomposition (SVD). * * @param pathToA The file which contains the matrix A, represented in * comma-separated-value format.// w w w.ja va2s . com * @param targetTrajectoryFile The file which contains the target * trajectory, represented in comma-separated-value format. * @param weightsFile The file, to which the calculated weights should be * written to. * @param offset The numbers of first steps to ignore (to skip fading-memory * initialization steps). */ public static void calculateWeights(final String pathToA, final String targetTrajectoryFile, final String weightsFile, final int offset) { try { RealMatrix A = csvToMatrix(pathToA); // cut first n elements A = A.getSubMatrix(offset, A.getRowDimension() - 1, 0, A.getColumnDimension() - 1); A = addNoise(A); RealMatrix b = csvToMatrix(targetTrajectoryFile); // adjust b to cutting int n = offset % b.getRowDimension(); if (n > 0) { RealMatrix tmp = b.getSubMatrix(n, b.getRowDimension() - 1, 0, b.getColumnDimension() - 1); b = b.getSubMatrix(0, n - 1, 0, b.getColumnDimension() - 1); double[][] tmpArray = tmp.getData(); double[][] tmpArray2 = b.getData(); b = MatrixUtils.createRealMatrix(concat(tmpArray, tmpArray2)); tmpArray = b.getData(); for (int i = 0; tmpArray.length < A.getRowDimension(); ++i) { tmpArray2 = new double[1][tmpArray[0].length]; for (int j = 0; j < tmpArray[i].length; ++j) { tmpArray2[0][j] = tmpArray[i][j]; } tmpArray = concat(tmpArray, tmpArray2); } b = MatrixUtils.createRealMatrix(tmpArray); } DecompositionSolver solver = new SingularValueDecomposition(A).getSolver(); RealMatrix x = solver.solve(b).transpose(); matrixToCsv(x, weightsFile); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Could not read a file: " + ex.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); Logger.getLogger(Weights.class.getName()).log(Level.WARNING, "Could not read a file: {0}", ex); } catch (DimensionMismatchException ex) { JOptionPane.showMessageDialog(null, "<html>Could not calculate the " + "pseudo-inverse since a dimension mismatch occurred.<br />" + "Please make sure that all lines of the CSV file posses " + "the same amount of entries.<br />Hint: Remove the last " + "line and try it again.</html>", "Matrix Dimension Mismatch", JOptionPane.ERROR_MESSAGE); Logger.getLogger(Weights.class.getName()).log(Level.WARNING, "A dimension mismatch occurred: {0}", ex); } }
From source file:com.vsthost.rnd.commons.math.ext.linear.EMatrixUtils.java
/** * Returns the column range from the matrix as a new matrix. * * @param matrix The input matrix/*from w w w . j ava 2 s . c o m*/ * @param start The index of the column to start with (inclusive) * @param end The index of the column to end with (inclusive) * @return A new matrix with columns specified */ public static RealMatrix getColumRange(RealMatrix matrix, int start, int end) { return matrix.getSubMatrix(0, matrix.getRowDimension() - 1, start, end); }
From source file:com.vsthost.rnd.commons.math.ext.linear.EMatrixUtils.java
/** * Returns the row range from the matrix as a new matrix. * * @param matrix The input matrix// w w w. j a va 2s . c o m * @param start The index of the row to start with (inclusive) * @param end The index of the row to end with (inclusive) * @return A new matrix with rows specified */ public static RealMatrix getRowRange(RealMatrix matrix, int start, int end) { return matrix.getSubMatrix(start, end, 0, matrix.getColumnDimension() - 1); }
From source file:edu.cudenver.bios.matrix.OrthogonalPolynomials.java
/** * Create a within or between subject contrast (C) for polynomial trends * for an arbitrary list of factors. The returned collection includes * the grand mean contrast, all 1-factor main effect contrasts, and * all possible interaction contrasts//from w w w .ja va 2 s .c o m * * @param factorList list of factors, including name and value information * @return polynomial contrast collection. * @throws IllegalArgumentException */ public static OrthogonalPolynomialContrastCollection buildContrastCollection(List<Factor> factorList, boolean between) throws IllegalArgumentException { if (factorList == null || factorList.size() <= 0) throw new IllegalArgumentException("no factors specified"); ArrayList<RealMatrix> zeroTrendList = new ArrayList<RealMatrix>(factorList.size()); ArrayList<RealMatrix> factorTrendList = new ArrayList<RealMatrix>(factorList.size()); for (Factor factor : factorList) { double[] centered = centerAndScale(factor.getValues()); RealMatrix poly = OrthogonalPolynomials.orthogonalPolynomialCoefficients(centered, centered.length - 1); zeroTrendList.add(poly.getColumnMatrix(0)); factorTrendList.add(poly.getSubMatrix(0, poly.getRowDimension() - 1, 1, poly.getColumnDimension() - 1)); } OrthogonalPolynomialContrastCollection results = new OrthogonalPolynomialContrastCollection(); /* * We need to create contrasts for every possible combination of * zero and factor trends. The possible combinations can be * enumerated by the binary representation of the numbers * 0 - 2^(#factors). In this case, 0 indicates that the zero-trend contrast should * be included in the Kronecker product for a given factor, and 1 indicates that the * factor trend contrast should be included in the Kronecker product. */ ArrayList<RealMatrix> kroneckerList = new ArrayList<RealMatrix>(factorList.size()); ArrayList<Factor> activeFactorList = new ArrayList<Factor>(factorList.size()); // build the grand mean for (RealMatrix zeroTrend : zeroTrendList) kroneckerList.add(zeroTrend); if (between) results.addContrast( new OrthogonalPolynomialContrast(MatrixUtils.getKroneckerProduct(kroneckerList).transpose())); else results.addContrast(new OrthogonalPolynomialContrast(MatrixUtils.getKroneckerProduct(kroneckerList))); // loop over the remaining contrasts int totalContrasts = (int) Math.pow(2.0, (double) factorList.size()); for (int i = 1; i < totalContrasts; i++) { kroneckerList.clear(); activeFactorList.clear(); int mask = 1; for (int factorIdx = 0; factorIdx < factorList.size(); factorIdx++, mask *= 2) { if ((i & mask) != 0) { kroneckerList.add(factorTrendList.get(factorIdx)); activeFactorList.add(factorList.get(factorIdx)); } else { kroneckerList.add(zeroTrendList.get(factorIdx)); } } // add the appropriate contrast type // note that if "i" is a power of 2 then we have a main effect contrast, else interaction RealMatrix contrast = null; if (between) contrast = MatrixUtils.getKroneckerProduct(kroneckerList).transpose(); else contrast = MatrixUtils.getKroneckerProduct(kroneckerList); results.addContrast(new OrthogonalPolynomialContrast( ((i & (i - 1)) == 0 ? ContrastType.MAIN_EFFECT : ContrastType.INTERACTION), activeFactorList, contrast)); } return results; }
From source file:ellipsoidFit.FitPoints.java
/** * Find the center of the ellipsoid./*from w w w .j av a 2 s . c o m*/ * * @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); }
From source file:ellipsoidFit.FitPoints.java
/** * Fit points to the polynomial expression Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz * + 2Fyz + 2Gx + 2Hy + 2Iz = 1 and determine the center and radii of the * fit ellipsoid./*from w ww. j a v a 2 s . c o m*/ * * @param points * the points to be fit to the ellipsoid. */ public void fitEllipsoid(ArrayList<ThreeSpacePoint> points) { // Fit the points to Ax^2 + By^2 + Cz^2 + 2Dxy + 2Exz // + 2Fyz + 2Gx + 2Hy + 2Iz = 1 and solve the system. // v = (( d' * d )^-1) * ( d' * ones.mapAddToSelf(1)); RealVector v = solveSystem(points); // Form the algebraic form of the ellipsoid. RealMatrix a = formAlgebraicMatrix(v); // Find the center of the ellipsoid. center = findCenter(a); // Translate the algebraic form of the ellipsoid to the center. RealMatrix r = translateToCenter(center, a); // Generate a submatrix of r. RealMatrix subr = r.getSubMatrix(0, 2, 0, 2); // subr[i][j] = subr[i][j] / -r[3][3]). double divr = -r.getEntry(3, 3); for (int i = 0; i < subr.getRowDimension(); i++) { for (int j = 0; j < subr.getRowDimension(); j++) { subr.setEntry(i, j, subr.getEntry(i, j) / divr); } } // Get the eigenvalues and eigenvectors. EigenDecomposition ed = new EigenDecomposition(subr, 0); evals = ed.getRealEigenvalues(); evecs = ed.getEigenvector(0); evecs1 = ed.getEigenvector(1); evecs2 = ed.getEigenvector(2); // Find the radii of the ellipsoid. radii = findRadii(evals); }
From source file:com.joptimizer.optimizers.OptimizationRequestHandler.java
/** * Find a solution of the linear (equalities) system A.x = b. * @see "S.Boyd and L.Vandenberghe, Convex Optimization, p. 682" *///from w w w. j a va2 s . co m protected double[] findEqFeasiblePoint(double[][] A, double[] b) throws Exception { RealMatrix AT = new Array2DRowRealMatrix(A).transpose(); int p = A.length; SingularValueDecomposition dFact1 = new SingularValueDecomposition(AT); int rangoAT = dFact1.getRank(); if (rangoAT != p) { throw new RuntimeException("Equalities matrix A must have full rank"); } QRDecomposition dFact = new QRDecomposition(AT); //A = QR RealMatrix Q1Q2 = dFact.getQ(); RealMatrix R0 = dFact.getR(); RealMatrix Q1 = Q1Q2.getSubMatrix(0, AT.getRowDimension() - 1, 0, p - 1); RealMatrix R = R0.getSubMatrix(0, p - 1, 0, p - 1); double[][] rData = R.copy().getData(); //inversion double[][] rInvData = Utils.upperTriangularMatrixUnverse(rData); RealMatrix RInv = new Array2DRowRealMatrix(rInvData); //w = Q1 * Inv([R]T) . b double[] w = Q1.operate(RInv.transpose().operate(new ArrayRealVector(b))).toArray(); return w; }
From source file:hivemall.anomaly.SingularSpectrumTransform.java
/** * Singular Value Decomposition (SVD) based naive scoring. *//*from w ww . j a v a 2 s .c o m*/ 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]; }
From source file:hivemall.utils.math.MatrixUtils.java
/** * QR decomposition for a tridiagonal matrix T. * * @see https://gist.github.com/lightcatcher/8118181 * @see http://www.ericmart.in/blog/optimizing_julia_tridiag_qr * @param T target tridiagonal matrix/*from www. j ava2s. c o m*/ * @param R output matrix for R which is the same shape as T * @param Qt output matrix for Q.T which is the same shape an T */ public static void tridiagonalQR(@Nonnull final RealMatrix T, @Nonnull final RealMatrix R, @Nonnull final RealMatrix Qt) { int n = T.getRowDimension(); Preconditions.checkArgument(n == R.getRowDimension() && n == R.getColumnDimension(), "T and R must be the same shape"); Preconditions.checkArgument(n == Qt.getRowDimension() && n == Qt.getColumnDimension(), "T and Qt must be the same shape"); // initial R = T R.setSubMatrix(T.getData(), 0, 0); // initial Qt = identity Qt.setSubMatrix(eye(n), 0, 0); for (int i = 0; i < n - 1; i++) { // Householder projection for a vector x // https://en.wikipedia.org/wiki/Householder_transformation RealVector x = T.getSubMatrix(i, i + 1, i, i).getColumnVector(0); x = unitL2norm(x); RealMatrix subR = R.getSubMatrix(i, i + 1, 0, n - 1); R.setSubMatrix(subR.subtract(x.outerProduct(subR.preMultiply(x)).scalarMultiply(2)).getData(), i, 0); RealMatrix subQt = Qt.getSubMatrix(i, i + 1, 0, n - 1); Qt.setSubMatrix(subQt.subtract(x.outerProduct(subQt.preMultiply(x)).scalarMultiply(2)).getData(), i, 0); } }