Java Code Examples for org.apache.commons.math3.linear.RealVector#getEntry()

The following examples show how to use org.apache.commons.math3.linear.RealVector#getEntry() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AlphaSkewRelatednessFunction.java    From Indra with MIT License 6 votes vote down vote up
@Override
public double sim(RealVector r1, RealVector r2, boolean sparse) {
    if (r1.getDimension() != r2.getDimension()) {
        return 0;
    }

    double alpha = 0.99;
    double divergence = 0.0;

    for (int i = 0; i < r1.getDimension(); ++i) {
        if (r1.getEntry(i) > 0.0 && r2.getEntry(i) > 0.0) {
            divergence += r1.getEntry(i) * Math.log(r1.getEntry(i) / ((1 - alpha) * r1.getEntry(i) + alpha * r2.getEntry(i)));
        }
    }

    double result = (1 - (divergence / Math.sqrt(2 * Math.log(2))));
    return Math.abs(result);
}
 
Example 2
Source File: Jaccard2RelatednessFunction.java    From Indra with MIT License 6 votes vote down vote up
@Override
public double sim(RealVector r1, RealVector r2, boolean sparse) {
    if (r1.getDimension() != r2.getDimension()) {
        return 0;
    }

    double min = 0.0;
    double max = 0.0;

    for (int i = 0; i <r1.getDimension(); ++i) {
        if (r1.getEntry(i) > r2.getEntry(i)) {
            min +=r2.getEntry(i);
            max += r1.getEntry(i);
        } else {
            min += r1.getEntry(i);
            max += r2.getEntry(i);
        }
    }

    if (max == 0) {
        return 0;
    }

    return Math.abs(min / max);
}
 
Example 3
Source File: XDataFrameLeastSquares.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
/**
 * Calculates the standard errors of the regression parameters.
 * @param betaVar   the variance of the beta parameters
 * @throws DataFrameException   if this operation fails
 */
private void computeParameterStdErrors(RealVector betaVar) {
    try {
        final int offset = hasIntercept() ? 1 : 0;
        if (hasIntercept()) {
            final double interceptVariance = betaVar.getEntry(0);
            final double interceptStdError = Math.sqrt(interceptVariance);
            this.intercept.data().setDouble(0, Field.STD_ERROR, interceptStdError);
        }
        for (int i = 0; i < regressors.size(); i++) {
            final double betaVar_i = betaVar.getEntry(i + offset);
            final double betaStdError = Math.sqrt(betaVar_i);
            this.betas.data().setDouble(i, Field.STD_ERROR, betaStdError);
        }
    } catch (Exception ex) {
        throw new DataFrameException("Failed to calculate regression coefficient standard errors", ex);
    }
}
 
Example 4
Source File: MinCovDet.java    From macrobase with Apache License 2.0 6 votes vote down vote up
public static Double getMahalanobis(RealVector mean,
                                    RealMatrix inverseCov,
                                    RealVector vec) {
    final int dim = mean.getDimension();
    double[] vecMinusMean = new double[dim];

    for (int d = 0; d < dim; ++d) {
        vecMinusMean[d] = vec.getEntry(d) - mean.getEntry(d);
    }

    double diagSum = 0, nonDiagSum = 0;

    for (int d1 = 0; d1 < dim; ++d1) {
        for (int d2 = d1; d2 < dim; ++d2) {
            double v = vecMinusMean[d1] * vecMinusMean[d2] * inverseCov.getEntry(d1, d2);
            if (d1 == d2) {
                diagSum += v;
            } else {
                nonDiagSum += v;
            }
        }
    }

    return Math.sqrt(diagSum + 2 * nonDiagSum);
}
 
Example 5
Source File: GMMTrainerTest.java    From pyramid with Apache License 2.0 6 votes vote down vote up
private static void plot(RealVector vector, int height, int width, String imageFile) throws Exception{

        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//        Graphics2D g2d = image.createGraphics();
//        g2d.setBackground(Color.WHITE);
//
//
//        g2d.fillRect ( 0, 0, image.getWidth(), image.getHeight() );
//        g2d.dispose();
        for (int i=0;i<width;i++){
            for (int j=0;j<height;j++){
                int v = (int)(vector.getEntry(i*width+j));
                int rgb = 65536 * v + 256 * v + v;
                image.setRGB(j,i,rgb);
//                image.setRGB(j,i,(int)(vector.get(i*width+j)/255*16777215));
            }
        }


        new File(imageFile).getParentFile().mkdirs();
        ImageIO.write(image,"png",new File(imageFile));
    }
 
