首页 > 解决方案 > 我的渐变体面正在收敛,但曲线拟合不正确

问题描述

我的 Gradient Decent 代码不起作用。我不明白我在哪里做错了

close all;
clear all;
clc
xx=linspace(0,10,100);
y=xx.^3+rand(1,100)*10;
subplot(1,2,1);
plot(xx,y,'.');
hold on
x0=ones(1,100);
x1=xx;
x1=x1;
x2=xx.^2;
x2=x2;
x3=xx.^3;
x3=x3;
X = [(x0);
    (x1);
    (x2);
    (x3);
    ];
X=X';
y=y';
alpha=.00001;
m=100;
n=4;
iteration=30000;
J=zeros(iteration,1);
theta=zeros(n,1);
for itr=1:iteration
    temp=zeros(n,1);
    for i=1:n
        temp(i)=sum((X*theta-y).*X(:,i))*alpha*1/m;
    end
    theta=theta-temp;
    J(itr)=sum((X*theta-y).^2);
end
Y=theta(1)+theta(2)*x1+theta(2)*x2+theta(3)*x3;
plot(xx,Y);
subplot(1,2,2);
plot(J);

右边是成本函数曲线

左边是拟合曲线,右边是成本函数曲线。成本函数收敛得更快。如果我增加迭代次数,成本函数输出保持不变,但拟合曲线会改变。但如果我这样做

            temp(i)=sum((X*theta-y))*alpha*1/m; 

代码工作正常。

在此处输入图像描述

标签: algorithmmatlabmachine-learningoctave

解决方案


推荐阅读