为什么我不能计算 CostFunction J
Why can't I calculate CostFunction J
这是我对 CostFunctionJ
的实现:
function J = CostFunctionJ(X,y,theta)
m = size(X,1);
predictions = X*theta;
sqrErrors =(predictions - y).^2;
J = 1/(2*m)* sum(sqrErrors);
但是当我尝试在 MATLAB 中输入命令时:
>> X = [1 1; 1 2; 1 3];
>> y = [1; 2; 3];
>> theta = [0,1];
>> J = CostFunctionJ(X,y,theta)
它给我以下错误:
Error using *
Inner matrix dimensions must agree.
Error in CostFunctionJ (line 4)
predictions = X*theta;
正如评论中所建议的,错误是因为 x
是 3x2
维度,theta
是 1x2
维度,所以你不能 X*theta
.
我怀疑你想要:
theta = [0;1]; % note the ; instead of ,
% theta is now of dimension 2x1
% X*theta is now a legit operation
这将导致:
>> predictions = X*theta
predictions =
1
2
3
这是我对 CostFunctionJ
的实现:
function J = CostFunctionJ(X,y,theta)
m = size(X,1);
predictions = X*theta;
sqrErrors =(predictions - y).^2;
J = 1/(2*m)* sum(sqrErrors);
但是当我尝试在 MATLAB 中输入命令时:
>> X = [1 1; 1 2; 1 3];
>> y = [1; 2; 3];
>> theta = [0,1];
>> J = CostFunctionJ(X,y,theta)
它给我以下错误:
Error using *
Inner matrix dimensions must agree.
Error in CostFunctionJ (line 4)
predictions = X*theta;
正如评论中所建议的,错误是因为 x
是 3x2
维度,theta
是 1x2
维度,所以你不能 X*theta
.
我怀疑你想要:
theta = [0;1]; % note the ; instead of ,
% theta is now of dimension 2x1
% X*theta is now a legit operation
这将导致:
>> predictions = X*theta
predictions =
1
2
3