Example 6
Source File: MovingAverage.java    From macrobase with Apache License 2.0 6 votes vote down vote up
@Override
public double scoreWindow() {
    if (windowSum == null) {
        return 0;
    }
    RealVector latest = getLatestDatum().metrics();
    RealVector average = windowSum.mapDivide(weightTotal);
    double percentDiff = 0;
    for (int i = 0; i < average.getDimension(); i++) {
        if (average.getEntry(i) == 0 || timeColumn == i) {
            // What should we do here?
            continue;
        }
        percentDiff += Math.abs((latest.getEntry(i) - average.getEntry(i))
                / average.getEntry(i));
    }

    return percentDiff;
}
 
Example 7
Source File: CommonsMathSolver.java    From myrrix-recommender with Apache License 2.0 5 votes vote down vote up
@Override
public double[] solveFToD(float[] b) {
  ArrayRealVector bVec = new ArrayRealVector(b.length);
  for (int i = 0; i < b.length; i++) {
    bVec.setEntry(i, b[i]);
  }
  RealVector vec = solver.solve(bVec);
  double[] result = new double[b.length];
  for (int i = 0; i < result.length; i++) {
    result[i] = vec.getEntry(i);
  }
  return result;
}
 
Example 8
Source File: CommonsMathSolver.java    From myrrix-recommender with Apache License 2.0 5 votes vote down vote up
@Override
public float[] solveDToF(double[] b) {
  RealVector vec = solver.solve(new ArrayRealVector(b, false));
  float[] result = new float[b.length];
  for (int i = 0; i < result.length; i++) {
    result[i] = (float) vec.getEntry(i);
  }
  return result;
}
 
Example 9
Source File: KDTree.java    From macrobase with Apache License 2.0 5 votes vote down vote up
public boolean isInsideBoundaries(Datum queryDatum) {
    RealVector vector = queryDatum.metrics();
    for (int i=0; i<k; i++) {
        if (vector.getEntry(i) < this.boundaries[i][0] || vector.getEntry(i) > this.boundaries[i][1]) {
            return false;
        }
    }
    return true;
}
 
Example 10
Source File: KDTree.java    From macrobase with Apache License 2.0 5 votes vote down vote up
/**
 * Estimates bounds on the distance to a region
 * @param queryDatum target point
 * @return array with min, max distances squared
 */
public double[] estimateL2DistanceSquared(Datum queryDatum) {
    RealVector vector = queryDatum.metrics();
    double[] estimates = new double[2];
    for (int i=0; i<k; i++) {
        double deltaLo = vector.getEntry(i) - this.boundaries[i][0];
        double deltaHi = this.boundaries[i][1] - vector.getEntry(i);
        double sqDeltaLo = deltaLo * deltaLo;
        double sqDeltaHi = deltaHi * deltaHi;

        // point is outside
        if (deltaLo < 0 || deltaHi < 0) {
            // Add the bigger distance to the longer estimate;
            if (sqDeltaHi < sqDeltaLo) {
                estimates[0] += sqDeltaHi;
                estimates[1] += sqDeltaLo;
            } else {
                estimates[0] += sqDeltaLo;
                estimates[1] += sqDeltaHi;
            }
        } else {
            // Point is inside so only add to max distance.
            // The point is inside the tree boundaries.
            estimates[1] += Math.max(sqDeltaHi, sqDeltaLo);
        }
    }
    return estimates;
}
 
Example 11
Source File: Solver.java    From oryx with Apache License 2.0 5 votes vote down vote up
public float[] solveFToF(float[] b) {
  RealVector bVec = new ArrayRealVector(b.length);
  for (int i = 0; i < b.length; i++) {
    bVec.setEntry(i, b[i]);
  }
  RealVector resultVec = solver.solve(bVec);
  float[] result = new float[resultVec.getDimension()];
  for (int i = 0; i < result.length; i++) {
    result[i] = (float) resultVec.getEntry(i);
  }
  return result;
}
 
