gpt4 book ai didi

machine-learning - 为什么我的成本函数给出了错误的答案?

转载 作者:行者123 更新时间:2023-11-30 08:56:38 26 4
gpt4 key购买 nike

我已经为成本函数编写了代码,但它给出了错误的答案。

我看了很多遍代码,但找不到错误。

这是我的代码:-

function J = computeCost(X, y, theta)

m = length(y); % number of training examples
s = 0;
h = 0;
sq = 0;

J = 0;

for i = 1:m
h = theta' * X(i, :)';
sq = (h - y(i))^2;
s = s + sq;
end

J = (1/2*m) * s;


end

示例:-

computeCost( [1 2; 1 3; 1 4; 1 5], [7;6;5;4], [0.1;0.2] )

ans = 11.9450

Here the answer should be 11.9450 but my code is giving me this:-

ans =  191.12

我已经检查了矩阵乘法并且代码计算正确。

最佳答案

您似乎误解了运算符(operator)评估顺序。事实上

1/2*m ~= 1/(2*m)

考虑到这一点,您似乎正在计算平均值。与其重新发明轮子,通常最好使用内置函数来完成这项工作,这样可以实现更清晰(且不易出错)的实现:

function J = computeCost(X, y, theta)
h = X * theta;
sq = (h - y).^2;
J = 1/2 * mean(sq);
end
computeCost( [1,2;1,3;1,4;1,5], [7;6;5;4], [0.1;0.2] )
% ans = 11.9450

Try it online!

关于machine-learning - 为什么我的成本函数给出了错误的答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57863775/

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