Example usage for org.apache.commons.math3.linear RealMatrix transpose

List of usage examples for org.apache.commons.math3.linear RealMatrix transpose

Introduction

In this page you can find the example usage for org.apache.commons.math3.linear RealMatrix transpose.

Prototype

RealMatrix transpose();

Source Link

Document

Returns the transpose of this matrix.

Usage

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;/*from  w w  w.ja va2s .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:net.myrrix.online.generation.MergeModels.java

public static void merge(File model1File, File model2File, File mergedModelFile) throws IOException {

    Generation model1 = GenerationSerializer.readGeneration(model1File);
    Generation model2 = GenerationSerializer.readGeneration(model2File);

    FastByIDMap<float[]> x1 = model1.getX();
    FastByIDMap<float[]> y1 = model1.getY();
    FastByIDMap<float[]> x2 = model2.getX();
    FastByIDMap<float[]> y2 = model2.getY();

    RealMatrix translation = multiply(y1, x2);

    FastByIDMap<float[]> xMerged = MatrixUtils.multiply(translation.transpose(), x1);

    FastIDSet emptySet = new FastIDSet();
    FastByIDMap<FastIDSet> knownItems = new FastByIDMap<FastIDSet>();
    LongPrimitiveIterator it = xMerged.keySetIterator();
    while (it.hasNext()) {
        knownItems.put(it.nextLong(), emptySet);
    }/*from  w  ww . jav  a2 s . c  o  m*/

    FastIDSet x1ItemTagIDs = model1.getItemTagIDs();
    FastIDSet y2UserTagIDs = model2.getUserTagIDs();

    Generation merged = new Generation(knownItems, xMerged, y2, x1ItemTagIDs, y2UserTagIDs);
    GenerationSerializer.writeGeneration(merged, mergedModelFile);
}

From source file:com.google.location.lbs.gnss.gps.pseudorange.EcefToTopocentricConverter.java

/**
 * Transformation of {@code inputVectorMeters} with origin at {@code originECEFMeters} into
 * topocentric coordinate system. The result is {@code TopocentricAEDValues} containing azimuth
 * from north +ve clockwise, radians; elevation angle, radians; distance, vector length meters
 *
 * <p>Source: http://www.navipedia.net/index.php/Transformations_between_ECEF_and_ENU_coordinates
 * http://kom.aau.dk/~borre/life-l99/topocent.m
 *
 *///from ww  w . java  2s  .  c om
public static TopocentricAEDValues convertCartesianToTopocentericRadMeters(final double[] originECEFMeters,
        final double[] inputVectorMeters) {

    GeodeticLlaValues latLngAlt = Ecef2LlaConverter.convertECEFToLLACloseForm(originECEFMeters[0],
            originECEFMeters[1], originECEFMeters[2]);

    RealMatrix rotationMatrix = Ecef2EnuConverter
            .getRotationMatrix(latLngAlt.latitudeRadians, latLngAlt.longitudeRadians).transpose();
    double[] eastNorthUpVectorMeters = GpsMathOperations
            .matrixByColVectMultiplication(rotationMatrix.transpose().getData(), inputVectorMeters);
    double eastMeters = eastNorthUpVectorMeters[EAST_IDX];
    double northMeters = eastNorthUpVectorMeters[NORTH_IDX];
    double upMeters = eastNorthUpVectorMeters[UP_IDX];

    // calculate azimuth, elevation and height from the ENU values
    double horizontalDistanceMeters = Math.hypot(eastMeters, northMeters);
    double azimuthRadians;
    double elevationRadians;

    if (horizontalDistanceMeters < MIN_DISTANCE_MAGNITUDE_METERS) {
        elevationRadians = Math.PI / 2.0;
        azimuthRadians = 0;
    } else {
        elevationRadians = Math.atan2(upMeters, horizontalDistanceMeters);
        azimuthRadians = Math.atan2(eastMeters, northMeters);
    }
    if (azimuthRadians < 0) {
        azimuthRadians += 2 * Math.PI;
    }

    double distanceMeters = Math.sqrt(Math.pow(inputVectorMeters[0], 2) + Math.pow(inputVectorMeters[1], 2)
            + Math.pow(inputVectorMeters[2], 2));
    return new TopocentricAEDValues(elevationRadians, azimuthRadians, distanceMeters);
}

From source file:com.rapidminer.tools.math.LinearRegression.java