Example 12
Source File: RegressionTree.java    From samantha with MIT License 5 votes vote down vote up
private int predictLeaf(LearningInstance instance) {
    int predNode = -1;
    if (variableSpace.getVectorVarSizeByName(treeName) > 0) {
        StandardLearningInstance ins = (StandardLearningInstance) instance;
        int node = 0;
        do {
            predNode = node;
            RealVector nodeVec = variableSpace.getVectorVarByNameIndex(treeName, node);
            int splitIdx = (int)nodeVec.getEntry(0);
            if (splitIdx == -1) {
                return predNode;
            }
            double splitVal = nodeVec.getEntry(1);
            double feaVal = 0.0;
            if (ins.getFeatures().containsKey(splitIdx)) {
                feaVal = ins.getFeatures().get(splitIdx);
            }
            if (feaVal <= splitVal) {
                node = (int)nodeVec.getEntry(2);
            } else {
                node = (int)nodeVec.getEntry(3);
            }
            if (node == -1) {
                return predNode;
            }
        } while (node != -1);
    }
    return predNode;
}
 
Example 13
Source File: RegressionTree.java    From samantha with MIT License 5 votes vote down vote up
public double[] predict(LearningInstance instance) {
    double[] preds = new double[1];
    if (variableSpace.getVectorVarSizeByName(treeName) > 0) {
        StandardLearningInstance ins = (StandardLearningInstance) instance;
        int node = 0;
        do {
            RealVector nodeVec = variableSpace.getVectorVarByNameIndex(treeName, node);
            int splitIdx = (int)nodeVec.getEntry(0);
            if (splitIdx == -1) {
                preds[0] = nodeVec.getEntry(4);
                return preds;
            }
            double splitVal = nodeVec.getEntry(1);
            double feaVal = 0.0;
            if (ins.getFeatures().containsKey(splitIdx)) {
                feaVal = ins.getFeatures().get(splitIdx);
            }
            if (feaVal <= splitVal) {
                node = (int)nodeVec.getEntry(2);
            } else {
                node = (int)nodeVec.getEntry(3);
            }
            if (node == -1) {
                preds[0] = nodeVec.getEntry(4);
                return preds;
            }
        } while (node != -1);
    }
    preds[0] = 0.0;
    return preds;
}
 
Example 14
Source File: EpanchnikovMulticativeKernel.java    From macrobase with Apache License 2.0 5 votes vote down vote up
@Override
public double density(RealVector u) {
    double rtn = 1.0;
    final int d = u.getDimension();
    for (int i = 0; i < d; i++) {
        double i2 = u.getEntry(i) * u.getEntry(i);
        if (i2 > 1) {
            return 0;
        }
        rtn *= 1 - i2;
    }
    return Math.pow(0.75, d) * rtn;
}
 
Example 15
Source File: SimpleAverageUserState.java    From samantha with MIT License 5 votes vote down vote up
private void setState(ObjectNode state, RealVector value) {
    double cnt = value.getEntry(0);
    state.put(modelName + "-state-cnt", cnt);
    for (int i=0; i< actionAttrs.size(); i++) {
        if (!state.has("state-" + actionAttrs.get(i))) {
            if (cnt != 0.0) {
                state.put("state-" + actionAttrs.get(i), value.getEntry(i + 1) / cnt);
            } else {
                state.put("state-" + actionAttrs.get(i), 0.0);
            }
        }
    }
}
 
Example 16
Source File: MatrixUtils.java    From incubator-hivemall with Apache License 2.0 5 votes vote down vote up
@Nonnull
static RealVector unitL2norm(@Nonnull final RealVector x) {
    double x0 = x.getEntry(0);
    double sign = MathUtils.sign(x0);
    x.setEntry(0, x0 + sign * x.getNorm());
    return x.unitVector();
}
 
Example 17
Source File: KDTree.java    From macrobase with Apache License 2.0 5 votes vote down vote up
/**
 * Estimates min and max difference absolute vectors from point to region
 * @param queryDatum target point
 * @return minVec, maxVec
 */
