c - 线性回归收敛但结果不好
问题描述
重要提示:我是 ML 的初学者,我想自己实现我正在学习的算法,而不使用 ML 库。
我有一个数据集,其中包含公里数(x)的价格(y),我想找到描述数据的函数。您可以在此处找到数据集和整个代码:https ://wetransfer.com/downloads/034d9918f6d29268f06be45d76e156f420190330174420/6af73b
我正在使用一种经典的梯度下降算法:我的代码可以很好地解决一些单一的线性回归问题,但不是我感兴趣的问题。
/* Classic gradient descent algorithm */
ft_sum(double *x, double *y, long double theta0, long double theta1, int epoch, int truth)
{
long double result = 0.00;
long double tmp;
int i;
i = 0;
while (epoch--)
{
/* Derivative part of the gradient descent */
tmp = ((x[i] * theta1 + theta0)) - (y[i]);
if (truth == 1)
tmp = tmp * (x[i]);
result += tmp;
i++;
}
return (result);
}
/* Linear regression */
void single_linear_regression(double *x, double *y, double epoch, char *argv)
{
long double theta0 = 0; /* bias */
long double theta1 = 0; /* weight */
long double error = 100; /* Cost of the function */
long double tmp1;
long double tmp2;
double alpha = 0.0000000001; /* with higher learning rate it does not converge */
int i = 0;
while (!(error > -0.4 && error < 0.4)) // it doesn't go below 0.4
{
tmp1 = theta0 - ((alpha * (1.00 / epoch) *
(error = ft_sum(x, y, theta0, theta1, epoch - 1, 0))));
tmp2 = theta1 - ((alpha * (1.00 / epoch) *
(error = ft_sum(x, y, theta0, theta1, epoch - 1, 1))));
theta0 = tmp1;
theta1 = tmp2;
printf("error := %Lf\n", error);
}
printf("error := %Lf | theta0 == %Lf | theta1 == %Lf\n", error, theta0, theta1);
}
最后,我有:
错误:= 0.240723 | θ0 == 0.000004 | theta1 == 0.044168
(f(x) = 0.044x + 0.000004) 当实际函数为:-0.02x + 8500...
我已经尝试过规范化数据[0-1],改变权重和偏差的起始值,我真的坚持这一点。
解决方案
推荐阅读
- javascript - 将远程 api json 数据显示到谷歌地图中
- vector - highchart 地图通过单击创建标记并获取经纬度坐标
- azureservicebus - 最新 SDK 即 Azure.Messaging.ServiceBus 中 Microsoft.Azure.ServiceBus 的 ITopicClient 的等价物是什么
- javascript - JavaScript Async\Await 理解
- kdb - 如何过滤 KDB 中的列表?
- python-3.x - Django cms 不更新页面类型
- java - java - 如何在java中基于多个条件(如优先查询)从列表中获取项目?
- php - PHP 动态值作为大数据中的 time() 函数速度
- selenium - 如何在命令行上为机器人框架的日志/输出/报告文件设置用户定义路径
- c# - .NETCore 3.1 覆盖 docker compose 中的自定义值