Example usage for org.apache.commons.math3.stat.regression SimpleRegression predict

List of usage examples for org.apache.commons.math3.stat.regression SimpleRegression predict

Introduction

In this page you can find the example usage for org.apache.commons.math3.stat.regression SimpleRegression predict.

Prototype

public double predict(final double x) 

Source Link

Document

Returns the "predicted" y value associated with the supplied x value, based on the data that has been added to the model when this method is activated.

Usage

From source file:joinery.impl.Display.java

private static void addTrend(final Chart chart, final Series series, final List<Object> xdata) {
    final SimpleRegression model = new SimpleRegression();
    final Iterator<? extends Number> y = series.getYData().iterator();
    for (int x = 0; y.hasNext(); x++) {
        model.addData(x, y.next().doubleValue());
    }/*from w w w .ja va 2  s .  c o m*/
    final Color mc = series.getMarkerColor();
    final Color c = new Color(mc.getRed(), mc.getGreen(), mc.getBlue(), 0x60);
    final Series trend = chart.addSeries(series.getName() + " (trend)",
            Arrays.asList(xdata.get(0), xdata.get(xdata.size() - 1)),
            Arrays.asList(model.predict(0), model.predict(xdata.size() - 1)));
    trend.setLineColor(c);
    trend.setMarker(SeriesMarker.NONE);
}

From source file:eu.verdelhan.ta4j.indicators.statistics.SimpleLinearRegressionIndicatorTest.java

@Test
public void calculateLinearRegression() {
    double[] values = new double[] { 1, 2, 1.3, 3.75, 2.25 };
    ClosePriceIndicator indicator = new ClosePriceIndicator(new MockTimeSeries(values));
    SimpleLinearRegressionIndicator reg = new SimpleLinearRegressionIndicator(indicator, 5);

    SimpleRegression origReg = buildSimpleRegression(values);
    assertDecimalEquals(reg.getValue(4), origReg.predict(4));
}

From source file:cloudnet.workloads.prediction.SimpleRegressionPredictionStrategy.java

@Override
public Long predictValue(long futureTimeStamp, long currTimeStamp, WorkloadHistory history) {
    Ensure.NotNull(history, "history");

    SimpleRegression r = new SimpleRegression();
    for (Map.Entry<Long, Long> entry : history.getWorkloadHistory().entrySet()) {
        r.addData(entry.getKey(), entry.getValue());
    }/*from  w ww .  j a  v  a 2 s  .co m*/

    double predicted = r.predict(futureTimeStamp);
    return predicted == Double.NaN || predicted < 0 ? null : (long) predicted;
}

From source file:eu.verdelhan.ta4j.indicators.statistics.SimpleLinearRegressionIndicatorTest.java

@Test
public void calculateLinearRegressionOn4Observations() {

    SimpleLinearRegressionIndicator reg = new SimpleLinearRegressionIndicator(closePrice, 4);
    assertDecimalEquals(reg.getValue(1), 20);
    assertDecimalEquals(reg.getValue(2), 30);

    SimpleRegression origReg = buildSimpleRegression(10, 20, 30, 40);
    assertDecimalEquals(reg.getValue(3), 40);
    assertDecimalEquals(reg.getValue(3), origReg.predict(3));

    origReg = buildSimpleRegression(30, 40, 30, 40);
    assertDecimalEquals(reg.getValue(5), origReg.predict(3));

    origReg = buildSimpleRegression(30, 20, 30, 50);
    assertDecimalEquals(reg.getValue(9), origReg.predict(3));
}

From source file:com.ipeirotis.gal.core.CategoryPair.java

public Double getWorkerWageRegr(double qualifiedWage, double costThreshold, Map<String, Category> priors) {

    SimpleRegression regression = new SimpleRegression();

    for (int m = 1; m <= 41; m += 4) {

        double cost = getWorkerCost(m, priors, 1000);
        if (cost == 0)
            break;
        regression.addData(Math.log(cost), m);

    }/* w w  w  .  j  a  v  a 2  s .c  o m*/

    double d = regression.predict(Math.log(costThreshold));

    return qualifiedWage / d;

}

