成本函数中的X * theta如何起作用?

问题描述 投票:1回答:1

在线性回归中,有一个成本函数为:

https://i.stack.imgur.com/TPOVM.png

八度中的代码是:

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 
J = 0;

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta
%               You should set J to the cost.

H = X*theta; 
S = (H - y).^2;
J = 1 / (2*m) * sum(S);

% =========================================================================

end

有人可以告诉我为什么sigma(h0(x(i)))等于向量化X * theta吗?

谢谢

vectorization octave linear-regression
1个回答
1
投票

有人可以告诉我为什么sigma(h0(x(i)))等于向量化X * theta吗?

不是这样。此代码中的任何时候都不会单独计算sigma(h(x_i))。变量H不等于该值,而是一个存储值的(列)向量

 `h(x_i)=dot_product(x_i,theta)` 

对于所有示例。

您在Latex中给出的公式只是说,它希望我们将所有示例的((h(x_i)-y_i))^2相加。您要避免执行的操作是以顺序方式为所有这些示例计算h(x_i),因为这将很耗时。从h(x)的定义中,您知道

#I've written a more general case, and the case `n==1` will correspond to your Latex formula)
h(x_i)=[1 x_i1 ... x_in]*[theta_0 theta_1 ... theta_n]' 

矩阵X的大小为m*n,其中m是示例数。因此向量的每一行

H=X*theta #H is a vector of size m*1

将对应一个h(x_i)

知道这一点,您可以看到它

S=(H-y).^2 #S is a vector of size m*1

是一个向量,每个元素都是(h(x_i)-y_i)^2之一。因此,您只需要将它们全部与sum(S)相加即可从Latex公式中获得sigma的值。

© www.soinside.com 2019 - 2024. All rights reserved.