Index exceeds the number of array elements (3)
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Tommy
am 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]?
Antworten (0)
Siehe auch
Kategorien
Mehr zu Systems of Nonlinear Equations finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!