List of usage examples for org.apache.commons.math3.linear RealVector mapDivide
public RealVector mapDivide(double d)
From source file:com.cloudera.oryx.kmeans.common.LloydsUpdateStrategy.java
/** * Compute the {@code Vector} that is the centroid of the given weighted points. * /*from w w w . j a va 2 s .co m*/ * @param points The weighted points * @return The centroid of the weighted points */ public static <W extends Weighted<RealVector>> RealVector centroid(Iterable<W> points) { RealVector center = null; double sz = 0.0; for (W v : points) { RealVector weighted = v.thing().mapMultiply(v.weight()); if (center == null) { center = weighted; } else { center = center.add(weighted); } sz += v.weight(); } return center.mapDivide(sz); }
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 ww . j a va2s . com*/ * @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:net.sf.dsp4j.octave_3_2_4.m.polynomial.Roots.java
public static Complex[] roots(RealVector v) { if (v.isInfinite() || v.isNaN()) { throw new RuntimeException("roots: inputs must not contain Inf or NaN"); }//from ww w. jav a 2 s .co m int n = v.getDimension(); // ## If v = [ 0 ... 0 v(k+1) ... v(k+l) 0 ... 0 ], we can remove the // ## leading k zeros and n - k - l roots of the polynomial are zero. int[] f = new int[v.getDimension()]; if (v.getDimension() > 0) { int fI = 0; double max = v.getMaxValue(); double min = FastMath.abs(v.getMinValue()); if (min > max) { max = min; } RealVector v1 = v.mapDivide(max); f = OctaveBuildIn.find(v1); } Complex[] r = new Complex[0]; if (f.length > 0 && n > 1) { v = v.getSubVector(f[0], f[f.length - 1] - f[0] + 1); if (v.getDimension() > 1) { double[] ones = new double[v.getDimension() - 2]; Arrays.fill(ones, 1); RealMatrix A = OctaveBuildIn.diag(ones, -1); for (int i = 0; i < A.getRowDimension(); i++) { A.setEntry(i, 0, -v.getEntry(i + 1) / v.getEntry(0)); } try { r = Eig.eig(A); } catch (Exception e) { throw new RuntimeException(e); } if (f[f.length - 1] < n) { int diffLength = n - 1 - f[f.length - 1]; if (diffLength > 0) { int rl = r.length; r = Arrays.copyOf(r, r.length + diffLength); Arrays.fill(r, rl, r.length, Complex.ZERO); } } } else { r = new Complex[n - f[f.length - 1]]; Arrays.fill(r, Complex.ZERO); } } else { r = new Complex[0]; } return r; }
From source file:edu.cuhk.hccl.cmd.CosineDocumentSimilarity.java
private RealVector toRealVector(Map<String, Integer> map) { RealVector vector = new ArrayRealVector(terms.size()); int i = 0;// w w w.j a v a2s .c o m for (String term : terms) { int value = map.containsKey(term) ? map.get(term) : 0; vector.setEntry(i++, value); } return (RealVector) vector.mapDivide(vector.getL1Norm()); }
From source file:lucene.CosineDocumentSimilarity.java
RealVector toRealVector(Map<String, Integer> map) { RealVector vector = new ArrayRealVector(terms.size()); int i = 0;/*from ww w . ja v a 2 s . c o m*/ for (String term : terms) { int value = map.containsKey(term) ? map.get(term) : 0; vector.setEntry(i++, value); } return (RealVector) vector.mapDivide(vector.getL1Norm()); }
From source file:edu.utexas.cs.tactex.servercustomers.factoredcustomer.DefaultFactoredCustomer.java
/** * use my predictions to override the originator's profile *///w w w .java 2 s. c o m @Override public void updateEnergyRecord(CapacityBundle bundle, RealVector populationEstimatedEnergy, int currentTimeslot) { List<CapacityOriginator> capacityOriginators = bundle.getCapacityOriginators(); int numOriginators = capacityOriginators.size(); // divide estimated energy by number of originators RealVector originatorEnergy = populationEstimatedEnergy.mapDivide(numOriginators); for (CapacityOriginator originator : capacityOriginators) { originator.convertEnergyProfileFromBrokerToServer(originatorEnergy, currentTimeslot); } }
From source file:edu.stanford.cfuller.imageanalysistools.fitting.BisquareLinearFit.java
/** * Calculates the standardized adjusted residuals (according to the same definition used by MATLAB) of the data points for fitting. * * @param indVarValues The values of the independent variable used for the fitting. * @param depVarValues The values of the dependent variable used for the fitting. * @param leverages the leverages of the independent variables, as compted by {@link #calculateLeverages(RealVector)} * @param fitParams the results of a (possibly weighted) least squares fit to the data, containing one or two components: a slope and an optional y-intercept. * @return a RealVector containing an adjusted residual value for each data point */// w w w . ja v a2 s . c om protected RealVector calculateStandardizedAdjustedResiduals(RealVector indVarValues, RealVector depVarValues, RealVector leverages, RealVector fitParams) { RealVector predictedValues = indVarValues.mapMultiply(fitParams.getEntry(0)); RealVector denom = leverages.mapMultiply(-1.0).mapAddToSelf(1 + this.CLOSE_TO_ZERO) .mapToSelf(new org.apache.commons.math3.analysis.function.Sqrt()); if (!this.noIntercept) { predictedValues = predictedValues.mapAdd(fitParams.getEntry(1)); } double stddev = 0; double mean = 0; for (int i = 0; i < depVarValues.getDimension(); i++) { mean += depVarValues.getEntry(i); } mean /= depVarValues.getDimension(); stddev = depVarValues.mapSubtract(mean).getNorm() * (depVarValues.getDimension() * 1.0 / (depVarValues.getDimension() - 1)); RealVector residuals = depVarValues.subtract(predictedValues).ebeDivide(denom); RealVector absDev = residuals.map(new org.apache.commons.math3.analysis.function.Abs()); int smallerDim = 2; if (this.noIntercept) { smallerDim = 1; } double[] resArray = residuals.map(new org.apache.commons.math3.analysis.function.Abs()).toArray(); java.util.Arrays.sort(resArray); RealVector partialRes = new ArrayRealVector(absDev.getDimension() - smallerDim + 1, 0.0); for (int i = smallerDim - 1; i < resArray.length; i++) { partialRes.setEntry(i - smallerDim + 1, resArray[i]); } double resMAD = 0; if (partialRes.getDimension() % 2 == 0) { resMAD = LocalBackgroundEstimationFilter.quickFindKth(partialRes.getDimension() / 2, partialRes) + LocalBackgroundEstimationFilter.quickFindKth(partialRes.getDimension() / 2 - 1, partialRes); resMAD /= 2.0; } else { resMAD = LocalBackgroundEstimationFilter.quickFindKth((partialRes.getDimension() - 1) / 2, partialRes); } resMAD /= 0.6745; if (resMAD < stddev * CLOSE_TO_ZERO) { resMAD = stddev * CLOSE_TO_ZERO; } return residuals.mapDivide(DEFAULT_TUNING_CONST * resMAD); }
From source file:org.apache.predictionio.examples.java.recommendations.tutorial4.FeatureBasedAlgorithm.java
public FeatureBasedModel train(PreparedData data) { Map<Integer, RealVector> userFeatures = new HashMap<Integer, RealVector>(); Map<Integer, Integer> userActions = new HashMap<Integer, Integer>(); for (Integer uid : data.userInfo.keySet()) { userFeatures.put(uid, new ArrayRealVector(data.featureCount)); userActions.put(uid, 0);// w ww .j a va 2s . c o m } for (TrainingData.Rating rating : data.ratings) { final int uid = rating.uid; final int iid = rating.iid; final double rate = rating.rating; // Skip features outside the range. if (!(params.min <= rate && rate <= params.max)) continue; final double actualRate = (rate - params.drift) * params.scale; final RealVector userFeature = userFeatures.get(uid); final RealVector itemFeature = data.itemFeatures.get(iid); userFeature.combineToSelf(1, actualRate, itemFeature); userActions.put(uid, userActions.get(uid) + 1); } // Normalize userFeatures by l-inf-norm for (Integer uid : userFeatures.keySet()) { final RealVector feature = userFeatures.get(uid); feature.mapDivideToSelf(feature.getLInfNorm()); } // Normalize itemFeatures by weight Map<Integer, RealVector> itemFeatures = new HashMap<Integer, RealVector>(); for (Integer iid : data.itemFeatures.keySet()) { final RealVector feature = data.itemFeatures.get(iid); final RealVector normalizedFeature = feature.mapDivide(feature.getL1Norm()); itemFeatures.put(iid, normalizedFeature); } return new FeatureBasedModel(userFeatures, userActions, itemFeatures); }
From source file:org.rhwlab.BHCnotused.GaussianGIWPrior.java
@Override public RealVector getMean() { RealVector ret = new ArrayRealVector(m.getDimension()); int n = 0;//from w w w .j a va 2s . c om for (LabeledFieldVector v : data) { int label = v.getLabel(); RealVector[] vs = source.getClusterVectors(label); for (int i = 0; i < vs.length; ++i) { ret = ret.add(vs[i]); ++n; } ret = ret.mapDivide(n); } return ret; }
From source file:org.rhwlab.variationalbayesian.GaussianMixture.java
public void Mstep() { alphaBetaNu();// ww w .j av a 2s. c o m // compute the means of the components for (int k = 0; k < K; ++k) { if (inModel[k]) { RealVector v1 = xBar[k].mapMultiply(N[k]); RealVector v2 = mu0.mapMultiply(beta0); RealVector v3 = v2.add(v1); m[k] = v3.mapDivide(beta[k]); } } // compute the precision matrices for (int k = 0; k < K; ++k) { if (inModel[k]) { RealVector del = xBar[k].subtract(mu0); RealMatrix del2 = del.outerProduct(del); double f = beta0 * N[k] / (beta0 + N[k]); RealMatrix mat = del2.scalarMultiply(f); RealMatrix NS = S[k].scalarMultiply(N[k]); Winverse[k] = W0inverse.add(NS).add(mat); LUDecomposition cd = new LUDecomposition(Winverse[k]); W[k] = cd.getSolver().getInverse(); detWinv[k] = cd.getDeterminant(); detW[k] = 1.0 / cd.getDeterminant(); } } lambdaTilde(); }