Example usage for org.apache.mahout.math Vector minus

List of usage examples for org.apache.mahout.math Vector minus

Introduction

In this page you can find the example usage for org.apache.mahout.math Vector minus.

Prototype

Vector minus(Vector x);

Source Link

Document

Return a new vector containing the element by element difference of the recipient and the argument

Usage

From source file:DisplayClustering.java

License:Apache License

/**
 * Identical to plotRectangle(), but with the option of setting the color of
 * the rectangle's stroke./*  w  ww  . j  ava2s . co  m*/
 *
 * NOTE: This should probably be refactored with plotRectangle() since most of
 * the code here is direct copy/paste from that method.
 *
 * @param g2
 *          A Graphics2D context.
 * @param v
 *          A vector for the rectangle's center.
 * @param dv
 *          A vector for the rectangle's dimensions.
 * @param color
 *          The color of the rectangle's stroke.
 */
protected static void plotClusteredRectangle(Graphics2D g2, Vector v, Vector dv, Color color) {
    double[] flip = { 1, -1 };
    Vector v2 = v.times(new DenseVector(flip));
    v2 = v2.minus(dv.divide(2));
    int h = SIZE / 2;
    double x = v2.get(0) + h;
    double y = v2.get(1) + h;

    g2.setStroke(new BasicStroke(1));
    g2.setColor(color);
    g2.draw(new Rectangle2D.Double(x * DS, y * DS, dv.get(0) * DS, dv.get(1) * DS));
}

From source file:DisplayClustering.java

License:Apache License

/**
 * Draw a rectangle on the graphics context
 *
 * @param g2/*from  w  ww .jav a  2s . c o  m*/
 *          a Graphics2D context
 * @param v
 *          a Vector of rectangle center
 * @param dv
 *          a Vector of rectangle dimensions
 */
protected static void plotRectangle(Graphics2D g2, Vector v, Vector dv) {
    double[] flip = { 1, -1 };
    Vector v2 = v.times(new DenseVector(flip));
    v2 = v2.minus(dv.divide(2));
    int h = SIZE / 2;
    double x = v2.get(0) + h;
    double y = v2.get(1) + h;
    g2.draw(new Rectangle2D.Double(x * DS, y * DS, dv.get(0) * DS, dv.get(1) * DS));
}

From source file:DisplayClustering.java

License:Apache License

/**
 * Draw an ellipse on the graphics context
 *
 * @param g2//ww w.  j  a  v a 2  s  .  com
 *          a Graphics2D context
 * @param v
 *          a Vector of ellipse center
 * @param dv
 *          a Vector of ellipse dimensions
 */
protected static void plotEllipse(Graphics2D g2, Vector v, Vector dv) {
    double[] flip = { 1, -1 };
    Vector v2 = v.times(new DenseVector(flip));
    v2 = v2.minus(dv.divide(2));
    int h = SIZE / 2;
    double x = v2.get(0) + h;
    double y = v2.get(1) + h;
    g2.draw(new Ellipse2D.Double(x * DS, y * DS, dv.get(0) * DS, dv.get(1) * DS));
}

From source file:ca.uwaterloo.cpami.mahout.matrix.utils.GramSchmidt.java

License:Apache License

public static void orthonormalizeColumns(Matrix mx) {

    //int n = mx.numCols();
    int n = mx.numRows();

    for (int c = 0; c < n; c++) {
        System.out.println("col: " + c);
        Vector col = mx.viewRow(c);
        for (int c1 = 0; c1 < c; c1++) {
            Vector viewC1 = mx.viewRow(c1);
            col.assign(col.minus(viewC1.times(viewC1.dot(col))));

        }/*from   w  w  w .  ja  va  2s.  c o  m*/
        final double norm2 = col.norm(2);
        if (norm2 == 0) {
            System.out.println("zero");
        }
        col.assign(new DoubleFunction() {
            @Override
            public double apply(double x) {
                return x / norm2;
            }
        });
    }
}

From source file:com.cloudera.science.ml.parallel.covariance.MahalanobisDistance.java

License:Open Source License

public double distance(Vector v) {
    Vector d = v.minus(m);
    return d.dot(ci.times(d));
}

From source file:com.mapr.stats.GammaNormalDistributionTest.java

License:Apache License

