help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Pass multiple parameters to a function to use with fminunc


From: Kai Torben Ohlhus
Subject: Re: Pass multiple parameters to a function to use with fminunc
Date: Fri, 1 May 2020 23:16:45 +0900
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.7.0

On 5/1/20 10:56 PM, Tempo98 wrote:
> I have this function on a .m file:
> 
> ---------------------------------------------------------
>> function [jVal, gradient] = costFunction(theta, m, X, Y)
>>  jVal = (1/(2*m)) * sum((X*theta-Y) .^2);
>>  gradient = X'*(X*theta-Y);
>> endfunction
> ----------------------------------------------------
> 
> and I would like to run it through fminunc in another script that looks like
> so:
> 
> ------------------------------------------------------------------
> clear, clc
> 
> % loading the data and scaling it
> data = csvread('data.csv');
> mu = mean(data);
> dev = std(data);
> for i =1:size(data, 2)
>   data(:, i) = (data(:, i) - mu(i)) * (1/dev(I));
> endfor
> 
> % extracting the features (X) and labels from the data (Y)
> Y = data(:, end);
> X = [ones(size(Y, 1), 1) data(:, [1:end-1])];
> 
> % number of training examples (m) and number of features (n)
> [m, n] = size(X);
> 
> % initializing starting theta vector
> iniTheta = zeros(n, 1);
> 
> options = optimset('GradObj', 'on', 'MaxIter', 100)
> 
> [optTheta, minValue] = fminunc(@costFunction, iniTheta, options)
> ---------------------------------------------------------------------------------
> 
> how can I do so while also passing the m, X and Y parameters?
> 
> 


One idea is to write a wrapping anonymous function [1], e.g.

   cFunction = @(theta) costFunction(theta, m, X, Y)

Your calling program should look like this:

---------------------------------------------------------------------------------
% loading the data and scaling it
data = rand (20, 2);
mu = mean(data);
dev = std(data);
for i =1:size(data, 2)
  data(:, i) = (data(:, i) - mu(i)) * (1/dev(i));
endfor

% extracting the features (X) and labels from the data (Y)
Y = data(:, end);
X = [ones(size(Y, 1), 1) data(:, [1:end-1])];

% number of training examples (m) and number of features (n)
[m, n] = size(X);

% initializing starting theta vector
iniTheta = zeros(n, 1);

options = optimset('GradObj', 'on', 'MaxIter', 100)

cFunction = @(theta) costFunction(theta, m, X, Y);

[optTheta, minValue] = fminunc(cFunction, iniTheta, options)
---------------------------------------------------------------------------------

HTH,
Kai

[1] https://octave.org/doc/v5.2.0/Anonymous-Functions.html



reply via email to

[Prev in Thread] Current Thread [Next in Thread]