matlab - 如何在 MATLAB 代码中与 GD 收敛?显然在矩阵维度上显示错误
问题描述
我的梯度下降代码中存在尺寸错误。代码应该随着 Y_prediction 迭代次数的增加而收敛。Theta_0 和 Theta_1 应该迭代,但它显示 Y_prediction 的尺寸错误。
Theta_0 = 0
Theta_1 = 0
learning_rate = 0.001
X = [2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013] % Year
Y = [2.00 2.500 2.900 3.147 4.515 4.903 5.365 5.704 6.853 7.971 8.561 10.00 11.280 12.900] % Price
n = length(X)
for i = 1:100
Y_prediction = Theta_1.*X + Theta_0 ! Y = mx + c
Derivative_Theta_0 = (1/n)*sum(Y_prediction - Y)
Derivative_Theta_1 = (1/n)*sum(X.*(Y_prediction - Y))
Theta_0(i+1) = Theta_0(i) - learning_rate*Derivative_Theta_0
Theta_1(i+1) = Theta_1(i) - learning_rate*Derivative_Theta_1
end
解决方案
Theta_0 = 0
Theta_1 = 0
learning_rate = 0.001
X = [2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013] % Year
Y = [2.00 2.500 2.900 3.147 4.515 4.903 5.365 5.704 6.853 7.971 8.561 10.00 11.280
12.900] % Price
X = X - 2000
n = length(X)
for i = 1:100000
Y_prediction = Theta_1*X + Theta_0;
Derivative_Theta_0 = (1/n)*sum(Y_prediction - Y);
Derivative_Theta_1 = (1/n)*sum(X.*(Y_prediction - Y));
Theta_0 = Theta_0 - learning_rate*Derivative_Theta_0;
Theta_1 = Theta_1 - learning_rate*Derivative_Theta_1;
end
% Linear Regression
Y_prediction = Theta_1*X + Theta_0;
推荐阅读
- c++ - 返回时复制操作是在 lock_guard 析构函数之前还是之后执行的?
- sql - 从 BigQuery 导出自定义维度
- sql - 在 Amazon Redshift 中使用 max() 或 min() 条件查询优化选择
- c# - Selenium xpath 断言
- javascript - 为什么我在 ES6 中的 Javascript 导入不起作用?意外的标记 *
- java - 在 Spring Boot 中上传时读取 CSV 文件
- command-line-interface - Julia `--project` 命令行选项中的`@.` 是什么?
- python - Python - 如何解决 Web 服务器连接限制
- angular - 我可以将对象及其方法存储在@ngrx 中吗
- jwplayer - 如何阻止JW播放器控制栏在播放过程中淡出?(JW 8)