首页 > 解决方案 > 如何在 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 

标签: matlab

解决方案


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;

推荐阅读