我正在通過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