gpt4 book ai didi

octave - 使用 fminunc 实现的线性回归

转载 作者:行者123 更新时间:2023-12-04 16:09:42 26 4
gpt4 key购买 nike

我正在尝试在 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)

这里是成本函数,它返回梯度以及成本函数的值。

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.

由于您的输入是一个成本函数(即将您选择的参数向量与成本相关联),因此您的成本函数的输入参数需要通过 fminunc< 进行优化 只是 theta,因为 xy(即您的观察和您的目标)被认为是问题的“给定”方面,而不是您正在尝试的事情优化。所以你要么声明 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

关于octave - 使用 fminunc 实现的线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44848279/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com