Index exceeds the number of array elements (3)

1 visualizzazione (ultimi 30 giorni)
Cenk  Bursali
Cenk Bursali il 23 Apr 2020
Commentato: Cenk Bursali il 24 Apr 2020
Hi,
I have a cost function for 3-layer-feedforward propagation below. Theta is a vector including weight values of first and second layers and I need to convert it to matrices. Therefore, I am using reshape function. Function works, when I try it with correct values of theta, X, y, s1, s2, s3 in command window.
function J= cost_fun(theta, X, y, s1, s2, s3)
m= size(y,1);
theta1= reshape(theta(1:(s2*(s1+1))),s2,s1+1);
theta2= reshape(theta((s2*(s1+1)+1):end),s3,s2+1);
a2= X*theta1';
a2= [ones(size(a2,1),1) a2];
a3= a2*theta2';
J= (1/(2*m))*sum((a3-y).^2);
end
However, when I try to minimize cost function for theta below, I get an error "Index exceeds the number of array elements (3)". Error refers to third line of the function file above. I could not understand why the error occurs.
load dataset
m= size(dataset,1);
X= [ones(m,1) dataset(:,1) dataset(:,1).^2];
y= dataset(:,2);
theta0= [1,1,1];
s1= 2; s2= 2; s3= 1;
A= [];
b= [];
fun= @(theta)cost_fun(theta, X, y, s1, s2, s3);
theta= fmincon(fun, theta0, A, b);
I would be very glad if you help.
Thank you.
  2 Commenti
Tommy
Tommy il 24 Apr 2020
With theta=[1,1,1], s1=2, and s2=2, this line
theta(1:(s2*(s1+1)))
is the same as
theta(1:6)
which would throw your error.
"Function works, when I try it with correct values of theta, X, y, s1, s2, s3 in command window"
What are those values? Specifically what are the dimensions of theta?
"Theta is a vector including weight values of first and second layers and I need to convert it to matrices. Therefore, I am using reshape function."
Can you explain a bit more? What does a theta of [1,1,1] mean, and what should theta1 and theta2 be for a theta of [1,1,1]?
Cenk  Bursali
Cenk Bursali il 24 Apr 2020
theta0 is a vector including initial values of theta for optimization. You are right its size is different from theta vector in the function. That is the source of error. It is solved now.
Thank you very much.

Accedi per commentare.

Risposte (0)

Categorie

Scopri di più su Systems of Nonlinear Equations in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by