-
Notifications
You must be signed in to change notification settings - Fork 0
/
Regression.pde
54 lines (44 loc) · 1.42 KB
/
Regression.pde
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Regression {
float y_intercept, slope;
float lambda = 1;
public Regression() {
y_intercept = 0;
slope = 1;
}
public float penalty() {
return lambda * (slope * slope);
}
public float LeastSquareError() {
float error = 0;
float residual = 0;
// y is the actual value
// ModelFunction is my prediciton of y
for (int i = 0; i < data.size(); i++) {
residual = data.get(i).y - (ModelFunction(data.get(i).x, slope, y_intercept));
error += residual * residual;
}
return error;
}
public void LeastSquareRegression() {
float sumXY = 0, sumX = 0, sumY = 0, sumXSquare = 0;
float N = data.size();
for (int i = 0; i < data.size(); i++) {
sumXY += data.get(i).x * data.get(i).y;
sumX += data.get(i).x;
sumY += data.get(i).y;
sumXSquare += pow(data.get(i).x, 2);
}
slope = (N * sumXY - sumX * sumY) / (N * sumXSquare - pow(sumX, 2));
y_intercept = (sumY - slope * sumX) / N;
}
// Returns y at
public float ModelFunction(float x, float slope, float intercept) {
return intercept + slope * x;
}
public void DrawLine() {
stroke(0);
fill(0);
line(0, y_intercept, width, ModelFunction((float)height, slope, y_intercept));
text("y_intercept: " + (height - y_intercept) + "\nslope: " + abs(slope) + "\nLeastSquareError: " + LeastSquareError(), 2, textAscent());
}
}