/** Calculates the coefficients of linear ridge regression. */
public static double[] performRegression(Matrix a, Matrix b, double ridge) {
    RealMatrix x = MatrixUtils.createRealMatrix(a.getArray());
    RealMatrix y = MatrixUtils.createRealMatrix(b.getArray());
    int numberOfColumns = x.getColumnDimension();
    double[] coefficients = new double[numberOfColumns];
    RealMatrix xTransposed = x.transpose();
    Matrix result;//from  ww  w . j av a  2 s .  c  om
    boolean finished = false;
    while (!finished) {
        RealMatrix xTx = xTransposed.multiply(x);

        for (int i = 0; i < numberOfColumns; i++) {
            xTx.addToEntry(i, i, ridge);
        }

        RealMatrix xTy = xTransposed.multiply(y);
        coefficients = xTy.getColumn(0);

        try {
            // do not use Apache LUDecomposition for solve instead because it creates different
            // results
            result = new Matrix(xTx.getData()).solve(new Matrix(coefficients, coefficients.length));
            for (int i = 0; i < numberOfColumns; i++) {
                coefficients[i] = result.get(i, 0);
            }
            finished = true;
        } catch (Exception ex) {
            double ridgeOld = ridge;
            if (ridge > 0) {
                ridge *= 10;
            } else {
                ridge = 0.0000001;
            }
            finished = false;
            logger.warning("Error during calculation: " + ex.getMessage() + ": Increasing ridge factor from "
                    + ridgeOld + " to " + ridge);
        }
    }
    return coefficients;
}

From source file:edu.oregonstate.eecs.mcplan.ml.MatrixAlgorithms.java

/**
 * Computes the inverse of a matrix using the singular value decomposition.
 * /*from   w  w  w  .ja  v a  2 s.c o  m*/
 * 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:edu.washington.gs.skyline.model.quantification.WeightedRegression.java

public static double[] weighted(double[][] x, double[] y, double[] weights, boolean intercept) {
    RealMatrix predictor;
    if (intercept) {
        int nRows = x.length;
        int nCols = x[0].length + 1;
        predictor = MatrixUtils.createRealMatrix(nRows, nCols);
        for (int iRow = 0; iRow < nRows; iRow++) {
            predictor.setEntry(iRow, 0, 1.0);
            for (int iCol = 1; iCol < nCols; iCol++) {
                predictor.setEntry(iRow, iCol, x[iRow][iCol - 1]);
            }//from   w  w  w.ja va2  s.c o  m
        }
    } else {
        predictor = MatrixUtils.createRealMatrix(x);
    }
    RealVector responseVector = MatrixUtils.createRealVector(y);
    RealMatrix weightsMatrix = MatrixUtils.createRealDiagonalMatrix(weights);
    RealMatrix predictorTransposed = predictor.transpose();
    RealMatrix predictorTransposedTimesWeights = predictorTransposed
            .multiply(weightsMatrix.multiply(predictor));
    CholeskyDecomposition choleskyDecomposition = new CholeskyDecomposition(predictorTransposedTimesWeights);
    RealVector vectorToSolve = predictorTransposed.operate(weightsMatrix.operate(responseVector));
    RealVector result = choleskyDecomposition.getSolver().solve(vectorToSolve);
    return result.toArray();
}

From source file:hivemall.utils.math.MatrixUtils.java

/**
 * Lanczos tridiagonalization for a symmetric matrix C to make s * s tridiagonal matrix T.
 *
 * @see http://www.cas.mcmaster.ca/~qiao/publications/spie05.pdf
 * @param C target symmetric matrix/*from   w  w  w. j  a va2  s .c  o  m*/
 * @param a initial vector
 * @param T result is stored here
 */
public static void lanczosTridiagonalization(@Nonnull final RealMatrix C, @Nonnull final double[] a,
        @Nonnull final RealMatrix T) {
    Preconditions.checkArgument(Arrays.deepEquals(C.getData(), C.transpose().getData()),
            "Target matrix C must be a symmetric matrix");
    Preconditions.checkArgument(C.getColumnDimension() == a.length,
            "Column size of A and length of a should be same");
    Preconditions.checkArgument(T.getRowDimension() == T.getColumnDimension(), "T must be a square matrix");

    int s = T.getRowDimension();

    // initialize T with zeros
    T.setSubMatrix(new double[s][s], 0, 0);

    RealVector a0 = new ArrayRealVector(a.length);
    RealVector r = new ArrayRealVector(a);

    double beta0 = 1.d;

    for (int i = 0; i < s; i++) {
        RealVector a1 = r.mapDivide(beta0);
        RealVector Ca1 = C.operate(a1);

        double alpha1 = a1.dotProduct(Ca1);

        r = Ca1.add(a1.mapMultiply(-1.d * alpha1)).add(a0.mapMultiply(-1.d * beta0));

        double beta1 = r.getNorm();

        T.setEntry(i, i, alpha1);
        if (i - 1 >= 0) {
            T.setEntry(i, i - 1, beta0);
        }
        if (i + 1 < s) {
            T.setEntry(i, i + 1, beta1);
        }

        a0 = a1.copy();
        beta0 = beta1;
    }
}

