我正在通过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设置什么值..请帮助
我将'computeCost.m'保存在一个文件中。然后'computeCost(X,y,[0; 1])= 0'和'computeCost(X,y,[0; 0]) ans = 2.3333'。两者都是正确的。尝试打印出中间结果进行调试。 – greeness 2014-10-19 22:55:01
通过使用'pwd'检查您是否在正确的目录中来确保您正在执行正确的代码。 – user3 2014-10-20 05:37:53