文章目录
1.回顾
假设函数: hθ(x) = θ0 + θ1x
代价函数:
2.代价函数的代码实现
现有一个数据集,目标是定义一个函数来计算代价函数J(θ),不同θ值所对应的代价函数值J。
代价函数costFunctionJ代码如下:
function J = costFunctionJ(X, y, theta)
%x is the "design matrix" containing our training examples.
% y is the class labels
m= size(X,1);%number of training examples
predictions = X*theta; % predictions of hypothesis on all m examples
sqrErrors = (predictions - y).^2; % squared errors
J= 1/(2*m) * sum(sqrErrors) ;
执行代价函数:
X=[1 1;1 2;1 3];
y = [1;2;3];
theta = [0;0];
j = costFunctionJ(X,y,theta)
运行结果: