2014-10-19 64 views
1

我正在通过Coursera教授Andrew Ng的机器学习课程的第二周。我们正在研究线性回归,现在我正在处理编码成本函数。无法计算成本函数中1个变量的成本

我写的代码正确解决了这个问题,当我在八度命令行中逐一地逐一扫描每一行时,但是当我从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] 

当我在命令提示执行由一个上述线中的一条我得到J = 0和J = 2.333时THETA = [0 0]。但当我从octave命令行运行相同的代码computeCost.m我总是得到J = 0无论我为theta设置什么值..请帮助

+1

我将'computeCost.m'保存在一个文件中。然后'computeCost(X,y,[0; 1])= 0'和'computeCost(X,y,[0; 0]) ans = 2.3333'。两者都是正确的。尝试打印出中间结果进行调试。 – greeness 2014-10-19 22:55:01

+2

通过使用'pwd'检查您是否在正确的目录中来确保您正在执行正确的代码。 – user3 2014-10-20 05:37:53

回答

0

是否有可能在调用computeCost时发生错误?您提到您正在从computeCost.m运行脚本。 (我认为最好的是你描述哪个代码pasrt在哪个文件中,以及如何调用函数)

规则是:如果你的函数名是“computeCost”,则应该实现该函数(function until endfunction)在一个名为“computeCost.m”的文件中。 (有一些例外,我遗漏了)

也有可能您错误地调用了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中设置一个带有“keyboard”的断点,并从那里设置dbstep。你有没有看过调试功能?使用它们真的很值得,因为这使得调试变得非常简单:Debugging in Octave