gpt4 book ai didi

machine-learning - 使用矢量化的梯度下降的倍频代码未正确更新成本函数

转载 作者:行者123 更新时间:2023-11-30 08:52:37 24 4
gpt4 key购买 nike

我已经使用矢量化实现了以下梯度下降代码,但成本函数似乎没有正确递减。相反,成本函数随着每次迭代而增加。

假设 theta 为 n+1 向量,y 为 m 向量,X 为设计矩阵 m*(n+1)

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)

m = length(y); % number of training examples
n = length(theta); % number of features
J_history = zeros(num_iters, 1);
error = ((theta' * X')' - y)*(alpha/m);
descent = zeros(size(theta),1);

for iter = 1:num_iters
for i = 1:n
descent(i) = descent(i) + sum(error.* X(:,i));
i = i + 1;
end

theta = theta - descent;
J_history(iter) = computeCost(X, y, theta);
disp("the value of cost function is : "), disp(J_history(iter));
iter = iter + 1;
end

计算成本函数为:

function J = computeCost(X, y, theta)
m = length(y);
J = 0;
for i = 1:m,
H = theta' * X(i,:)';
E = H - y(i);
SQE = E^2;
J = (J + SQE);
i = i+1;
end;
J = J / (2*m);

最佳答案

您可以进一步矢量化它:

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y);
J_history = zeros(num_iters, 1);

for iter = 1:num_iters

delta = (theta' * X'-y')*X;
theta = theta - alpha/m*delta';
J_history(iter) = computeCost(X, y, theta);

end

end

关于machine-learning - 使用矢量化的梯度下降的倍频代码未正确更新成本函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26656640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com