【发布时间】:2020-11-28 08:24:32
【问题描述】:
我需要编写一个函数来获得数据集的曲线拟合。下面的代码是我所拥有的。它尝试使用梯度下降来找到最适合数据的多项式系数。
//solves for y using the form y = a + bx + cx^2 ...
double calc_polynomial(int degree, double x, double* coeffs) {
double y = 0;
for (int i = 0; i <= degree; i++)
y += coeffs[i] * pow(x, i);
return y;
}
//find polynomial fit
//returns an array of coefficients degree + 1 long
double* poly_fit(double* x, double* y, int count, int degree, double learningRate, int iterations) {
double* coeffs = malloc(sizeof(double) * (degree + 1));
double* sums = malloc(sizeof(double) * (degree + 1));
for (int i = 0; i <= degree; i++)
coeffs[i] = 0;
for (int i = 0; i < iterations; i++) {
//reset sums each iteration
for (int j = 0; j <= degree; j++)
sums[j] = 0;
//update weights
for (int j = 0; j < count; j++) {
double error = calc_polynomial(degree, x[j], coeffs) - y[j];
//update sums
for (int k = 0; k <= degree; k++)
sums[k] += error * pow(x[j], k);
}
//subtract sums
for (int j = 0; j <= degree; j++)
coeffs[j] -= sums[j] * learningRate;
}
free(sums);
return coeffs;
}
还有我的测试代码:
double x[] = { 0, 1, 2, 3, 4 };
double y[] = { 5, 3, 2, 3, 5 };
int size = sizeof(x) / sizeof(*x);
int degree = 1;
double* coeffs = poly_fit(x, y, size, degree, 0.01, 1000);
for (int i = 0; i <= degree; i++)
printf("%lf\n", coeffs[i]);
上面的代码在 degree = 1 时有效,但任何更高的值都会导致系数返回为 nan。
我也试过替换
coeffs[j] -= sums[j] * learningRate;
与
coeffs[j] -= (1/count) * sums[j] * learningRate;
但后来我返回 0 而不是 nan。
有人知道我做错了什么吗?
【问题讨论】:
-
1/count是整数除法,其结果被截断。 -
啊,这就是问题所在……我现在感觉很笨
-
我尝试了
degree = 2, iteration = 10并得到了除nan以外的结果(值约为几千)在iteration上加一似乎使结果的幅度在此之后增大了大约3 倍。跨度> -
考虑避免重复调用
pow实现 Horner's method 来评估多项式和类似的错误总和。 -
注意:使用
printf("%le\n", coeffs[i]);比printf("%lf\n", coeffs[i]);提供更多信息
标签: c machine-learning gradient-descent