List of usage examples for org.apache.commons.math3.linear RealVector getDimension
public abstract int getDimension();
From source file:bigdataproject.PCA.java
public double[][] reduceDimensions() { BlockRealMatrix matrix = new BlockRealMatrix(dataSet); Covariance cov = new Covariance(matrix, false); RealMatrix covarianceMatrix = cov.getCovarianceMatrix(); EigenDecomposition dec = new EigenDecomposition(covarianceMatrix); RealVector principalEigenVector = dec.getEigenvector(0); RealVector secondEigenVector = dec.getEigenvector(1); BlockRealMatrix pca = new BlockRealMatrix(principalEigenVector.getDimension(), 2); pca.setColumnVector(0, principalEigenVector); pca.setColumnVector(1, secondEigenVector); BlockRealMatrix pcaTranspose = pca.transpose(); BlockRealMatrix columnVectorMatrix = matrix.transpose(); BlockRealMatrix matrix2D = pcaTranspose.multiply(columnVectorMatrix); return matrix2D.getData(); }
From source file:com.github.thorbenlindhauer.cluster.ep.TruncatedGaussianPotentialResolverTest.java
@Test public void testTwoSidedTruncatedGaussianApproximation() { ContinuousVariable variable = new ContinuousVariable("A"); Scope scope = new Scope(Collections.singleton(variable)); GaussianFactor factor = StandaloneGaussiaFactorBuilder.withVariables(variable).scope("A").momentForm() .parameters(new ArrayRealVector(new double[] { 2.0d }), new Array2DRowRealMatrix(new double[] { 4.0d })); TruncatedGaussianPotentialResolver resolver = new TruncatedGaussianPotentialResolver(variable, 0.5d, 6.0d); FactorSet<GaussianFactor> factorSet = new FactorSet<GaussianFactor>(Collections.singleton(factor)); FactorSet<GaussianFactor> approximation = resolver.project(factorSet, scope); assertThat(approximation.getFactors()).hasSize(1); GaussianFactor approximationFactor = approximation.getFactors().iterator().next(); RealVector meanVector = approximationFactor.getMeanVector(); RealMatrix covarianceMatrix = approximationFactor.getCovarianceMatrix(); assertThat(meanVector.getDimension()).isEqualTo(1); assertThat(meanVector.getEntry(0)).isEqualTo(2.658510664d, TestConstants.DOUBLE_VALUE_TOLERANCE); assertThat(covarianceMatrix.isSquare()); assertThat(covarianceMatrix.getColumnDimension()).isEqualTo(1); assertThat(covarianceMatrix.getEntry(0, 0)).isEqualTo(1.787386921d, TestConstants.DOUBLE_VALUE_TOLERANCE); }
From source file:fi.smaa.jsmaa.model.MultivariateGaussianCriterionMeasurement.java
private RealVector setMeanVectorInternal(RealVector newValue) { if (newValue.getDimension() != alternatives.size()) { throw new IllegalArgumentException( "Incorrect vector size " + newValue.getDimension() + ", expected " + alternatives.size()); }//from ww w.ja va 2 s.c om RealVector oldValue = meanVector; meanVector = newValue; return oldValue; }
From source file:edu.oregonstate.eecs.mcplan.abstraction.EvaluateSimilarityFunction.java
public static Instances transformInstances(final Instances src, final CoordinateTransform transform) { final ArrayList<Attribute> out_attributes = new ArrayList<Attribute>(); for (int i = 0; i < transform.outDimension(); ++i) { out_attributes.add(new Attribute("x" + i)); }//from w ww .j a v a 2s.com out_attributes.add((Attribute) src.classAttribute().copy()); final Instances out = new Instances(src.relationName() + "_" + transform.name(), out_attributes, 0); for (int i = 0; i < src.size(); ++i) { final Instance inst = src.get(i); final RealVector flat = new ArrayRealVector(WekaUtil.unlabeledFeatures(inst)); final RealVector transformed_vector = transform.encode(flat).x; final double[] transformed = new double[transformed_vector.getDimension() + 1]; for (int j = 0; j < transformed_vector.getDimension(); ++j) { transformed[j] = transformed_vector.getEntry(j); } transformed[transformed.length - 1] = inst.classValue(); final Instance transformed_instance = new DenseInstance(inst.weight(), transformed); out.add(transformed_instance); transformed_instance.setDataset(out); } out.setClassIndex(out.numAttributes() - 1); return out; }
From source file:com.datumbox.framework.core.common.dataobjects.MapRealVector.java
/** {@inheritDoc} */ @Override//from w w w .ja v a 2 s . c om public RealMatrix outerProduct(RealVector v) { final int m = this.getDimension(); final int n = v.getDimension(); final RealMatrix product; if (m > 1000000) { //use only in big values product = new MapRealMatrix(m, n); } else { product = new OpenMapRealMatrix(m, n); } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { product.setEntry(i, j, this.getEntry(i) * v.getEntry(j)); } } return product; }
From source file:game.plugins.metrics.StandardClassificationMetrics.java
private double evaluateWeightedAverage(RealVector row) { double ret = 0; double sum = 0; for (int i = 0; i < row.getDimension() - 1; i++) { double w = truePositives.get(i) + falseNegatives.get(i); ret += row.getEntry(i) * w;/*from www . j a v a 2s .c o m*/ sum += w; } ret = sum == 0 ? 0 : ret / sum; return ret; }
From source file:edu.utexas.cs.tactex.EnergyPredictionManagerService.java
@Override public ArrayRealVector getPredictionForAbout7Days(CustomerInfo customerInfo, boolean customerPerspective, int currentTimeslot, boolean fixed) { // portfolioManager returns predictions from the broker's // perspective (producer has kwh > 0, consumer has kwh < 0) // so to view it from customer perspective we multiply by -1 int sign = customerPerspective ? -1 : 1; // TODO this is a temporary place holder - idealy this class // won't need the portfolioManager to get its prediction RealVector energy = portfolioManager.getGeneralRawUsageForCustomer(customerInfo, fixed).mapMultiply(sign); // sanity check if (energy.getDimension() != 7 * 24) { log.error("Expecting energy dimension to be 7 * 24 - unexpected behavior might happen"); }/*from ww w .java2 s . com*/ // rotate to start from current time return BrokerUtils.rotateWeeklyRecordAndAppendTillEndOfDay(energy, currentTimeslot); }
From source file:com.joptimizer.functions.SOCPLogarithmicBarrier.java
public double[] gradient(double[] X) { RealVector x = new ArrayRealVector(X); RealVector ret = new ArrayRealVector(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); RealMatrix Jacob = this.buildJ(param, x); int k = u.getDimension(); RealVector G = new ArrayRealVector(k + 1); G.setSubVector(0, u);/*from w w w . j av a 2 s. com*/ G.setEntry(k, -t); RealVector ret_i = Jacob.operate(G).mapMultiply((2. / t2uu)); ret = ret.add(ret_i); } return ret.toArray(); }
From source file:edu.stanford.cfuller.imageanalysistools.fitting.NelderMeadMinimizer.java
/** * Constructs the initial simplex that is the starting point of the optimization given an initial guess at the minimum and a size scale for each parameter. * @param initialPoint The initial guess at the minimum, one component per parameter. * @param componentScales A size scale for each parameter that is used to set how large the initial simplex is. * @return A matrix containing p + 1 rows, each of which is one set of p parameters, which specify the simplex. *///from w w w .j a v a 2 s. c o m public RealMatrix generateInitialSimplex(RealVector initialPoint, RealVector componentScales) { RealMatrix initialSimplex = new Array2DRowRealMatrix(initialPoint.getDimension() + 1, initialPoint.getDimension()); initialSimplex.setRowVector(0, initialPoint); for (int i = 1; i < initialSimplex.getRowDimension(); i++) { RealVector newVector = initialPoint.copy(); newVector.setEntry(i - 1, newVector.getEntry(i - 1) + componentScales.getEntry(i - 1)); initialSimplex.setRowVector(i, newVector); } return initialSimplex; }
From source file:edu.stanford.cfuller.imageanalysistools.clustering.GaussianLikelihoodObjectiveFunction.java
/** * Evaluates the function with the specified parameters. * * The parameters describe a set of gaussian generators (which are the Clusters). * * @param parameters A RealVector containing the values of all the parameters of each Gaussian, ordered so that all the parameters of a single gaussian are together, then the next gaussian, etc. * @return The negative log likelihood of having observed the ClusterObjects at their locations, given the parameters describing the Gaussian clusters. *///from w w w.j a va 2s. c om public double evaluate(RealVector parameters) { int nClusters = parameters.getDimension() / nParametersEach; //java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("nClusters: " + nClusters + " abdMatrices_size: " + abdMatrices.size() + " det_dim: " + det.getDimension()); if (det.getDimension() != nClusters) { clusterProbs = new Array2DRowRealMatrix(this.objects.size(), nClusters); det = new ArrayRealVector(nClusters); pk = new ArrayRealVector(nClusters); if (abdMatrices.size() < nClusters) { int originalSize = abdMatrices.size(); for (int i = 0; i < nClusters - originalSize; i++) { abdMatrices.add(new Array2DRowRealMatrix(numDim, numDim)); } } else { abdMatrices.setSize(nClusters); } } pk.mapMultiplyToSelf(0.0); //java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("nClusters: " + nClusters + " abdMatrices_size: " + abdMatrices.size() + " det_dim: " + det.getDimension()); for (int i = 0; i < nClusters; i++) { /* double ct = Math.cos(parameters.getEntry(nParametersEach*i+3)); double st = Math.sin(parameters.getEntry(nParametersEach*i+3)); double sin2t = Math.sin(2*parameters.getEntry(nParametersEach*i+3)); double a = (ct*ct/(2*parameters.getEntry(nParametersEach*i+2)) + st*st/(2*parameters.getEntry(nParametersEach*i+4))); double b = (sin2t/(4*parameters.getEntry(nParametersEach*i+4)) - sin2t/(4*parameters.getEntry(nParametersEach*i+2))); double d = (st*st/(2*parameters.getEntry(nParametersEach*i+2)) + ct*ct/(2*parameters.getEntry(nParametersEach*i+4))); */ double a = parameters.getEntry(nParametersEach * i + 2); double d = parameters.getEntry(nParametersEach * i + 4); double b = Math.sqrt(a * d) * parameters.getEntry(nParametersEach * i + 3); abdMatrices.get(i).setEntry(0, 0, a); abdMatrices.get(i).setEntry(1, 0, b); abdMatrices.get(i).setEntry(0, 1, b); abdMatrices.get(i).setEntry(1, 1, d); LUDecomposition abdLU = (new LUDecomposition(abdMatrices.get(i))); det.setEntry(i, (abdLU).getDeterminant()); //det.setEntry(i, a*d-b*b); try { abdMatrices.set(i, abdLU.getSolver().getInverse()); } catch (org.apache.commons.math3.linear.SingularMatrixException e) { return Double.MAX_VALUE; } } for (int n = 0; n < this.objects.size(); n++) { ClusterObject c = this.objects.get(n); double max = -1.0 * Double.MAX_VALUE; int maxIndex = 0; for (int k = 0; k < nClusters; k++) { mean.setEntry(0, c.getCentroid().getX() - parameters.getEntry(nParametersEach * k)); mean.setEntry(1, c.getCentroid().getY() - parameters.getEntry(nParametersEach * k + 1)); x = abdMatrices.get(k).operate(mean); double dot = x.dotProduct(mean); // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("k, n: " + k + ", " + this.objects.size()); // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("parameters: " + parameters.toString()); // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("abd matrix: " + abdMatrices.get(k).toString()); // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("det: " + det.getEntry(k)); // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("mean: " + mean.toString()); // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("dot: " + dot); double logN = negLog2PI - 0.5 * Math.log(det.getEntry(k)) - 0.5 * dot; // java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("logN: " + logN); clusterProbs.setEntry(n, k, logN); if (logN > max) { max = logN; maxIndex = k; } if (Double.isInfinite(logN) || Double.isNaN(logN)) { return Double.MAX_VALUE; } } c.setMostProbableCluster(maxIndex); } for (int k = 0; k < nClusters; k++) { double tempMax = -1.0 * Double.MAX_VALUE; for (int n = 0; n < this.objects.size(); n++) { if (clusterProbs.getEntry(n, k) > tempMax) tempMax = clusterProbs.getEntry(n, k); } pk.setEntry(k, tempMax + Math.log( clusterProbs.getColumnVector(k).mapSubtract(tempMax).mapToSelf(new Exp()).getL1Norm()) - Math.log(this.objects.size())); } double pkMax = -1.0 * Double.MAX_VALUE; for (int k = 0; k < nClusters; k++) { if (pk.getEntry(k) > pkMax) pkMax = pk.getEntry(k); } double logSumPk = pkMax + Math.log(pk.mapSubtract(pkMax).mapToSelf(new Exp()).getL1Norm()); pk.mapSubtractToSelf(logSumPk); //java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("pk: " + pk.toString()); double L = 0; for (int n = 0; n < this.objects.size(); n++) { RealVector toSum = clusterProbs.getRowVector(n).add(pk); double tempMax = -1.0 * Double.MAX_VALUE; for (int k = 0; k < nClusters; k++) { if (toSum.getEntry(k) > tempMax) tempMax = toSum.getEntry(k); } double pn = tempMax + Math.log(toSum.mapSubtract(tempMax).mapToSelf(new Exp()).getL1Norm()); //java.util.logging.Logger.getLogger("edu.stanford.cfuller.imageanalysistools").info("pn: " + pn); L += pn; } return -1.0 * L; }