algorithm - 我的渐变体面正在收敛,但曲线拟合不正确
问题描述
我的 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;
代码工作正常。
解决方案
推荐阅读
- javascript - 如何解决布尔诺言
- c# - 如何使用 IsFaulted、IsCanceled 和 IsCompleted 测试用例测试“ToListAsync”
- sql - 32 位 ODBC 驱动程序连接问题
- html - 使用 XPath 将 HTML 中的信息提取/解析到 Google 表格中
- c++ - 如何添加预防措施以绕过未注册的 Microsoft.ACE.OLEDB.12.0?
- jquery - 无法从 Zend Framework 3 向 Ajax 调用发送 JSON 响应
- c# - Entity Framework core 3.1.1 多级继承
- docker - 通过 Docker 日志记录数据 - .NET Core 3.1 Filebeat ELK
- wso2 - 将 SOAP 消息体发送到端点
- database - VB 如何定位 Access 数据库中的特定表