用bp神经网络实现神经网络pid控制 达到很好的效果
源代码在线查看: wupid.m
%BP based PID Control
clear all;
close all;
xite=0.25;
alfa=0.05;
IN=4;m=5;Out=3; %NN Structure
wi=0.050*rands(m,IN);
wi1=wi;wi2=wi;
wo=0.050*rands(Out,m);
wo1=wo;wo2=wo;
du1=0;
u1=0;
y1=0;
Oh=zeros(m,1); %Output from NN middle layer
I=Oh; %Input to NN middle layer
e2=0;
e1=0;
ts=0.001;
for k=1:1:100
r(k)=1.0;
time(k)=k*ts;
%Unlinear model
a(k)=1.2*(1-0.8*exp(-0.1*k));
y(k)=a(k)*y1/(1+y1^2)+u1;
e(k)=r(k)-y(k);xi=[r(k),y(k),e(k),u1];
x(1)=e(k)-e1;
x(2)=e(k);
x(3)=e(k)-2*e1+e2;
epid=[x(1);x(2);x(3)];
I=xi*wi';
for j=1:1:m
Oh(j)=(exp(I(j))-exp(-I(j)))/(exp(I(j))+exp(-I(j))); %Middle Layer
end
K=wo*Oh; %Output Layer
for l=1:1:Out
K(l)=exp(K(l))/(exp(K(l))+exp(-K(l))); %Getting kp,ki,kd
end
kp(k)=K(1);ki(k)=K(2);kd(k)=K(3);
Kpid=[kp(k),ki(k),kd(k)];
du(k)=Kpid*epid;
u(k)=u1+du(k);
dyu(k)=sign((y(k)-y1)/(du(k)-du1+0.0001));
%Output layer
for j=1:1:Out
dK(j)=2/(exp(K(j))+exp(-K(j)))^2;
end
for l=1:1:Out
delta3(l)=e(k)*dyu(k)*epid(l)*dK(l);
end
for l=1:1:Out
for i=1:1:m
dwo=xite*delta3(l)*Oh(i)-alfa*(wo1-wo2);
end
end
wo=wo1+dwo-alfa*(wo1-wo2);
%Hidden layer
for i=1:1:m
dO(i)=4/(exp(I(i))+exp(-I(i)))^2;
end
segma=delta3*wo;
for i=1:1:m
delta2(i)=dO(i)*segma(i);
end
dwi=xite*delta2'*xi;
wi=wi1+dwi-alfa*(wi1-wi2);
%Parameters Update
du1=du(k);u1=u(k);
y1=y(k);
wo2=wo1;
wo1=wo;
wi2=wi1;
wi1=wi;
e2=e1;
e=e(k);
end
figure(1);
subplot(311);
plot(time,r,'r',time,y,'b');
xlabel('Time(k*ts)');ylabel('输入r输出y');
subplot(312);
plot(time,e,'r');
xlabel('Time(k*ts)');ylabel('误差e(k)');
subplot(313);
plot(time,u,'g');
xlabel('Time(k*ts)');ylabel('控制量U');
figure(2);
subplot(311);
plot(time,kp,'r');
xlabel('Time(k*ts)');ylabel('kp');
subplot(312);
plot(time,ki,'g');
xlabel('Time(k*ts)');ylabel('ki');
subplot(313);
plot(time,kd,'b');
xlabel('Time(k*ts)');ylabel('kd');