Java:时间序列普通最小二乘法

时间:2015-02-12 14:32:36

标签: java time-series regression mathematical-optimization least-squares

我使用The Apache Commons数学库与OLS有一些问题。我有一个时间序列y,我想在前26个观测中拟合最小二乘趋势线。这是我的代码:

List<Double> y = new ArrayList<>(Arrays.asList(206.0, 245.0,
                185.0, 169.0, 162.0, 177.0, 207.0, 216.0, 193.0, 230.0, 212.0,
                192.0, 162.0, 189.0, 244.0, 209.0, 207.0, 211.0, 210.0, 173.0,
                194.0, 234.0, 156.0, 206.0, 188.0, 162.0, 172.0, 210.0, 205.0,
                244.0, 218.0, 182.0, 206.0, 211.0, 273.0, 248.0, 262.0, 258.0,
                233.0, 255.0, 303.0, 282.0, 291.0, 280.0, 255.0, 312.0, 296.0,
                307.0, 281.0, 308.0, 280.0, 345.0));

OLSMultipleLinearRegression ols = new OLSMultipleLinearRegression();
        int obs = y.size()/2;

int vars = 1;

        double data[] = new Utils().toArray(y);

        try {
            ols.newSampleData(data, obs, vars); // 3
        }
        catch(IllegalArgumentException e) {
            System.out.print("Can't sample data: ");
            e.printStackTrace();
        }

        double[] coe = null;
        try {
            coe = ols.estimateRegressionParameters(); // 4
        } catch(Exception e) { // 5
            System.out.print("Can't estimate parameters: ");
            e.printStackTrace();
        }

我得到的结果是:

coe[0] = 58.3379729430363 
coe[1] = 0.7075495794353521

然而,结果应该是(参见截图):

coe[0] = 202.6246154
coe[1] = -0.368205128

http://i.imgur.com/KqlR4i4.png

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

请仔细阅读文档。您调用的方法是将数据数组的偶数索引处的值解释为观察值,将奇数索引处的值解释为预测变量值。

http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math4/stat/regression/OLSMultipleLinearRegression.html#newSampleData-double:A-int-int-

我同意这非常不直观,我个人会避免使用这种令人困惑的方法。

看起来你想要做的是将x [0:25]拟合到一个时间变量,时间从1开始。为此,我将创建一个大小为26的数组,从i =开始创建一个for循环0,并为i th 索引赋值(i + 1.0)。从那里你可以使用SimpleRegression类。 http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math4/stat/regression/SimpleRegression.html