From source file:eu.vital.orchestrator.rest.EvaluationRESTService.java

@POST
@Path("/prediction")
public Response executePredictionScenario(JsonNode input) throws Exception {
    String dmsUrl = "https://local.vital-iot.eu:8443/vital-core-dms";

    // 1. Get List of sensors from DMS observing AvailableBikes
    Client dmsClient = ClientBuilder.newClient();
    WebTarget dmsTarget = dmsClient.target(dmsUrl).path("querySensor").queryParam("encodeKeys", "false");
    ObjectNode sensorQuery = objectMapper.createObjectNode();
    sensorQuery.put("http://purl\\u002eoclc\\u002eorg/NET/ssnx/ssn#observes.@type",
            "http://vital-iot.eu/ontology/ns/Speed");
    ArrayNode sensorList = dmsTarget.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.json(sensorQuery),
            ArrayNode.class);

    // 2. Find the nearest sensor
    double minDistance = Double.MAX_VALUE;
    JsonNode nearestSensor = null;//from   ww  w  .ja  v  a2 s. co  m
    for (int i = 0; i < sensorList.size(); i++) {
        JsonNode sensor = sensorList.get(i);

        // Calculate Distance:
        double tmp = distance(input.get("lat").asDouble(), input.get("lng").asDouble(),
                sensor.get("hasLastKnownLocation").get("geo:lat").asDouble(),
                sensor.get("hasLastKnownLocation").has("geo:long")
                        ? sensor.get("hasLastKnownLocation").get("geo:long").asDouble()
                        : sensor.get("hasLastKnownLocation").get("geo:lon").asDouble());
        if (tmp < minDistance) {
            minDistance = tmp;
            nearestSensor = sensor;
        }
    }

    // 3. Get all observations of this sensor from DMS archive
    dmsTarget = dmsClient.target(dmsUrl).path("queryObservation").queryParam("encodeKeys", "false");
    ObjectNode observationQuery = objectMapper.createObjectNode();
    observationQuery.put("http://purl\\u002eoclc\\u002eorg/NET/ssnx/ssn#observedBy.@value",
            nearestSensor.get("id").asText());
    observationQuery.put("http://purl\\u002eoclc\\u002eorg/NET/ssnx/ssn#observationProperty.@type",
            "http://vital-iot.eu/ontology/ns/Speed");

    ArrayNode observationList = dmsTarget.request(MediaType.APPLICATION_JSON_TYPE)
            .post(Entity.json(observationQuery), ArrayNode.class);

    // 4. Run the prediction algorithm
    SimpleRegression regression = new SimpleRegression();
    for (int i = 0; i < observationList.size(); i++) {
        JsonNode observation = observationList.get(i);
        double value = observation.get("ssn:observationResult").get("ssn:hasValue").get("value").asDouble();
        String dateStr = observation.get("ssn:observationResultTime").get("time:inXSDDateTime").asText();
        Calendar date = javax.xml.bind.DatatypeConverter.parseDateTime(dateStr);
        regression.addData(date.getTimeInMillis(), value);
    }
    double futureMillis = javax.xml.bind.DatatypeConverter.parseDateTime(input.get("atDate").asText())
            .getTimeInMillis();
    double prediction = regression.predict(futureMillis);

    // 5. Return the result:
    ObjectNode result = objectMapper.createObjectNode();
    result.put("predictionValue", prediction);
    result.put("predictionDate", input.get("atDate").asText());

    return Response.ok(result).build();
}

From source file:com.medlog.webservice.vo.DiaryAnalysisSummaryVO.java