// TODO: Make this method faster.
public RealVector[] getMinMaxDistanceVectors(Datum queryDatum) {
    double[] minDifferences = new double[k];
    double[] maxDifferences = new double[k];

    RealVector metrics = queryDatum.metrics();
    for (int i=0; i<k; i++) {
        double deltaLo = metrics.getEntry(i) - this.boundaries[i][0];
        double deltaHi = this.boundaries[i][1] - metrics.getEntry(i);
        // point is outside
        double minD = Math.abs(deltaLo);
        double maxD = Math.abs(deltaHi);
        if (minD < maxD) {
            minDifferences[i] = minD;
            maxDifferences[i] = maxD;
        } else {
            minDifferences[i] = maxD;
            maxDifferences[i] = minD;
        }

        if (deltaLo > 0 && deltaHi > 0) {
            // Point is inside so only add to max distance.
            minDifferences[i] = 0;
        }
    }

    RealVector[] rtn = new RealVector[2];
    rtn[0] = new ArrayRealVector(minDifferences);
    rtn[1] = new ArrayRealVector(maxDifferences);
    return rtn;
}
 
Example 18
Source File: JensenShannonRelatednessFunction.java    From Indra with MIT License 5 votes vote down vote up
@Override
public double sim(RealVector r1, RealVector r2, boolean sparse) {
    if (r1.getDimension() != r2.getDimension()) {
        return 0;
    }

    double divergence = 0.0;
    double avr = 0.0;

    for (int i = 0; i < r1.getDimension(); ++i) {
        avr = (r1.getEntry(i) + r2.getEntry(i)) / 2;

        if (r1.getEntry(i) > 0.0 && avr > 0.0) {
            divergence += r1.getEntry(i) * Math.log(r1.getEntry(i) / avr);
        }
    }
    for (int i = 0; i < r2.getDimension(); ++i) {
        avr = (r1.getEntry(i) + r2.getEntry(i)) / 2;

        if (r2.getEntry(i) > 0.0 && avr > 0.0) {
            divergence += r1.getEntry(i) * Math.log(r2.getEntry(i) / avr);
        }
    }

    double result = 1 - (divergence / (2 * Math.sqrt(2 * Math.log(2))));
    return Math.abs(result);
}
 
Example 19
Source File: SumPaths.java    From pacaya with Apache License 2.0 4 votes vote down vote up
/**
 * Computes the approximate sum of paths through the graph where the weight
 * of each path is the product of edge weights along the path;
 * 
 * If consumer c is not null, it will be given the intermediate estimates as
 * they are available
 */
public static double approxSumPaths(WeightedIntDiGraph g, RealVector startWeights, RealVector endWeights,
        Iterator<DiEdge> seq, DoubleConsumer c) {
    // we keep track of the total weight of discovered paths ending along
    // each edge and the total weight
    // of all paths ending at each node (including the empty path); on each
    // time step, we
    // at each step, we pick an edge (s, t), update the sum at s, and extend
    // each of those (including
    // the empty path starting there) with the edge (s, t)

    DefaultDict<DiEdge, Double> prefixWeightsEndingAt = new DefaultDict<DiEdge, Double>(Void -> 0.0);

    // we'll maintain node sums and overall sum with subtraction rather than
    // re-adding (it's an approximation anyway!)
    RealVector currentSums = startWeights.copy();
    double currentTotal = currentSums.dotProduct(endWeights);
    if (c != null) {
        c.accept(currentTotal);
    }
    for (DiEdge e : ScheduleUtils.iterable(seq)) {
        int s = e.get1();
        int t = e.get2();
        // compute the new sums
        double oldTargetSum = currentSums.getEntry(t);
        double oldEdgeSum = prefixWeightsEndingAt.get(e);
        // new edge sum is the source sum times the edge weight
        double newEdgeSum = currentSums.getEntry(s) * g.getWeight(e);
        // new target sum is the old target sum plus the difference between
        // the new and old edge sums
        double newTargetSum = oldTargetSum + (newEdgeSum - oldEdgeSum);
        // the new total is the old total plus the difference in new and
        // target
        double newTotal = currentTotal + (newTargetSum - oldTargetSum) * endWeights.getEntry(t);
        // store the new sums
        prefixWeightsEndingAt.put(e, newEdgeSum);
        currentSums.setEntry(t, newTargetSum);
        currentTotal = newTotal;
        // and report the new total to the consumer
        if (c != null) {
            c.accept(currentTotal);
        }
    }
    return currentTotal;
}
 
Example 20
Source File: KalmanScalarFilter.java    From macrobase with Apache License 2.0 4 votes vote down vote up
public double step(double observation, int time) {
    RealVector v = super.step(toVector(observation), time);
    return v.getEntry(0);
}