使用 fminunc 实现的线性回归

Linear Regression using fminunc Implementation

我正在尝试使用 Octave 中的 fminunc 实现仅具有一项功能的线性回归。

这是我的代码。

x = load('/home/battousai/Downloads/ex2Data/ex2x.dat');
y = load('/home/battousai/Downloads/ex2Data/ex2y.dat');

m = length(y);
x = [ones(m , 1) , x];
theta = [0 , 0]';

X0 = [x , y , theta];

options = optimset('GradObj' , 'on' , 'MaxIter' , 1500);
[x , val] = fminunc(@computeCost , X0 , options) 

这是成本函数,其中 returns 梯度以及成本函数的值。

function [J , gradient] = computeCost(x , y , theta)
  m = length(y);
  J = (0.5 / m) .* (x * theta - y )' * (x * theta - y );
  gradient = (1/m) .* x' * (x * theta - y);
end

数据集的长度为50,即维度为50 x 1。我不知道我应该如何将 X0 传递给 fminunc.

更新的驱动程序代码:

x = load('/home/battousai/Downloads/ex2Data/ex2x.dat');
y = load('/home/battousai/Downloads/ex2Data/ex2y.dat');

m = length(y);
x = [ones(m , 1) x];
theta_initial = [0 , 0];
options = optimset('Display','iter','GradObj','on' , 'MaxIter' , 100);
[X , Cost] = fminunc(@(t)(computeCost(x , y , theta)), theta_initial , options) 

成本函数的更新代码:

function [J , gradient] = computeCost(x , y , theta)
  m = length(y);
  J = (1/(2*m)) * ((x * theta) - y )' * ((x * theta) - y) ;
  gradient = (1 / m) .* x' * ((x * theta) - y);  
end

现在我得到 theta 的值是 [0,0] 但是当我使用正规方程时,theta 的值结果是 [0.750163 , 0.063881]

来自 fminunc 的文档:

FCN should accept a vector (array) defining the unknown variables

X0 determines a starting guess.

由于您的输入是一个 cost 函数(即将您选择的参数向量与成本相关联),因此您的成本函数的输入参数需要通过以下方式进行优化fminunc 只是 theta,因为 xy(即您的观察结果和目标)被认为是问题的 'given' 方面,而不是您要优化的东西.所以你要么声明 xy 全局并从你的函数中访问它们,如下所示:

function [J , gradient] = computeCost(theta_0)
  global x; global y;
  % ...

然后将 fminunc 调用为:fminunc (@computeCost, t_0, options)

,将您的 computeCost 函数保持为 computeCost(x, y, theta),并将您的 fminunc 调用更改为如下内容:

[x , val] = fminunc(@ (t) computeCost(x, y, t) , t0 , options) 

更新 不确定您做错了什么。这是完整的代码和一个 Octave session 运行 它。看起来不错。

%% in file myscript.m
x = load('ex2x.dat');
y = load('ex2y.dat');

m = length(y);
x = [ones(m , 1) , x];
theta_0 = [0 , 0]';

options = optimset('GradObj' , 'on' , 'MaxIter' , 1500);
[theta_opt, cost] = fminunc(@ (t) computeCost(x,y,t) , theta_0 , options) 

%% in file computeCost.m
function [J , gradient] = computeCost(x , y , theta)
  m = length(y);
  J = (0.5 / m) .* (x * theta - y )' * (x * theta - y );
  gradient = (1/m) .* x' * (x * theta - y);
end

%% in the octave terminal:
>> myscript
theta_opt =

   0.750163
   0.063881

cost =    9.8707e-04