【发布时间】:2016-10-31 21:38:07
【问题描述】:
我尝试为一些样本数据使用梯度下降制作线性回归程序。我得到的 theta 值并没有给出最适合数据的值。我已经对数据进行了标准化。
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);
}
}
【问题讨论】:
-
我没有测试你的代码,但我的理解是梯度下降不能保证总是找到绝对最小值/最大值(而是找到一个本地的)。所以这可能是您使用的方法的限制,而不是 Java 代码中的怪癖。
-
欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。具体来说,包括你得到的输出和预期的输出,以及你相信你会找到全局最佳匹配的理由;你确定解空间是正确凸的吗?
-
@TimBiegeleisen 总的来说你是对的,唯一的问题是:从代码中的导数我们知道它是 平方误差函数,它是凸的(因此它在线性回归)
标签: java machine-learning statistics artificial-intelligence gradient-descent