private void populateCorrelation() {
    SpearmansCorrelation c = new SpearmansCorrelation();

    getCorr()[IDX_MOOD] = c.correlation(getMood(), getMood());
    getCorr()[IDX_AGREEABLENESS_BIG5] = c.correlation(getMood(), getAgreeablenessBig5());
    getCorr()[IDX_MOOD] = c.correlation(getMood(), getMood());
    getCorr()[IDX_AGREEABLENESS_BIG5] = c.correlation(getMood(), getAgreeablenessBig5());
    getCorr()[IDX_ANALYTICAL] = c.correlation(getMood(), getAnalytical());
    getCorr()[IDX_ANGER] = c.correlation(getMood(), getAnger());
    getCorr()[IDX_CONFIDENT] = c.correlation(getMood(), getConfident());
    getCorr()[IDX_CONSCIENTIOUSNESS_BIG5] = c.correlation(getMood(), getConscientiousnessBig5());
    getCorr()[IDX_DISGUST] = c.correlation(getMood(), getDisgust());
    getCorr()[IDX_EMOTIONALRANGE_BIG5] = c.correlation(getMood(), getEmotionalRangeBig5());
    getCorr()[IDX_EXTRAVERSION_BIG5] = c.correlation(getMood(), getExtraversionBig5());
    getCorr()[IDX_FEAR] = c.correlation(getMood(), getFear());
    getCorr()[IDX_JOY] = c.correlation(getMood(), getJoy());
    getCorr()[IDX_OPENNESS_BIG5] = c.correlation(getMood(), getOpennessBig5());
    getCorr()[IDX_SADNESS] = c.correlation(getMood(), getSadness());
    getCorr()[IDX_TENTATIVE] = c.correlation(getMood(), getTentative());
    double corrTemp;
    for (int k = 0; k < getCorr().length; k++) {
        corrTemp = Math.pow(getCorr()[k], 2);
        if (StrUtl.matchOR(k, IDX_ANGER, IDX_DISGUST, IDX_FEAR, IDX_SADNESS)) {
            corrTemp = .99 - corrTemp;// w w w . j a v  a  2s .c o m
        }
        getrSquared()[k] = corrTemp;
    }
    double q3 = org.apache.commons.math3.stat.StatUtils.percentile(getrSquared(), .75);

    double q1 = org.apache.commons.math3.stat.StatUtils.percentile(getrSquared(), .25);
    double var = StatUtils.variance(getrSquared());
    System.out.println("q1" + q1);
    System.out.println("q3" + q3);
    System.out.println("var" + var);
    double max = StatUtils.max(getrSquared());

    double min = StatUtils.max(getrSquared());

    setSum(StatUtils.sum(getrSquared()) - 1.0);
    System.out.println("sum" + getSum());
    for (int j = 1; j < 14; j++) {
        getCorrRanked()[j] = getrSquared()[j] / getSum();
    }
    System.out.println("pmf sum" + StatUtils.sum(getCorrRanked()));
    double[] cRCopy = ArrayUtils.clone(getCorrRanked());
    Arrays.sort(cRCopy);
    ArrayUtils.reverse(cRCopy);
    setToneList(new ArrayList<ToneKeyValuePair>());
    for (int j = 1; j < 14; j++) {
        ArrayUtils.indexOf(cRCopy, getCorrRanked()[j]);
        //ToneKeyValuePair t = ToneKeyValuePair.builder().key(CORR_STR[j]).value(getrSquared()[j]).weightedValue(getCorrRanked()[j]).rank(ArrayUtils.indexOf(cRCopy, getCorrRanked()[j])).build();
        getToneList().add(ToneKeyValuePair.builder().key(CORR_STR[j]).value(getrSquared()[j])
                .weightedValue(getCorrRanked()[j]).rank(ArrayUtils.indexOf(cRCopy, getCorrRanked()[j]) + 1)
                .historicalRawAvg(getAverageScores()[j]).build());
        //            corrRanked[j] = rSquared[j] / sum;
    }

    double guess = 0;

    for (ToneKeyValuePair t : getToneList()) {
        guess += (t.getWeightedValue() * 10 * getValFromKeyPct(t.getKey()));//t.getWeightedValue());

        System.out.println(t.toString());
        System.out.println("com.medlog.webservice.vo.DiaryAnalysisSummaryVO.populateCorrelation() Guess with "
                + t.getRank() + "== " + guess);
    }
    SimpleRegression sg = new SimpleRegression(false);
    populateLineGuessPoints(sg);

    getGuesses()[1] = sg.predict(getToneCurrentAvgX());
    System.out
            .println("\n\n\ncom.medlog.webservice.vo.DiaryAnalysisSummaryVO.populateCorrelation() GUESS === >");

    System.out.printf("Weighted (history) Guess ------> %.3f%n", (guess));
    System.out.printf("Best fit line Guess -----------> %.3f%n", sg.predict(getToneCurrentAvgX()));
    guess /= 10;
    guess = Math.round(guess);
    System.out.printf("Weighted (history) Guess adj.-----> %.3f%n", (guess));
    System.out.println("-------------------------------------------\n");
    getGuesses()[0] = guess;
    getLineEq()[SLOPE] = sg.getSlope();
    getLineEq()[YINT] = sg.getIntercept();
    getLineEq()[R] = sg.getRSquare();
    double[] norm = StatUtils.normalize(getCorrRanked());

    if (DEBUG) {
        System.out.println("com.medlog.webservice.vo.DiaryAnalysisSummaryVO.populateCorrelation()"
                + Arrays.toString(norm));
    }
    getFiveSummary()[0] = StatUtils.min(norm);
    getFiveSummary()[1] = StatUtils.percentile(norm, 25);

    getFiveSummary()[2] = StatUtils.percentile(norm, 50);

    getFiveSummary()[3] = StatUtils.percentile(norm, 75);

    getFiveSummary()[4] = StatUtils.max(norm);

}

