2014-10-19 31 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