|
-
December 3rd, 2011, 01:09 PM
#1
Feed data from CSV to variables as pair of numbers
Hello all,
I have a project fro school i need to some help with. I am calculating regression on a set of numbers from a CSV file. The CSV file has a pair for number where each line represent a pair of X and Y:
22.33,22.42
11.23,24.23
...
I need to write a code that ask the user to upload their CSV file from the file system and parse the variables into to arrays reading doubles.
I have the code for the regression side i just don't know how to upload the file and parse to my need.
Code:
public class LinearRegression {
public static void main(String[] args) {
int MAXN = 1000;
int n = 0;
double[] x = new double[MAXN];
double[] y = new double[MAXN];
// first pass: read in data, compute xbar and ybar reading from conosle
double sumx = 0.0, sumy = 0.0, sumx2 = 0.0;
while(!StdIn.isEmpty()) {
x[n] = StdIn.readDouble();
y[n] = StdIn.readDouble();
sumx += x[n];
sumx2 += x[n] * x[n];
sumy += y[n];
n++;
}
double xbar = sumx / n;
double ybar = sumy / n;
// second pass: compute summary statistics
double xxbar = 0.0, yybar = 0.0, xybar = 0.0;
for (int i = 0; i < n; i++) {
xxbar += (x[i] - xbar) * (x[i] - xbar);
yybar += (y[i] - ybar) * (y[i] - ybar);
xybar += (x[i] - xbar) * (y[i] - ybar);
}
double beta1 = xybar / xxbar;
double beta0 = ybar - beta1 * xbar;
// print results
System.out.println("y = " + beta1 + " * x + " + beta0);
// analyze results
int df = n - 2;
double rss = 0.0; // residual sum of squares
double ssr = 0.0; // regression sum of squares
for (int i = 0; i < n; i++) {
double fit = beta1*x[i] + beta0;
rss += (fit - y[i]) * (fit - y[i]);
ssr += (fit - ybar) * (fit - ybar);
}
double R2 = ssr / yybar;
double svar = rss / df;
double svar1 = svar / xxbar;
double svar0 = svar/n + xbar*xbar*svar1;
System.out.println("R^2 = " + R2);
System.out.println("std error of beta_1 = " + Math.sqrt(svar1));
System.out.println("std error of beta_0 = " + Math.sqrt(svar0));
svar0 = svar * sumx2 / (n * xxbar);
System.out.println("std error of beta_0 = " + Math.sqrt(svar0));
System.out.println("SSTO = " + yybar);
System.out.println("SSE = " + rss);
System.out.println("SSR = " + ssr);
}
}
The code above does what i need but it uses the console to feed in numbers. i want to be able to upload a file and do the same operation on the file.
Thank you for helping!
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|