From source file:org.hawkular.datamining.forecast.models.DoubleExponentialSmoothing.java

@Override
protected DoubleExState initState(List<DataPoint> initData) {

    if (initData.size() < minimumInitSize()) {
        throw new IllegalArgumentException("For init are required " + minimumInitSize() + " points.");
    }//from www . j av a 2s  .  c  om

    double level;
    double slope;

    if (initData.size() == 2) {
        DataPoint[] dataPoints = initData.toArray(new DataPoint[0]);
        level = dataPoints[0].getValue();
        slope = dataPoints[1].getValue() - dataPoints[0].getValue();
    } else {
        SimpleRegression regression = new SimpleRegression();
        initData.forEach(dataPoint -> regression.addData(dataPoint.getTimestamp(), dataPoint.getValue()));
        level = regression.predict(initData.get(0).getTimestamp());
        slope = regression.getSlope();
    }

    return state = new DoubleExState(level, slope);
}

From source file:org.hawkular.datamining.forecast.models.TripleExponentialSmoothing.java

@Override
protected TripleExState initState(List<DataPoint> dataPoints) {

    if (dataPoints.size() < minimumInitSize()) {
        throw new IllegalArgumentException("At least two complete seasons are required");
    }//from   w  w w  .ja  va2 s .  c  om

    AdditiveSeasonalDecomposition decomposition = new AdditiveSeasonalDecomposition(dataPoints, periods);
    double[] periodIndices = decomposition.decompose();

    // do regression on seasonally adjusted data points
    List<DataPoint> seasonal = decomposition.seasonal();
    SimpleRegression regression = new SimpleRegression();
    for (int i = 0; i < dataPoints.size(); i++) {
        regression.addData(i, dataPoints.get(i).getValue() - seasonal.get(i).getValue());
    }
    double level = regression.predict(0);
    double slope = regression.getSlope();

    double[] switchedPeriods = rotatePeriods(periodIndices, 0);

    return state = new TripleExState(level, slope, switchedPeriods, dataPoints.get(0).getTimestamp());
}

From source file:org.zavodnikov.math.LinearRegression.java

@Test
public void test1() {
    final SimpleRegression regression = new SimpleRegression();

    final int[] observations = new int[] { 1, 1, 1, 2, 2, 5, 2, 3, 1 };
    for (int i = 0; i < observations.length; ++i) {
        regression.addData(i + 1, observations[i]);
    }// w  w  w . j a v a2s  . com

    final int predictTime = observations.length + 1;
    //final double predict = regression.getSlope() * predictTime + regression.getIntercept();
    System.out.println(regression.predict(predictTime));
    System.out.println(findValue(regression, 5));
}