gpt4 book ai didi

matlab - 线性回归代码

转载 作者:行者123 更新时间:2023-12-04 16:45:36 26 4
gpt4 key购买 nike

我正在上 Andrew Ng 的类(class),学习机器学习并实现线性回归算法。

我的代码有什么问题?

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y);
J_history = zeros(num_iters, 1);
h = (X*theta)
for iter = 1:num_iters
theta(1,1) = theta(1,1)-(alpha/m)*sum((h-y).*X(:,1));
theta(2,1) = theta(2,1)-(alpha/m)*sum((h-y).*X(:,2));
J_history(iter) = computeCost(X, y, theta);
end
end

代价函数为:

function J = computeCost(X, y, theta)
m = length(y);
h = (X*theta)
J = (1/(2*m))*sum((h-y).^2)
end

J_history 的值不断增加。它给出了非常异常的(大值),即比应有的值高出大约 1000 倍。

image

最佳答案

您需要更新 for 循环中的 htheta,如下所示

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
h = ((X*theta)-y)'*X;
theta = theta - alpha*(1/m)*h';
J_history(iter) = computeCost(X, y, theta);
end
end

关于matlab - 线性回归代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51985737/

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