@Test
public void testEstimation() {
    final Random gen = new Random(1);
    GammaNormalDistribution gnd = new GammaNormalDistribution(0, 1, 1, gen);

    for (int i = 0; i < 10000; i++) {
        gnd.add(gen.nextGaussian() * 2 + 1);
    }//w w w .j a v  a 2s. c  o m

    assertEquals(1.0, gnd.nextMean(), 0.05);
    assertEquals(2.0, gnd.nextSD(), 0.1);

    double[] x = new double[10000];
    double[] y = new double[10000];
    double[] z = new double[10000];
    AbstractContinousDistribution dist = gnd.posteriorDistribution();
    for (int i = 0; i < 10000; i++) {
        x[i] = gnd.nextDouble();
        y[i] = dist.nextDouble();
        z[i] = gen.nextGaussian() * 2 + 1;
    }

    Arrays.sort(x);
    Arrays.sort(y);
    Arrays.sort(z);

    final Vector xv = new DenseVector(x).viewPart(1000, 8000);
    final Vector yv = new DenseVector(y).viewPart(1000, 8000);
    final Vector zv = new DenseVector(z).viewPart(1000, 8000);
    final double diffX = xv.minus(zv).assign(Functions.ABS).maxValue();
    final double diffY = yv.minus(zv).assign(Functions.ABS).maxValue();
    assertEquals(0, diffX, 0.13);
    assertEquals(0, diffY, 0.13);
}

From source file:edu.snu.dolphin.bsp.examples.ml.algorithms.clustering.em.EMMainCmpTask.java

License:Apache License

@Override
public void run(final int iteration) {
    clusterToStats = new HashMap<>();
    final int numClusters = clusterSummaries.size();

    // Compute the partial statistics of each cluster
    for (final Vector vector : points) {
        final int dimension = vector.size();
        Matrix outProd = null;//from   www .j a v a2 s.  c o m

        if (isCovarianceDiagonal) {
            outProd = new SparseMatrix(dimension, dimension);
            for (int j = 0; j < dimension; j++) {
                outProd.set(j, j, vector.get(j) * vector.get(j));
            }
        } else {
            outProd = vector.cross(vector);
        }

        double denominator = 0;
        final double[] numerators = new double[numClusters];
        for (int i = 0; i < numClusters; i++) {
            final ClusterSummary clusterSummary = clusterSummaries.get(i);
            final Vector centroid = clusterSummary.getCentroid();
            final Matrix covariance = clusterSummary.getCovariance();
            final Double prior = clusterSummary.getPrior();

            final Vector differ = vector.minus(centroid);
            numerators[i] = prior / Math.sqrt(covariance.determinant())
                    * Math.exp(differ.dot(inverse(covariance).times(differ)) / (-2));
            denominator += numerators[i];
        }

        for (int i = 0; i < numClusters; i++) {
            final double posterior = denominator == 0 ? 1.0 / numerators.length : numerators[i] / denominator;
            if (!clusterToStats.containsKey(i)) {
                clusterToStats.put(i,
                        new ClusterStats(times(outProd, posterior), vector.times(posterior), posterior, false));
            } else {
                clusterToStats.get(i).add(
                        new ClusterStats(times(outProd, posterior), vector.times(posterior), posterior, false));
            }
        }
    }
}

From source file:edu.utsa.sifter.som.SelfOrganizingMap.java

License:Apache License

int maxTermDifference(final int tID, final int uID) {
    final Vector t = getCell(tID);
    final Vector u = getCell(uID);
    final Vector diff = t.minus(u);
    final double maxValue = diff.maxValue();
    final double minValue = diff.minValue();

    if (minValue < 0 && Math.abs(minValue) > maxValue) { // even if maxValue is negative, this will hold
        return -diff.minValueIndex();
    } else {//  w ww .  ja  v a 2s . c o  m
        return diff.maxValueIndex();
    }
}

From source file:org.trustedanalytics.atk.giraph.algorithms.cgd.ConjugateGradientDescentComputation.java

License:Apache License

/**
 * Compute beta according to Hestenes-Stiefel formula
 *
 * @param gradient of type Vector//  w w w .  j a va2s.  com
 * @param conjugate of type Vector
 * @param gradientNext of type Vector
 * @return beta of type double
 */
