function BPNet
%% 参数初始化
l = 0.09; % 学习率
n = 20; % 样本数
cells1 = 4; % 神经元个数
cells2 = 2;
times = 3000; % 训练轮数
x = (linspace(0,2*pi*19/20,20)); % 选取样本点
t = 0.5*(1+cos(x)); % 样本需要学习的函数
w1 = rand(cells1,1); % 随机赋值第一层连接权系数 [6 ,1] [4, 1]
w2 = rand(cells2,cells1); % 随机赋值第二层连接权系数 [1, 6] [2, 4]
w3=rand(1,cells2); % 随机赋值第三层连接权系数 [1, 2]
yw1 = rand(cells1,1); % 随机赋值第一层输出阈值 [6, 1] [4, 1]
yw2 = rand(cells2,1); % 随机赋值第二层输出阈值 [1] [2, 1]
yw3=rand; % 随机赋值第三层输出阈值 [1]
y = rand(1,n); % 随机赋值输出
counts = 1; % 计数值初始化
e=zeros(1,times); % 均方差初始值设为0
%% 学习过程
for i=1:times % 学习轮数
ei=0;
for a=1:n % 样本数
net1=w1*x(a)-yw1; % 第一层网络的输入 [6, 1] [4, 1]
out1=logsig(net1); % 第一层网路的输出 [6, 1] [4, 1]
net2=w2*out1-yw2; % 第二层网络的输入 [1, 6]*[6 ,1]=[1] [2, 1]
out2=logsig(net2); % 第二层网络的输出 [1] [2, 1]
net3=w3*out2-yw3; % 第三层网络的输出 [1]
y(a)=net3; % 第三层网络的输出 [1]
det3=t(a)-y(a); % 计算偏差 [1]
det2=((det3*(w3))'.*out2).*(1-out2); %%2*1 ([6, 1]'*[6 ,1])*[6, 1] = [6, 1] [2, 1]
det1=((det2'*(w2))'.*out1).*(1-out1);%%4*1 [4, 1]
w1=w1+det1*x(a)*l; % [6, 1] [4, 1]
w2=w2+(det2*out1')*l; % [1, 6] [2, 4]
w3=w3+(det3*out2')*l; % [1, 2]
yw1=-det1*l+yw1;
yw2=-det2*l+yw2;
yw3=-det3*l+yw3;
ei=ei+det3^2/2;
e(i)=ei;
end % 结束一次样本遍历
if ei<0.008
break;
end
counts=counts+1;
end % 结束学习
%% 计算学习的曲线
for a=1:n
net1=w1*x(a)-yw1;
out1=logsig(net1);
net2=w2*out1-yw2;
out2=logsig(net2);
net3=w3*out2-yw3;
y(a)=net3;
end
%% 绘图
subplot(2,1,1);
plot(x,t,'b-',x,y,'ro-');
grid on
title('BP学习方法逼近y=0.5*(1+cos(x))');
xlabel('x轴');
ylabel('y=0.5*(1+cos(x))');
if (counts<times)
count=1:counts;
sum=counts;
else
count=1:times;
sum=times;
end
subplot(2,1,2);
plot(count,e(1:sum));
grid on;
title('BP算法学习曲线');
xlabel('迭代次数');
ylabel('Mean-Square-Error');
return;
没有合适的资源?快使用搜索试试~ 我知道了~
例3-2 BP神经网络代码
资源推荐
资源详情
资源评论
收起资源包目录
例3-2 BP神经网络.zip (2个子文件)
Eg3_2BPNet.m 2KB
BPNet.m 2KB
共 2 条
- 1
资源评论
梁小憨憨
- 粉丝: 1063
- 资源: 11
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功