# 請問Back Propagation的程式

e=0.1;

w=zeros(1,16);

x=(linspace(-pi,pi,36));

d=cos(x);

NI=zeros(1,6);

y_1=zeros(1,5);

y_2=zeros(1,36);

count=1;

temp=0;

for i=1:16

w(i)=rand;

w(i)=w(i)-0.5;

end

SI=sprintf('The Initial weight is %3.4f \n',w)

while count<36

for j=1:36

NI(6)=0;

for i=1:5

NI(i)=w(i)*x(j)+w(5+i);

if NI(i)<-1

y_1(i)=-1.25-1/(16*NI(i)+12);

elseif NI(i)>1

y_1(i)=1.25-1/(16*NI(i)-12);

else

y_1(i)=NI(i);

end

NI(6)=NI(6)+y_1(i)*w(10+i);

end

NI(6)=NI(6)+w(16);

if NI(6)<-1

y_2(j)=-1.25-1/(16*NI(6)+12);

elseif NI(6)>1

y_2(j)=1.25-1/(16*NI(6)-12);

else

y_2(j)=NI(6);

end

if abs(d(j)-y_2(j))<0.1

count=count+1;

elseif NI(6)<-1

for i=1:5

k=(d(j)-y_2(j))/(4*NI(6)+3)^2;

w(10+i)=w(10+i)+e*y_1(i)*k;

end

w(16)=w(16)+e*k;

count=1;

elseif NI(6)>1

for i=1:5

k=(d(j)-y_2(j))/(4*NI(6)-3)^2;

w(10+i)=w(10+i)+e*y_1(i)*k;

end

w(16)=w(16)+e*k;

count=1;

else

for i=1:5

k=(d(j)-y_2(j));

w(10+i)=w(10+i)+e*y_1(i)*k;

end

w(16)=w(16)+e*k;

count=1;

end

if count==1

for i=1:5

if NI(i)<-1

w(i)=w(i)+e*x(j)*k*w(10+i)/(4*NI(i)+3)^2;

w(i+5)=w(i+5)+e*k*w(10+i)/(4*NI(i)+3)^2;

elseif NI(i)>1

w(i)=w(i)+e*x(j)*k*w(10+i)/(4*NI(i)-3)^2;

w(i+5)=w(i+5)+e*k*w(10+i)/(4*NI(i)-3)^2;

else

w(i)=w(i)+e*k*x(j)*w(10+i);

w(i+5)=w(i+5)+e*k*w(10+i);

end

end

elseif count==36, break;

end

temp=temp+1;

end

end

SF=sprintf('The Final weight is %3.4f \n',w)

d,y_2,d-y_2

temp

plot(x,y_2,'r',x,d,'b')