I tried making a program for linear regression using gradient descent for some sample data. The theta values that I get do not give the best fit for the data. I have already normalized the data.
public class OneVariableRegression {
public static void main(String[] args) {
double x1[] = {-1.605793084, -1.436762233, -1.267731382, -1.098700531, -0.92966968, -0.760638829, -0.591607978, -0.422577127, -0.253546276, -0.084515425, 0.084515425, 0.253546276, 0.422577127, 0.591607978, 0.760638829, 0.92966968, 1.098700531, 1.267731382, 1.436762233, 1.605793084};
double y[] = {0.3, 0.2, 0.24, 0.33, 0.35, 0.28, 0.61, 0.38, 0.38, 0.42, 0.51, 0.6, 0.55, 0.56, 0.53, 0.61, 0.65, 0.68, 0.74, 0.87};
double theta0 = 0.5;
double theta1 = 0.5;
double temp0;
double temp1;
double alpha = 1.5;
double m = x1.length;
System.out.println(m);
double derivative0 = 0;
double derivative1 = 0;
do {
for (int i = 0; i < x1.length; i++) {
derivative0 = (derivative0 + (theta0 + (theta1 * x1[i]) - y[i])) * (1/m);
derivative1 = (derivative1 + (theta0 + (theta1 * x1[i]) - y[i])) * (1/m) * x1[i];
}
temp0 = theta0 - (alpha * derivative0);
temp1 = theta1 - (alpha * derivative1);
theta0 = temp0;
theta1 = temp1;
//System.out.println("Derivative0 = " + derivative0);
//System.out.println("Derivative1 = " + derivative1);
}
while (derivative0 > 0.0001 || derivative1 > 0.0001);
System.out.println();
System.out.println("theta 0 = " + theta0);
System.out.println("theta 1 = " + theta1);
}
}