Index exceeds the number of array elements (3)
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Tommy
2020-4-24
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]?
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Systems of Nonlinear Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!