List of usage examples for org.apache.commons.math3.linear RealMatrix add
RealMatrix add(RealMatrix m) throws MatrixDimensionMismatchException;
From source file:com.itemanalysis.psychometrics.mixture.MvNormalMixtureModel.java
private void setCommonCovariance(RealMatrix[] cov) { RealMatrix tempS = new Array2DRowRealMatrix(dimensions, dimensions); for (int g = 0; g < groups; g++) { tempS = tempS.add(cov[g].scalarMultiply(compDistribution[g].getMixingProportion())); }//from w w w . j a v a 2s . co m for (int g = 0; g < groups; g++) { cov[g] = tempS; } }
From source file:com.cloudera.oryx.app.serving.als.model.ALSServingModel.java
public Solver getYTYSolver() { Solver cached = cachedYTYSolver.get(); if (cached != null) { return cached; }/* www . j av a2 s . c o m*/ RealMatrix YTY = null; for (FeatureVectors yPartition : Y) { RealMatrix YTYpartial = yPartition.getVTV(); if (YTYpartial != null) { YTY = YTY == null ? YTYpartial : YTY.add(YTYpartial); } } // Possible to compute this twice, but not a big deal Solver newYTYSolver = LinearSystemSolver.getSolver(YTY); cachedYTYSolver.set(newYTYSolver); return newYTYSolver; }
From source file:com.analog.lyric.dimple.solvers.sumproduct.customFactors.CustomComplexGaussianPolynomial.java
private Object[] calculateWeightedSums(Complex[] in) { double[] means = new double[] { 0, 0 }; for (int i = 0; i < in.length; i++) { means[0] += in[i].getReal();/*from www . j av a 2s. c om*/ means[1] += in[i].getImaginary(); } means[0] /= in.length; means[1] /= in.length; RealMatrix cm = createRealMatrix(2, 2); RealVector mm = wrapRealVector(means); for (int i = 0; i < in.length; i++) { RealVector m = createRealVector(new double[] { in[i].getReal(), in[i].getImaginary() }); RealVector m2 = m.subtract(mm); cm = cm.add(m2.outerProduct(m2)); } cm = cm.scalarMultiply(1.0 / in.length); return new Object[] { new Complex(means[0], means[1]), matrixGetDataRef(cm) }; }
From source file:hulo.localization.models.obs.GaussianProcess.java
public GaussianProcess fit(double[][] X, double[][] Y) { int ns = X.length; this.X = X;/*from w w w . jav a 2 s . com*/ this.Y = Y; // Compute Gram Matrix (Symmetric matrix) K = computeGramMatrix(X); RealMatrix KMat = MatrixUtils.createRealMatrix(K); RealMatrix sigma_n2I = MatrixUtils.createRealIdentityMatrix(ns).scalarMultiply(sigmaN * sigmaN); RealMatrix Ky = KMat.add(sigma_n2I); this.Ky = Ky.getData(); LUDecomposition LUDecomp = new LUDecomposition(Ky); detKy = LUDecomp.getDeterminant(); RealMatrix invKyMat = LUDecomp.getSolver().getInverse(); invKy = invKyMat.getData(); // Precompute dY = Y - mX int ny = Y[0].length; this.mX = new double[ns][ny]; this.dY = new double[ns][ny]; for (int i = 0; i < ns; i++) { for (int j = 0; j < ny; j++) { mX[i][j] = meanFunc(X[i], j); dY[i][j] = Y[i][j] - mX[i][j]; } } if (optConstVar == 1) { invKyDY = computeInvKyDY(invKy, dY); } return this; }
From source file:com.anhth12.lambda.app.serving.als.model.ALSServingModel.java
public Solver getYTYSolver() { RealMatrix YTY = null; for (int partition = 0; partition < Y.length; partition++) { RealMatrix YTYpartial;// w w w .ja va2 s. c o m try (AutoLock al = new AutoLock(yLocks[partition].readLock())) { YTYpartial = VectorMath.transposeTimesSelf(Y[partition].values()); } if (YTYpartial != null) { YTY = YTY == null ? YTYpartial : YTY.add(YTYpartial); } } return new LinearSystemSolver().getSolver(YTY); }
From source file:edu.oregonstate.eecs.mcplan.ml.GaussianMixtureModel.java
@Override public void run() { init();//from w w w.j a v a 2 s. c o m System.out.println("Init"); for (int i = 0; i < mu().length; ++i) { System.out.println("Mu " + i + ": " + mu()[i]); System.out.println("Sigma " + i + ": " + Sigma()[i]); } int iterations = 0; while (!converged_ && iterations++ < max_iterations_) { // Expectation makeMixture(); for (int i = 0; i < n_; ++i) { for (int j = 0; j < k_; ++j) { c_[i][j] = posterior(data_[i], j); } Fn.normalize_inplace(c_[i]); } // Maximization for (int j = 0; j < k_; ++j) { double Z = 0.0; final RealVector mu_j = new ArrayRealVector(d_); RealMatrix Sigma_j = new Array2DRowRealMatrix(d_, d_); for (int i = 0; i < n_; ++i) { final double c_ij = c_[i][j]; Z += c_ij; final RealVector x_i = new ArrayRealVector(data_[i]); // mu_j += c_ij * x_i mu_j.combineToSelf(1.0, 1.0, x_i.mapMultiply(c_ij)); final RealVector v = x_i.subtract(mu_[j]); // Sigma_j += c_ij * |v><v| Sigma_j = Sigma_j.add(v.outerProduct(v).scalarMultiply(c_ij)); } final double Zinv = 1.0 / Z; final double pi_j = Z / n_; mu_j.mapMultiplyToSelf(Zinv); Sigma_j = Sigma_j.scalarMultiply(Zinv); // converged &= hasConverged( j, pi_j, mu_j, Sigma_j ); pi_[j] = pi_j; mu_[j] = mu_j; Sigma_[j] = Sigma_j; } // debug(); final double log_likelihood = logLikelihood(); if (Math.abs(log_likelihood - old_log_likelihood_) < epsilon_) { converged_ = true; } old_log_likelihood_ = log_likelihood; } }
From source file:com.cloudera.oryx.ml.serving.als.model.ALSServingModel.java
public Solver getYTYSolver() { RealMatrix YTY = null; for (int partition = 0; partition < Y.length; partition++) { RealMatrix YTYpartial;// w ww . j a v a 2 s .c o m Lock lock = yLocks[partition].readLock(); lock.lock(); try { YTYpartial = VectorMath.transposeTimesSelf(Y[partition].values()); } finally { lock.unlock(); } if (YTYpartial != null) { YTY = YTY == null ? YTYpartial : YTY.add(YTYpartial); } } return new LinearSystemSolver().getSolver(YTY); }
From source file:edu.ucdenver.bios.power.ConditionalOrthogonalPolynomial2FactorTest.java
/** * //w ww .j av a 2s.c o m * @param checker * @param params */ private void checkPower(PowerChecker checker, String title, GLMMPowerParameters params) { /* * get orthogonal contrasts for within subject factors * Log base 2 spacing Clip (2,4,16) and Region(2,8,32) */ ArrayList<Factor> factorList = new ArrayList<Factor>(); factorList.add(factorA); factorList.add(factorB); OrthogonalPolynomialContrastCollection collection = OrthogonalPolynomials.withinSubjectContrast(factorList); params.setWithinSubjectContrast(collection.getInteractionContrast(factorList).getContrastMatrix()); // theta critical matrix used to back-tranform beta from U // THETA = {.25}#{.5 1 -1 .5}; * =Theta(cr) from 1st sentence *after* // equation 7, Coffey and Muller (2003); double[][] thetaData = { { 0.5, 1, -1, 0.5 } }; RealMatrix thetaCr = (new Array2DRowRealMatrix(thetaData)).scalarMultiply(0.25); // loop over the various sigma matrices //Test[] testList = Test.values(); GLMMTestFactory.Test[] testList = { GLMMTestFactory.Test.UNIREP, GLMMTestFactory.Test.UNIREP_BOX, GLMMTestFactory.Test.UNIREP_GEISSER_GREENHOUSE, GLMMTestFactory.Test.UNIREP_HUYNH_FELDT }; for (GLMMTestFactory.Test test : testList) { params.clearTestList(); params.addTest(test); for (RealMatrix sigStar : sigmaStars) { RealMatrix U = params.getWithinSubjectContrast(); // 1st paragraph in section 2.4, Coffey and Muller 2003 *; RealMatrix sigmaTemp = U.multiply(sigStar).multiply(U.transpose()); int dimension = sigmaTemp.getRowDimension(); RealMatrix Uother = MatrixUtils.getRealMatrixWithFilledValue(dimension, 1, 1 / Math.sqrt(U.getColumnDimension())); Uother = MatrixUtils.getHorizontalAppend(Uother, collection.getMainEffectContrast(factorA).getContrastMatrix()); Uother = MatrixUtils.getHorizontalAppend(Uother, collection.getMainEffectContrast(factorB).getContrastMatrix()); double varianceMean = (double) sigStar.getTrace() / (double) sigStar.getColumnDimension(); RealMatrix sigmaError = sigmaTemp .add(Uother.multiply(Uother.transpose()).scalarMultiply(varianceMean)); if (verbose) printMatrix("Sigma Error", sigmaError); // 1st paragraph in section 2.4, Coffey and Muller 2003 *; RealMatrix beta = thetaCr.multiply(U.transpose()); params.setSigmaError(sigmaError); params.setBeta(new FixedRandomMatrix(beta.getData(), null, false)); checker.checkPower(params); } } // output the results ValidationReportBuilder reportBuilder = new ValidationReportBuilder(); reportBuilder.createValidationReportAsStdout(checker, title, false); assertTrue("results outside tolerance: " + TOLERANCE, checker.isSASDeviationBelowTolerance(TOLERANCE)); }
From source file:edu.cudenver.bios.power.test.paper.TestConditionalOrthogonalPolynomial2Factor.java
/** * /*from ww w. j a v a2 s . com*/ * @param checker * @param outputFilename * @param params */ private void checkPower(PowerChecker checker, String title, String description, String outputFilename, GLMMPowerParameters params) { /* * get orthogonal contrasts for within subject factors * Log base 2 spacing Clip (2,4,16) and Region(2,8,32) */ ArrayList<Factor> factorList = new ArrayList<Factor>(); factorList.add(factorA); factorList.add(factorB); OrthogonalPolynomialContrastCollection collection = OrthogonalPolynomials.withinSubjectContrast(factorList); params.setWithinSubjectContrast(collection.getInteractionContrast(factorList).getContrastMatrix()); // theta critical matrix used to back-tranform beta from U // THETA = {.25}#{.5 1 -1 .5}; * =Theta(cr) from 1st sentence *after* // equation 7, Coffey and Muller (2003); double[][] thetaData = { { 0.5, 1, -1, 0.5 } }; RealMatrix thetaCr = (new Array2DRowRealMatrix(thetaData)).scalarMultiply(0.25); // loop over the various sigma matrices //Test[] testList = Test.values(); Test[] testList = { Test.UNIREP, Test.UNIREP_BOX, Test.UNIREP_GEISSER_GREENHOUSE, Test.UNIREP_HUYNH_FELDT }; for (Test test : testList) { params.clearTestList(); params.addTest(test); for (RealMatrix sigStar : sigmaStars) { RealMatrix U = params.getWithinSubjectContrast(); // 1st paragraph in section 2.4, Coffey and Muller 2003 *; RealMatrix sigmaTemp = U.multiply(sigStar).multiply(U.transpose()); int dimension = sigmaTemp.getRowDimension(); RealMatrix Uother = MatrixUtils.getRealMatrixWithFilledValue(dimension, 1, 1 / Math.sqrt(U.getColumnDimension())); Uother = MatrixUtils.getHorizontalAppend(Uother, collection.getMainEffectContrast(factorA).getContrastMatrix()); Uother = MatrixUtils.getHorizontalAppend(Uother, collection.getMainEffectContrast(factorB).getContrastMatrix()); double varianceMean = (double) sigStar.getTrace() / (double) sigStar.getColumnDimension(); RealMatrix sigmaError = sigmaTemp .add(Uother.multiply(Uother.transpose()).scalarMultiply(varianceMean)); if (verbose) printMatrix("Sigma Error", sigmaError); // 1st paragraph in section 2.4, Coffey and Muller 2003 *; RealMatrix beta = thetaCr.multiply(U.transpose()); params.setSigmaError(sigmaError); params.setBeta(new FixedRandomMatrix(beta.getData(), null, false)); checker.checkPower(params); } } // output the results try { ValidationReportBuilder reportBuilder = new ValidationReportBuilder(); reportBuilder.createValidationReportAsStdout(checker, title, false); reportBuilder.createValidationReportAsLaTex(outputFilename, title, AUTHOR, description, params, checker); } catch (Exception e) { System.err.println(e.getMessage()); } assertTrue(checker.isSASDeviationBelowTolerance()); checker.reset(); }
From source file:com.joptimizer.functions.SOCPLogarithmicBarrier.java
public double[][] hessian(double[] X) { RealVector x = new ArrayRealVector(X); RealMatrix ret = new Array2DRowRealMatrix(dim, dim); for (int i = 0; i < socpConstraintParametersList.size(); i++) { SOCPConstraintParameters param = socpConstraintParametersList.get(i); double t = this.buildT(param, x); RealVector u = this.buildU(param, x); double t2uu = t * t - u.dotProduct(u); RealVector t2u = u.mapMultiply(-2 * t); RealMatrix Jacob = this.buildJ(param, x); int k = u.getDimension(); RealMatrix H = new Array2DRowRealMatrix(k + 1, k + 1); RealMatrix ID = MatrixUtils.createRealIdentityMatrix(k); H.setSubMatrix(ID.scalarMultiply(t2uu).add(u.outerProduct(u).scalarMultiply(2)).getData(), 0, 0); H.setSubMatrix(new double[][] { t2u.toArray() }, k, 0); for (int j = 0; j < k; j++) { H.setEntry(j, k, t2u.getEntry(j)); }// www. ja va2 s.co m H.setEntry(k, k, t * t + u.dotProduct(u)); RealMatrix ret_i = Jacob.multiply(H).multiply(Jacob.transpose()).scalarMultiply(2. / Math.pow(t2uu, 2)); ret = ret.add(ret_i); } return ret.getData(); }