Reputation: 331
I have some problems with the OLS using the The Apache Commons Mathematics Library. I have got a time series y and I would like to fit a least squares trend line to the first 26 observations. This is my code for that:
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();
}
The result what I get is:
coe[0] = 58.3379729430363
coe[1] = 0.7075495794353521
However, the result should be (cf. screenshot as well):
coe[0] = 202.6246154
coe[1] = -0.368205128
Can anyone help me with this isse?
Upvotes: 3
Views: 638
Reputation: 49
Read the documentation a bit more carefully. The method you called is interpreting the values at the even indices of your data array as the observations and the values at the odd indices as the predictor variable values.
I agree that this is extremely non-intuitive and I personally would avoid using methods that are this confusing.
It looks like what you would like to do is fit x[0:25] to a time variable, with time starting at 1. For that I would create an array with size 26, create a for loop starting at i = 0, and assign the ith index the value (i + 1.0). From there you can use the SimpleRegression class. http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math4/stat/regression/SimpleRegression.html
Upvotes: 1