作业帮 > 综合 > 作业

matlab来实现梯度下降算法,为什么误差越来越大?下面是源代码

来源:学生作业帮 编辑:灵鹊做题网作业帮 分类:综合作业 时间:2024/06/13 00:42:49
matlab来实现梯度下降算法,为什么误差越来越大?下面是源代码
function [ theta,J_history ] = gradientDescent( X,y,theta,alpha,num_iters )
%GRADIENTDESCENT Summary of this function goes here
% Detailed explanation goes here
m=size(X,1);
J_history = zeros(num_iters,1);
for iter=1:num_iters
p=theta(1)-alpha*(sum((X*theta-y).*X(:,1)));
q=theta(2)-alpha*(sum((X*theta-y).*X(:,2)));
theta(1)=p;
theta(2)=q;
J_history(iter) = computeCost(X,y,theta);
end
end
matlab来实现梯度下降算法,为什么误差越来越大?下面是源代码
你for循环里怎么没有m出现?
应该是
p= theta(1) - (alpha / m) * sum((X * theta - y).* X(:,1));
q= theta(2) - (alpha / m) * sum((X * theta - y).* X(:,2));
再问: 我第一次的时候添加进去了,但得到的误差值还是递增的,不知道怎么回事,我实验了一个这样的例子,
data=[1 1;
2 2.2;
3 2.8;
4 4.2;
5 5.3;
6 6;
7 7.5;
8 8.2;
9 9
];
b=[1 1 1 1 1 1 1 1 1];
data=[b' data];
这就是训练的数据
再答: 那你的theta,alpha给的值是多少?
再问: 嗯嗯,发现问题了,是alpha取大了,所以越过了最小值,谢谢了哈