我是通过Coursera在Andrew Ng教授的机器学习课程的第二周。我们正在进行线性回归,现在我正在处理成本函数的编码。
当我在octave命令行中逐一执行每一行时,我编写的代码正确地解决了问题,但是当我从Octave中的文件computeCost.m文件运行它时返回0。
我到目前为止的代码。
function J = computeCost(X, y, theta)
%COMPUTECOST Compute cost for linear regression
% J = COMPUTECOST(X, y, theta) computes the cost of using theta as the
% parameter for linear regression to fit the data points in X and y
% Initialize some useful values
%m = length(y) % number of training examples
% You need to return the following variables correctly
% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta
% You should set J to the cost.
m = size(X,1);
predictions= X*theta;
sqrErrors= (predictions-y).^2;
J= 1/(2*m) * sum(sqrErrors);
=========================================================================
end
我已经设定
X=[1 1; 1 2; 1 3] y=[1;2;3] and theta=[0,1]
当我在命令提示符中逐个执行上面的行时,当theta = [0; 0]时,我得到J = 0和J = 2.333。但是当我从octave命令行的文件computeCost.m运行相同的代码时无论我为theta设定什么值,我总是得到J = 0.请帮助
答案 0 :(得分:0)
调用computeCost时是否可能出错?你提到你正在从computeCost.m运行脚本。 (我认为最好的是你描述了哪个代码pasrt在哪个文件以及你如何调用函数)
规则是:如果您的函数名称为" computeCost",则应在名为" computeCost.m"的文件中实现该函数(函数直到endfunction)。 (我遗漏了一些例外情况)
您也可能错误地调用computeCost。考虑这个脚本
C = 0;
function C = addthem (A, B)
C = A+B;
endfunction
addthem (2, 3); # This WON'T update C
C = addthem (4, 5); # This will update C
您还可以使用"键盘"设置断点。在computeCost和dbstep从那里。你看过调试功能了吗?使用它们确实值得,因为这使得调试变得非常简单:Debugging in Octave
答案 1 :(得分:0)
问题出在体系结构中。不允许您分别在 computeCost.m 中或手动输入或定义变量。 进行测试的唯一方法是通过ex1.m
因此,请勿在初始的computeCost.m中输入任何变量:只需编辑公式即可。
不用担心在 ex1.m 下是否未定义'y'或'x':这些问题将消失。