【发布时间】:2013-05-29 06:41:40
【问题描述】:
我正在尝试实现一个非常简单的一维梯度下降算法。我的代码根本不起作用。基本上取决于我的 alpha 值,最终参数要么非常大(如 ~70 位),要么基本上为零(~ 0.000)。我觉得梯度下降在 alpha 中不应该如此敏感(我在 [0.0,1.0] 中生成小数据,但我认为梯度本身应该考虑数据的规模,不是吗?)。
代码如下:
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <vector>
using namespace std;
double a, b;
double theta0 = 0.0, theta1 = 0.0;
double myrand() {
return double(rand()) / RAND_MAX;
}
double f(double x) {
double y = a * x + b;
y *= 0.1 * (myrand() - 0.5); // +/- 5% noise
return y;
}
double h(double x) {
return theta1 * x + theta0;
}
int main() {
srand(time(NULL));
a = myrand();
b = myrand();
printf("set parameters: a = %lf, b = %lf\n", a, b);
int N = 100;
vector<double> xs(N);
vector<double> ys(N);
for (int i = 0; i < N; ++i) {
xs[i] = myrand();
ys[i] = f(xs[i]);
}
double sensitivity = 0.008;
double d0, d1;
for (int n = 0; n < 100; ++n) {
d0 = d1 = 0.0;
for (int i = 0; i < N; ++i) {
d0 += h(xs[i]) - ys[i];
d1 += (h(xs[i]) - ys[i]) * xs[i];
}
theta0 -= sensitivity * d0;
theta1 -= sensitivity * d1;
printf("theta0: %lf, theta1: %lf\n", theta0, theta1);
}
return 0;
}
【问题讨论】:
-
据我所见,您的函数“f”是一个随机函数,但您的渐变不一定对应于该函数。如果梯度没有很好地定义,则不能保证下降转换。我错过了什么吗?
-
没关系...刚刚意识到这是随机噪音
-
是的,
f只是用于生成训练数据。h是我正在为其执行下降的函数。 -
可以参考这里的开源实现:cimne.com/purple/default.asp
标签: c++ machine-learning artificial-intelligence