From source file:hivemall.utils.math.MatrixUtils.java

/**
 * Find eigenvalues and eigenvectors of given tridiagonal matrix T.
 *
 * @see http://web.csulb.edu/~tgao/math423/s94.pdf
 * @see http://stats.stackexchange.com/questions/20643/finding-matrix-eigenvectors-using-qr-
 *      decomposition/*w  w w  . j ava  2  s.c  om*/
 * @param T target tridiagonal matrix
 * @param nIter number of iterations for the QR method
 * @param eigvals eigenvalues are stored here
 * @param eigvecs eigenvectors are stored here
 */
public static void tridiagonalEigen(@Nonnull final RealMatrix T, @Nonnull final int nIter,
        @Nonnull final double[] eigvals, @Nonnull final RealMatrix eigvecs) {
    Preconditions.checkArgument(Arrays.deepEquals(T.getData(), T.transpose().getData()),
            "Target matrix T must be a symmetric (tridiagonal) matrix");
    Preconditions.checkArgument(eigvecs.getRowDimension() == eigvecs.getColumnDimension(),
            "eigvecs must be a square matrix");
    Preconditions.checkArgument(T.getRowDimension() == eigvecs.getRowDimension(),
            "T and eigvecs must be the same shape");
    Preconditions.checkArgument(eigvals.length == eigvecs.getRowDimension(),
            "Number of eigenvalues and eigenvectors must be same");

    int nEig = eigvals.length;

    // initialize eigvecs as an identity matrix
    eigvecs.setSubMatrix(eye(nEig), 0, 0);

    RealMatrix T_ = T.copy();

    for (int i = 0; i < nIter; i++) {
        // QR decomposition for the tridiagonal matrix T
        RealMatrix R = new Array2DRowRealMatrix(nEig, nEig);
        RealMatrix Qt = new Array2DRowRealMatrix(nEig, nEig);
        tridiagonalQR(T_, R, Qt);

        RealMatrix Q = Qt.transpose();
        T_ = R.multiply(Q);
        eigvecs.setSubMatrix(eigvecs.multiply(Q).getData(), 0, 0);
    }

    // diagonal elements correspond to the eigenvalues
    for (int i = 0; i < nEig; i++) {
        eigvals[i] = T_.getEntry(i, i);
    }
}

From source file:gamlss.utilities.MatrixFunctions.java

/**
* <p>Compute the "hat" matrix.//from w  w  w.  j  av a2 s .c  o m
* </p>
* <p>The hat matrix is defined in terms of the design matrix X
*  by X(X<sup>T</sup>X)<sup>-1</sup>X<sup>T</sup>
* </p>
* <p>The implementation here uses the QR decomposition to compute the
* hat matrix as Q I<sub>p</sub>Q<sup>T</sup> where I<sub>p</sub> is the
* p-dimensional identity matrix augmented by 0's.  This computational
* formula is from "The Hat Matrix in Regression and ANOVA",
* David C. Hoaglin and Roy E. Welsch,
* <i>The American Statistician</i>, Vol. 32, No. 1 (Feb., 1978), pp. 17-22.
*@param m - matrix
* @return the hat matrix
*/
public static RealMatrix calculateHat(final BlockRealMatrix m) {
    QRDecomposition qr = new QRDecomposition(m);
    // Create augmented identity matrix
    RealMatrix qM = qr.getQ();
    final int p = qr.getR().getColumnDimension();
    final int n = qM.getColumnDimension();
    Array2DRowRealMatrix augI = new Array2DRowRealMatrix(n, n);
    double[][] augIData = augI.getDataRef();
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i == j && i < p) {
                augIData[i][j] = 1d;
            } else {
                augIData[i][j] = 0d;
            }
        }
    }
    // Compute and return Hat matrix
    return qM.multiply(augI).multiply(qM.transpose());
}

From source file:io.warp10.script.functions.TRANSPOSE.java

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {

    Object o = stack.pop();//from w  ww.j  a va2  s .c o  m

    if (o instanceof RealMatrix) {
        RealMatrix matrix = (RealMatrix) o;

        stack.push(matrix.transpose());
    } else {
        throw new WarpScriptException(getName() + " expects a matrix on top of the stack.");
    }

    return stack;
}