qq_43534129
qq_43534129
2019-04-17 22:36

训练一个BP神经网络跟踪一条曲线,最后却越拟合越大,虽然图线形状越来接近单幅值越变越大

5
  • 人工智能
  • 神经网络

图片说明
clear all
clc

inputNums=15; %输入层节点数
outputNums=81; %输出层节点数
hideNums=81; %隐含层节点数
maxcount=100; %最大迭代次数
precision=0.001; %预设精度
alpha=0.85; %学习率
w=rand(inputNums,hideNums); %输入层到隐含层的权值
deltw=zeros(inputNums,hideNums); %权值改变量矩阵
v=rand(hideNums,outputNums); %隐含层到输出层的权值
deltv=zeros(hideNums,outputNums); %权值改变量矩阵
error=zeros(1,outputNums);

in=-4:0.1:4;
expectout=sin(2*in).^2+cos(in.^3); %期望函数

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BP神经网络样本训练 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
count=1; %计数器,计算迭代次数
%%%%%%%%%%%%%%%%%%%%%%%%%%% 获得输入和期望输出%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

while (count<=maxcount) %结束条件1(迭代次数)
for i=1:inputNums
x(i)=in(i);

end
for k=1:outputNums
d(k)=expectout(k);

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 计算实际输出值 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

for j=1:hideNums
out1=0;
for i=1:inputNums
out1=out1+x(i)*w(i,j); %输入层到隐含层的加权和∑x(i)w(i,j)
end
y1(j)=1/(1+exp(-out1)); %隐含层输出值,f(x)=1/(1+exp(-x))
end
for k=1:outputNums
out2=0;
for j=1:hideNums
out2=out2+y1(j)*v(j,k); %隐含层到输出层的加权和∑y1(j)v(j,k)
end
output(k)=1/(1+exp(-out2)); %实际输出值
end

%%%%%%%%%%%%%%%%%%%%%%% 计算误差函数——最速下降法%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

error=0;
for k=1:outputNums             
    error=error+(d(k)-output(k))^2;  
end
error=0.5*error;                     %求均方误差
if(error<precision)                  %结束条件2:(当误差满足给定精度时,跳出循环)
   break;
end 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 权值修正 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

for k=1:outputNums
deltk(k)=(d(k)-output(k))*output(k)*(1-output(k)); %输出层误差偏导
end
for j=1:hideNums
temp=0;
for k=1:outputNums
temp=temp+deltk(k)*v(j,k);
end
deltj(j)=temp*y1(j)*(1-y1(j)); %隐含层偏导
end
for j=1:hideNums
for k=1:outputNums
deltv(j,k)=alpha*deltk(k)*y1(j); %输出层权值v的调整量deltv(已乘学习率)
v(j,k)=v(j,k)+deltv(j,k) ; %权值调整

end

end
for i=1:inputNums
for j=1:hideNums
deltw(i,j)=alpha*deltj(j)*x(i); %输入层权值w的调整量
w(i,j)=w(i,j)+deltw(i,j); %权值调整
end
end
count=count+1;

%%%%%%%%%%%%%%%%%&&%%%%%%%%%%%%%% 作图 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for j=1:hideNums
out1=0;
for i=1:inputNums
out1=out1+x(i)*w(i,j); %输入层到隐含层的加权和∑x(i)w(i,j)
end
y1(j)=1/(1+exp(-out1)); %隐含层输出值,f(x)=1/(1+exp(-x))
end
for k=1:outputNums
out2=0;
for j=1:hideNums
out2=out2+y1(j)*v(j,k); %隐含层到输出层的加权和∑y1(j)v(j,k)
end
output(k)=out2; %实际输出值
end

figure(1)
subplot(1,2,1),plot(x,d,'r-'),title('训练样本输入输出图');   %红色的曲线   
hold on
hndl=plot(x,output);                                        %BP学习效果、蓝色的线
grid on
hold off
pause(0.2)
subplot(1,2,2),plot(count,error,'b.-'),title('误差曲线图');
hold on 
grid on

end


  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答