List of usage examples for org.apache.commons.math3.linear RealMatrix setEntry
void setEntry(int row, int column, double value) throws OutOfRangeException;
From source file:org.lenskit.mf.MFModel.java
private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { featureCount = input.readInt();/* w w w. ja v a 2s . c om*/ userCount = input.readInt(); itemCount = input.readInt(); RealMatrix umat = MatrixUtils.createRealMatrix(userCount, featureCount); for (int i = 0; i < userCount; i++) { for (int j = 0; j < featureCount; j++) { umat.setEntry(i, j, input.readDouble()); } } userMatrix = umat; RealMatrix imat = MatrixUtils.createRealMatrix(itemCount, featureCount); for (int i = 0; i < itemCount; i++) { for (int j = 0; j < featureCount; j++) { imat.setEntry(i, j, input.readDouble()); } } itemMatrix = imat; userIndex = (KeyIndex) input.readObject(); itemIndex = (KeyIndex) input.readObject(); if (userIndex.size() != userMatrix.getRowDimension()) { throw new InvalidObjectException("user matrix and index have different row counts"); } if (itemIndex.size() != itemMatrix.getRowDimension()) { throw new InvalidObjectException("item matrix and index have different row counts"); } }
From source file:org.lenskit.pf.HPFModelProvider.java
@Override public HPFModel get() { final int userNum = ratings.getUserIndex().size(); final int itemNum = ratings.getItemIndex().size(); final int featureCount = hyperParameters.getFeatureCount(); final double a = hyperParameters.getUserWeightShpPrior(); final double aPrime = hyperParameters.getUserActivityShpPrior(); final double bPrime = hyperParameters.getUserActivityPriorMean(); final double c = hyperParameters.getItemWeightShpPrior(); final double cPrime = hyperParameters.getItemActivityShpPrior(); final double dPrime = hyperParameters.getItemActivityPriorMean(); final double kappaShpU = aPrime + featureCount * a; final double tauShpI = cPrime + featureCount * c; RealMatrix gammaShp = MatrixUtils.createRealMatrix(userNum, featureCount); RealMatrix gammaRte = MatrixUtils.createRealMatrix(userNum, featureCount); RealVector kappaShp = MatrixUtils.createRealVector(new double[userNum]); RealVector kappaRte = MatrixUtils.createRealVector(new double[userNum]); RealMatrix lambdaShp = MatrixUtils.createRealMatrix(itemNum, featureCount); RealMatrix lambdaRte = MatrixUtils.createRealMatrix(itemNum, featureCount); RealVector tauShp = MatrixUtils.createRealVector(new double[itemNum]); RealVector tauRte = MatrixUtils.createRealVector(new double[itemNum]); RealMatrix gammaShpNext = MatrixUtils.createRealMatrix(userNum, featureCount); RealMatrix lambdaShpNext = MatrixUtils.createRealMatrix(itemNum, featureCount); gammaShpNext = gammaShpNext.scalarAdd(a); lambdaShpNext = lambdaShpNext.scalarAdd(c); RealVector phiUI = MatrixUtils.createRealVector(new double[featureCount]); initialize(gammaShp, gammaRte, kappaRte, kappaShp, lambdaShp, lambdaRte, tauRte, tauShp); logger.info("initialization finished"); final List<RatingMatrixEntry> train = ratings.getTrainRatings(); final List<RatingMatrixEntry> validation = ratings.getValidationRatings(); double avgPLLPre = Double.MAX_VALUE; double avgPLLCurr = 0.0; double diffPLL = 1.0; int iterCount = 1; while (iterCount < maxIterCount && diffPLL > threshold) { // update phi Iterator<RatingMatrixEntry> allUIPairs = train.iterator(); while (allUIPairs.hasNext()) { RatingMatrixEntry entry = allUIPairs.next(); int item = entry.getItemIndex(); int user = entry.getUserIndex(); double ratingUI = entry.getValue(); if (ratingUI <= 0) { continue; }//from ww w . j a v a2 s. c om for (int k = 0; k < featureCount; k++) { double gammaShpUK = gammaShp.getEntry(user, k); double gammaRteUK = gammaRte.getEntry(user, k); double lambdaShpIK = lambdaShp.getEntry(item, k); double lambdaRteIK = lambdaRte.getEntry(item, k); double phiUIK = Gamma.digamma(gammaShpUK) - Math.log(gammaRteUK) + Gamma.digamma(lambdaShpIK) - Math.log(lambdaRteIK); phiUI.setEntry(k, phiUIK); } logNormalize(phiUI); if (ratingUI > 1) { phiUI.mapMultiplyToSelf(ratingUI); } for (int k = 0; k < featureCount; k++) { double value = phiUI.getEntry(k); gammaShpNext.addToEntry(user, k, value); lambdaShpNext.addToEntry(item, k, value); } } logger.info("iteration {} first phrase update finished", iterCount); RealVector gammaRteSecondTerm = MatrixUtils.createRealVector(new double[featureCount]); for (int k = 0; k < featureCount; k++) { double gammaRteUK = 0.0; for (int item = 0; item < itemNum; item++) { gammaRteUK += lambdaShp.getEntry(item, k) / lambdaRte.getEntry(item, k); } gammaRteSecondTerm.setEntry(k, gammaRteUK); } // update user parameters double kappaRteFirstTerm = aPrime / bPrime; for (int user = 0; user < userNum; user++) { double gammaRteUKFirstTerm = kappaShp.getEntry(user) / kappaRte.getEntry(user); double kappaRteU = 0.0; for (int k = 0; k < featureCount; k++) { double gammaShpUK = gammaShpNext.getEntry(user, k); gammaShp.setEntry(user, k, gammaShpUK); gammaShpNext.setEntry(user, k, a); double gammaRteUK = gammaRteSecondTerm.getEntry(k); gammaRteUK += gammaRteUKFirstTerm; gammaRte.setEntry(user, k, gammaRteUK); kappaRteU += gammaShpUK / gammaRteUK; } kappaRteU += kappaRteFirstTerm; kappaRte.setEntry(user, kappaRteU); } logger.info("iteration {} second phrase update finished", iterCount); RealVector lambdaRteSecondTerm = MatrixUtils.createRealVector(new double[featureCount]); for (int k = 0; k < featureCount; k++) { double lambdaRteIK = 0.0; for (int user = 0; user < userNum; user++) { lambdaRteIK += gammaShp.getEntry(user, k) / gammaRte.getEntry(user, k); } lambdaRteSecondTerm.setEntry(k, lambdaRteIK); } // update item parameters double tauRteFirstTerm = cPrime / dPrime; for (int item = 0; item < itemNum; item++) { double lambdaRteFirstTerm = tauShp.getEntry(item) / tauRte.getEntry(item); double tauRteI = 0.0; for (int k = 0; k < featureCount; k++) { double lambdaShpIK = lambdaShpNext.getEntry(item, k); lambdaShp.setEntry(item, k, lambdaShpIK); lambdaShpNext.setEntry(item, k, c); double lambdaRteIK = lambdaRteSecondTerm.getEntry(k); // plus first term lambdaRteIK += lambdaRteFirstTerm; lambdaRte.setEntry(item, k, lambdaRteIK); // update tauRteI second term tauRteI += lambdaShpIK / lambdaRteIK; } tauRteI += tauRteFirstTerm; tauRte.setEntry(item, tauRteI); } logger.info("iteration {} third phrase update finished", iterCount); // compute average predictive log likelihood of validation data per {@code iterationfrequency} iterations if (iterCount == 1) { for (int user = 0; user < userNum; user++) { kappaShp.setEntry(user, kappaShpU); } for (int item = 0; item < itemNum; item++) { tauShp.setEntry(item, tauShpI); } } if ((iterCount % iterationFrequency) == 0) { Iterator<RatingMatrixEntry> valIter = validation.iterator(); avgPLLCurr = 0.0; while (valIter.hasNext()) { RatingMatrixEntry ratingEntry = valIter.next(); int user = ratingEntry.getUserIndex(); int item = ratingEntry.getItemIndex(); double rating = ratingEntry.getValue(); double eThetaBeta = 0.0; for (int k = 0; k < featureCount; k++) { double eThetaUK = gammaShp.getEntry(user, k) / gammaRte.getEntry(user, k); double eBetaIK = lambdaShp.getEntry(item, k) / lambdaRte.getEntry(item, k); eThetaBeta += eThetaUK * eBetaIK; } double pLL = 0.0; if (isProbPredition) { pLL = (rating == 0) ? (-eThetaBeta) : Math.log(1 - Math.exp(-eThetaBeta)); } else { pLL = rating * Math.log(eThetaBeta) - eThetaBeta - Gamma.logGamma(rating + 1); } avgPLLCurr += pLL; } avgPLLCurr = avgPLLCurr / validation.size(); diffPLL = Math.abs((avgPLLCurr - avgPLLPre) / avgPLLPre); avgPLLPre = avgPLLCurr; logger.info("iteration {} with current average predictive log likelihood {} and the change is {}", iterCount, avgPLLCurr, diffPLL); } iterCount++; } // construct feature matrix used by HPFModel RealMatrix eTheta = MatrixUtils.createRealMatrix(userNum, featureCount); RealMatrix eBeta = MatrixUtils.createRealMatrix(itemNum, featureCount); for (int user = 0; user < userNum; user++) { RealVector gammaShpU = gammaShp.getRowVector(user); RealVector gammaRteU = gammaRte.getRowVector(user); RealVector eThetaU = gammaShpU.ebeDivide(gammaRteU); eTheta.setRowVector(user, eThetaU); logger.info("Training user {} features finished", user); } for (int item = 0; item < itemNum; item++) { RealVector lambdaShpI = lambdaShp.getRowVector(item); RealVector lambdaRteI = lambdaRte.getRowVector(item); RealVector eBetaI = lambdaShpI.ebeDivide(lambdaRteI); eBeta.setRowVector(item, eBetaI); logger.info("Training item {} features finished", item); } KeyIndex uidx = ratings.getUserIndex(); KeyIndex iidx = ratings.getItemIndex(); return new HPFModel(eTheta, eBeta, uidx, iidx); }
From source file:org.lenskit.pf.HPFModelProvider.java
/** * Initialization of parameter matrices//from www . j a v a2s .c om * @param gammaShp * @param gammaRte * @param kappaRte * @param kappaShp * @param lambdaShp * @param lambdaRte * @param tauRte * @param tauShp */ public void initialize(RealMatrix gammaShp, RealMatrix gammaRte, RealVector kappaRte, RealVector kappaShp, RealMatrix lambdaShp, RealMatrix lambdaRte, RealVector tauRte, RealVector tauShp) { final int userNum = ratings.getUserIndex().size(); final int itemNum = ratings.getItemIndex().size(); final int featureCount = hyperParameters.getFeatureCount(); final double a = hyperParameters.getUserWeightShpPrior(); final double aPrime = hyperParameters.getUserActivityShpPrior(); final double bPrime = hyperParameters.getUserActivityPriorMean(); final double c = hyperParameters.getItemWeightShpPrior(); final double cPrime = hyperParameters.getItemActivityShpPrior(); final double dPrime = hyperParameters.getItemActivityPriorMean(); // Initialization Random random = new Random(rndSeed); final double kRte = aPrime + featureCount; final double tRte = cPrime + featureCount; for (int u = 0; u < userNum; u++) { for (int k = 0; k < featureCount; k++) { double valueShp = a + maxOffsetShp * random.nextDouble(); double valueRte = aPrime + maxOffsetRte * random.nextDouble(); gammaShp.setEntry(u, k, valueShp); gammaRte.setEntry(u, k, valueRte); } double kShp = aPrime + maxOffsetShp * random.nextDouble(); kappaRte.setEntry(u, kRte); kappaShp.setEntry(u, kShp); } for (int i = 0; i < itemNum; i++) { for (int k = 0; k < featureCount; k++) { double valueShp = c + maxOffsetShp * random.nextDouble(); double valueRte = cPrime + maxOffsetRte * random.nextDouble(); lambdaShp.setEntry(i, k, valueShp); lambdaRte.setEntry(i, k, valueRte); } double tShp = cPrime + maxOffsetShp * random.nextDouble(); tauRte.setEntry(i, tRte); tauShp.setEntry(i, tShp); } }
From source file:org.nd4j.linalg.Nd4jTestsComparisonFortran.java
@Test public void testGemvApacheCommons() { int[] rowsArr = new int[] { 4, 4, 4, 8, 8, 8 }; int[] colsArr = new int[] { 2, 1, 10, 2, 1, 10 }; for (int x = 0; x < rowsArr.length; x++) { int rows = rowsArr[x]; int cols = colsArr[x]; List<Pair<INDArray, String>> matrices = NDArrayCreationUtil.getAllTestMatricesWithShape(rows, cols, 12345);//w w w .j a v a 2 s. co m List<Pair<INDArray, String>> vectors = NDArrayCreationUtil.getAllTestMatricesWithShape(cols, 1, 12345); for (int i = 0; i < matrices.size(); i++) { for (int j = 0; j < vectors.size(); j++) { Pair<INDArray, String> p1 = matrices.get(i); Pair<INDArray, String> p2 = vectors.get(j); String errorMsg = getTestWithOpsErrorMsg(i, j, "mmul", p1, p2); INDArray m = p1.getFirst(); INDArray v = p2.getFirst(); RealMatrix rm = new BlockRealMatrix(m.rows(), m.columns()); for (int r = 0; r < m.rows(); r++) { for (int c = 0; c < m.columns(); c++) { double d = m.getDouble(r, c); rm.setEntry(r, c, d); } } RealMatrix rv = new BlockRealMatrix(cols, 1); for (int r = 0; r < v.rows(); r++) { double d = v.getDouble(r, 0); rv.setEntry(r, 0, d); } INDArray gemv = m.mmul(v); RealMatrix gemv2 = rm.multiply(rv); assertArrayEquals(new int[] { rows, 1 }, gemv.shape()); assertArrayEquals(new int[] { rows, 1 }, new int[] { gemv2.getRowDimension(), gemv2.getColumnDimension() }); //Check entries: for (int r = 0; r < rows; r++) { double exp = gemv2.getEntry(r, 0); double act = gemv.getDouble(r, 0); assertEquals(errorMsg, exp, act, 1e-5); } } } } }
From source file:org.opentestsystem.airose.linear.Matrices.java
public static void copyTo(Matrix matrix, Matrix output) { RealMatrix source = matrix._matrix;//from w ww. j ava 2s . c o m RealMatrix destination = output._matrix; for (int row = 0; row < source.getRowDimension(); ++row) { for (int column = 0; column < source.getColumnDimension(); ++column) { destination.setEntry(row, column, source.getEntry(row, column)); } } }
From source file:org.orekit.frames.TransformTest.java
@Test public void testLinear() { RandomGenerator random = new Well19937a(0x14f6411217b148d8l); for (int n = 0; n < 100; ++n) { Transform t = randomTransform(random); // build an equivalent linear transform by extracting raw translation/rotation RealMatrix linearA = MatrixUtils.createRealMatrix(3, 4); linearA.setSubMatrix(t.getRotation().getMatrix(), 0, 0); Vector3D rt = t.getRotation().applyTo(t.getTranslation()); linearA.setEntry(0, 3, rt.getX()); linearA.setEntry(1, 3, rt.getY()); linearA.setEntry(2, 3, rt.getZ()); // build an equivalent linear transform by observing transformed points RealMatrix linearB = MatrixUtils.createRealMatrix(3, 4); Vector3D p0 = t.transformPosition(Vector3D.ZERO); Vector3D pI = t.transformPosition(Vector3D.PLUS_I).subtract(p0); Vector3D pJ = t.transformPosition(Vector3D.PLUS_J).subtract(p0); Vector3D pK = t.transformPosition(Vector3D.PLUS_K).subtract(p0); linearB.setColumn(0, new double[] { pI.getX(), pI.getY(), pI.getZ() }); linearB.setColumn(1, new double[] { pJ.getX(), pJ.getY(), pJ.getZ() }); linearB.setColumn(2, new double[] { pK.getX(), pK.getY(), pK.getZ() }); linearB.setColumn(3, new double[] { p0.getX(), p0.getY(), p0.getZ() }); // both linear transforms should be equal Assert.assertEquals(0.0, linearB.subtract(linearA).getNorm(), 1.0e-15 * linearA.getNorm()); for (int i = 0; i < 100; ++i) { Vector3D p = randomVector(1.0e3, random); Vector3D q = t.transformPosition(p); double[] qA = linearA.operate(new double[] { p.getX(), p.getY(), p.getZ(), 1.0 }); Assert.assertEquals(q.getX(), qA[0], 1.0e-13 * p.getNorm()); Assert.assertEquals(q.getY(), qA[1], 1.0e-13 * p.getNorm()); Assert.assertEquals(q.getZ(), qA[2], 1.0e-13 * p.getNorm()); double[] qB = linearB.operate(new double[] { p.getX(), p.getY(), p.getZ(), 1.0 }); Assert.assertEquals(q.getX(), qB[0], 1.0e-10 * p.getNorm()); Assert.assertEquals(q.getY(), qB[1], 1.0e-10 * p.getNorm()); Assert.assertEquals(q.getZ(), qB[2], 1.0e-10 * p.getNorm()); }//from ww w. j av a 2s.c om } }
From source file:org.orekit.utils.AngularCoordinates.java
/** Find a vector from two known cross products. * <p>//from w ww . j av a2 s .c o m * We want to find such that: v? = c? and v = c * </p> * <p> * The first equation ( v? = c?) will always be fulfilled exactly, * and the second one will be fulfilled if possible. * </p> * @param v1 vector forming the first known cross product * @param c1 know vector for cross product v? * @param v2 vector forming the second known cross product * @param c2 know vector for cross product v * @param tolerance relative tolerance factor used to check singularities * @return vector such that: v? = c? and v = c * @exception MathIllegalArgumentException if vectors are inconsistent and * no solution can be found */ private static Vector3D inverseCrossProducts(final Vector3D v1, final Vector3D c1, final Vector3D v2, final Vector3D c2, final double tolerance) throws MathIllegalArgumentException { final double v12 = v1.getNormSq(); final double v1n = FastMath.sqrt(v12); final double v22 = v2.getNormSq(); final double v2n = FastMath.sqrt(v22); final double threshold = tolerance * FastMath.max(v1n, v2n); Vector3D omega; try { // create the over-determined linear system representing the two cross products final RealMatrix m = MatrixUtils.createRealMatrix(6, 3); m.setEntry(0, 1, v1.getZ()); m.setEntry(0, 2, -v1.getY()); m.setEntry(1, 0, -v1.getZ()); m.setEntry(1, 2, v1.getX()); m.setEntry(2, 0, v1.getY()); m.setEntry(2, 1, -v1.getX()); m.setEntry(3, 1, v2.getZ()); m.setEntry(3, 2, -v2.getY()); m.setEntry(4, 0, -v2.getZ()); m.setEntry(4, 2, v2.getX()); m.setEntry(5, 0, v2.getY()); m.setEntry(5, 1, -v2.getX()); final RealVector rhs = MatrixUtils.createRealVector( new double[] { c1.getX(), c1.getY(), c1.getZ(), c2.getX(), c2.getY(), c2.getZ() }); // find the best solution we can final DecompositionSolver solver = new QRDecomposition(m, threshold).getSolver(); final RealVector v = solver.solve(rhs); omega = new Vector3D(v.getEntry(0), v.getEntry(1), v.getEntry(2)); } catch (SingularMatrixException sme) { // handle some special cases for which we can compute a solution final double c12 = c1.getNormSq(); final double c1n = FastMath.sqrt(c12); final double c22 = c2.getNormSq(); final double c2n = FastMath.sqrt(c22); if (c1n <= threshold && c2n <= threshold) { // simple special case, velocities are cancelled return Vector3D.ZERO; } else if (v1n <= threshold && c1n >= threshold) { // this is inconsistent, if v? is zero, c? must be 0 too throw new NumberIsTooLargeException(c1n, 0, true); } else if (v2n <= threshold && c2n >= threshold) { // this is inconsistent, if v is zero, c must be 0 too throw new NumberIsTooLargeException(c2n, 0, true); } else if (Vector3D.crossProduct(v1, v2).getNorm() <= threshold && v12 > threshold) { // simple special case, v is redundant with v?, we just ignore it // use the simplest : orthogonal to both v? and c? omega = new Vector3D(1.0 / v12, Vector3D.crossProduct(v1, c1)); } else { throw sme; } } // check results final double d1 = Vector3D.distance(Vector3D.crossProduct(omega, v1), c1); if (d1 > threshold) { throw new NumberIsTooLargeException(d1, 0, true); } final double d2 = Vector3D.distance(Vector3D.crossProduct(omega, v2), c2); if (d2 > threshold) { throw new NumberIsTooLargeException(d2, 0, true); } return omega; }
From source file:org.rhwlab.BHC.Testing.java
static public void main(String[] args) { String[] tokens = "0.011332651026552858 3.41268617023919E-4 0.0018087352262063756 3.4126861702391887E-4 0.013068389158168082 -0.0018712410627799538 0.001808735226206376 -0.0018712410627799538 0.012536567307833844" .split(" "); RealMatrix m = new Array2DRowRealMatrix(3, 3); for (int r = 0; r < 3; ++r) { for (int c = 0; c < 3; ++c) { m.setEntry(r, c, Double.valueOf(tokens[3 * r + c])); }/*from w w w .j a v a2 s. c o m*/ } LUDecomposition lud = new LUDecomposition(m); RealMatrix mInv = lud.getSolver().getInverse(); EigenDecomposition decomp = new EigenDecomposition(lud.getSolver().getInverse()); double[] e = decomp.getRealEigenvalues(); int thsdfui = 0; }
From source file:org.rhwlab.dispim.nucleus.NamedNucleusFile.java
License:asdf
static public RealMatrix rotationMatrix(Vector3D A, Vector3D B) { Vector3D a = A.normalize();//from w ww . j av a 2 s . c om Vector3D b = B.normalize(); Vector3D v = a.crossProduct(b); double s = v.getNormSq(); double c = a.dotProduct(b); RealMatrix vx = MatrixUtils.createRealMatrix(3, 3); vx.setEntry(1, 0, v.getZ()); vx.setEntry(0, 1, -v.getZ()); vx.setEntry(2, 0, -v.getY()); vx.setEntry(0, 2, v.getY()); vx.setEntry(2, 1, v.getX()); vx.setEntry(1, 2, -v.getX()); RealMatrix vx2 = vx.multiply(vx); RealMatrix scaled = vx2.scalarMultiply((1.0 - c) / s); RealMatrix ident = MatrixUtils.createRealIdentityMatrix(3); RealMatrix sum = vx.add(scaled); RealMatrix ret = ident.add(sum); return ret; }
From source file:org.rhwlab.dispim.nucleus.Nucleus.java
private RealMatrix reverseHandedness(RealMatrix m) { RealMatrix ret = m.copy(); for (int c = 0; c < m.getColumnDimension(); ++c) { ret.setEntry(0, c, -m.getEntry(0, c)); }/*w w w. j ava 2s . co m*/ return ret; }