private double computeBeta(Vector gradient, Vector conjugate, Vector gradientNext) {
    double beta = 0d;
    if (conjugate.norm(1d) == 0d) {
        return beta;
    }
    Vector deltaVector = gradientNext.minus(gradient);
    beta = -gradientNext.dot(deltaVector) / conjugate.dot(deltaVector);
    return beta;
}

From source file:org.trustedanalytics.atk.giraph.algorithms.lbp.LoopyBeliefPropagationComputation.java

License:Apache License

@Override
public void compute(Vertex<LongWritable, VertexData4LBPWritable, DoubleWritable> vertex,
        Iterable<IdWithVectorMessage> messages) throws IOException {
    long step = getSuperstep();
    if (step == 0) {
        initializeVertex(vertex);//w  w  w .  j  av a  2 s.co m
        return;
    }

    // collect messages sent to this vertex
    HashMap<Long, Vector> map = new HashMap<Long, Vector>();
    for (IdWithVectorMessage message : messages) {
        map.put(message.getData(), message.getVector());
    }

    // update posterior according to prior and messages
    VertexData4LBPWritable vertexValue = vertex.getValue();
    VertexType vt = vertexValue.getType();
    vt = ignoreVertexType ? VertexType.TRAIN : vt;
    Vector prior = vertexValue.getPriorVector();
    double nStates = prior.size();
    if (vt != VertexType.TRAIN) {
        // assign a uniform prior for validate/test vertex
        prior = prior.clone().assign(Math.log(1.0 / nStates));
    }
    // sum of prior and messages
    Vector sumPosterior = prior;
    for (IdWithVectorMessage message : messages) {
        sumPosterior = sumPosterior.plus(message.getVector());
    }
    sumPosterior = sumPosterior.plus(-sumPosterior.maxValue());
    // update posterior if this isn't an anchor vertex
    if (prior.maxValue() < anchorThreshold) {
        // normalize posterior
        Vector posterior = sumPosterior.clone().assign(Functions.EXP);
        posterior = posterior.normalize(1d);
        Vector oldPosterior = vertexValue.getPosteriorVector();
        double delta = posterior.minus(oldPosterior).norm(1d);
        // aggregate deltas
        switch (vt) {
        case TRAIN:
            aggregate(SUM_TRAIN_DELTA, new DoubleWritable(delta));
            break;
        case VALIDATE:
            aggregate(SUM_VALIDATE_DELTA, new DoubleWritable(delta));
            break;
        case TEST:
            aggregate(SUM_TEST_DELTA, new DoubleWritable(delta));
            break;
        default:
            throw new IllegalArgumentException("Unknown vertex type: " + vt.toString());
        }
        // update posterior
        vertexValue.setPosteriorVector(posterior);
    }

    if (step < maxSupersteps) {
        // if it's not a training vertex, don't send out messages
        if (vt != VertexType.TRAIN) {
            return;
        }
        IdWithVectorMessage newMessage = new IdWithVectorMessage();
        newMessage.setData(vertex.getId().get());
        // update belief
        Vector belief = prior.clone();
        for (Edge<LongWritable, DoubleWritable> edge : vertex.getEdges()) {
            double weight = edge.getValue().get();
            long id = edge.getTargetVertexId().get();
            Vector tempVector = sumPosterior;
            if (map.containsKey(id)) {
                tempVector = sumPosterior.minus(map.get(id));
            }
            for (int i = 0; i < nStates; i++) {
                double sum = 0d;
                for (int j = 0; j < nStates; j++) {
                    double msg = Math.exp(
                            tempVector.getQuick(j) + edgePotential(Math.abs(i - j) / (nStates - 1), weight));
                    if (maxProduct) {
                        sum = sum > msg ? sum : msg;
                    } else {
                        sum += msg;
                    }
                }
                belief.setQuick(i, sum > 0d ? Math.log(sum) : Double.MIN_VALUE);
            }
            belief = belief.plus(-belief.maxValue());
            newMessage.setVector(belief);
            sendMessage(edge.getTargetVertexId(), newMessage);
        }
    } else {
        // convert prior back to regular scale before output
        prior = vertexValue.getPriorVector();
        prior = prior.assign(Functions.EXP);
        vertexValue.setPriorVector(prior);
        vertex.voteToHalt();
    }
}