重点是掌握BP神经网络的学习算法原理和代码设计方法,应用MATLAB编写BP神经网络训练方法;应用神经网络工具箱设计BP神经网络实现对输入输出数据的模型拟合。
已知:
训练样本: 期望输入:[x1,x2]T=[1,3]T, 期望输出:[t1, t2] T =[0.95, 0.05] T
激发函数f为:。学习步长为η=1。
初始权值和阈值:
%输入
x = [1,3,-1];
%输出
t = [0.95,0.05];
plot(t(1),t(2),'<')
%初始权值
%第二层第一个神经元的输入权值
w_1_i_1 = [1,-2,-3]';
%第二层第二个神经元的输入权值
w_1_i_2 = [2,0,1]';
%第三层第一个神经元的输入权值
w_2_i_1 = [1,0,2]';
%第三层第二个神经元的输入权值
w_2_i_2 = [1,-2,-3]';
plot_x = [];
plot_y = [];
for i=1:1000
In_2_1 = x*w_1_i_1;
In_2_2 = x*w_1_i_2;
o1 = 1/(1+exp(-In_2_1));
o2 = 1/(1+exp(-In_2_2));
In_3_1 = [o1,o2,-1]*w_2_i_1;
In_3_2 = [o1,o2,-1]*w_2_i_2;
y1 = 1/(1+exp(-In_3_1));
y2 = 1/(1+exp(-In_3_2));
plot_x = [plot_x y1];
plot_y = [plot_y y2];
%判断是否满足结果
fprintf('第%d轮\n',i)
disp('result:')
disp([y1,y2])
disp('target:')
disp(t)
if t(1)- y1 <=0.01 && y2 - t(2)<=0.01
disp('success!')
disp(w_1_i_1)
disp(w_1_i_2)
disp(w_2_i_1)
disp(w_2_i_2)
% 画法一
plot(plot_x,plot_y,'b*-');
axis([0,1,0,1]); %设定x轴和y轴的显示范围,分别是x轴显示的最小值 最大值,y轴显示的最小值 最大值
break
end
%计算广义误差
a_2_1 = (t(1)-y1)*y1*(1-y1);
a_2_2 = (t(2)-y2)*y2*(1-y2);
a_1_1 = (a_2_1*w_2_i_1(1)+a_2_2*w_2_i_2(1))*o1*(1-o1);
a_1_2 = (a_2_1*w_2_i_1(2)+a_2_2*w_2_i_2(2))*o2*(1-o2);
%更新权值
yita = 1;
dia_ta_w_1_i_1 = yita*a_1_1*x';
dia_ta_w_1_i_2 = yita*a_1_2*x';
dia_ta_w_2_i_1 = yita*a_2_1*x';
dia_ta_w_2_i_2 = yita*a_2_2*x';
w_1_i_1 = w_1_i_1 + dia_ta_w_1_i_1;
w_1_i_2 = w_1_i_2 + dia_ta_w_1_i_2;
w_2_i_1 = w_2_i_1 + dia_ta_w_2_i_1;
w_2_i_2 = w_2_i_2 + dia_ta_w_2_i_2;
end
x = [1,3]
t = [0.95,0.05]
plot(x(1),x(2),'*'); %绘制原始数据分布图
hold on
plot(t(1),t(2),'o');
hold on
net = newff([0,1],[2,1],{'tansig','tansig'});
net.trainParam.epochs = 100; %训练的最大次数
net.trainParam.goal = 0.005; %全局最小误差
net = train(net,x,t);
O = sim(net,x)
plot(O(1),O(2),'<');
axis([0.9,1,0,4]);
第107轮
result:
0.9448 0.0600
target:
0.9500 0.0500
success!
1.1556
-1.5331
-3.1556
2.2674
0.8022
0.7326
2.0090
3.0271
0.9910
0.0349
-4.8953
-2.0349
第645轮
result:
0.9500 0.0500
target:
0.9500 0.0500
success!
1.1627
-1.5119
-3.1627
2.2721
0.8163
0.7279
2.0236
3.0707
0.9764
-0.0078
-5.0235
-1.9922
>> ANN_By_newff
x =
1 3
t =
0.9500 0.0500
O =
0.9997 0.0597