2020-10-18 16:01

# matlab实现Bp神经网络拟合函数100*(x2-x1^2)^2+（1-x1)^2=f误差太大

clc,clear
Data = -5:1:5;
Value = zeros(11,11);
for i = 1:11
for j = 1:11
x1 = Data(i);
x2 = Data(j);
Value(i,j) = 100*(x2-x1^2)^2+(1-x1)^2;
end
end
W1 = rand(20,1);%输入层x1与隐含层之间的权重
W12 = rand(20,1);%输入层x2与隐含层之间的权重
B1 = rand(20,1);%隐含层神经元的阈值
W2 = rand(1,20);%隐含层与输出层之间的权重
B2 = rand();%输出层神经元的阈值
yita = 0.0005;
loop = 5000;
E = zeros(1,loop);%误差随迭代次数的变化
for loopi = 1:loop
tempsume = 0;
Y = zeros(11,11);%模型输出的结果
for i = 1:11
for k = 1:11
x1= Data(i);%输入层输入数据
x2= Data(k);
hidein = x1*W1+x2*W12-B1;%隐含层的输入数据
hideout = zeros(20,1);%隐含层的输出数据
for j = 1:20
hideout(j) = sigmod(hidein(j));
end
y = W2*hideout-B2;%输出
Y(i,k) = y;
e = y-Value(i,k);%误差
%反馈，修改参数
dB2 = -1*yita*e;
dW2 = e*yita*hideout';
dB1 = zeros(20,1);
for j = 1:20
dB1(j) = W2(j)*sigmod(hidein(j))*(1-sigmod(hidein(j)))*(-1)*e*yita;
end
dW1 = zeros(20,1);
dW12 =zeros(20,1);
for j = 1:20
dW1(j) = W2(j)*sigmod(hidein(j))*(1-sigmod(hidein(j)))*x1*e*yita;
dW12(j) = W2(j)*sigmod(hidein(j))*(1-sigmod(hidein(j)))*x2*e*yita;
end
W1 = W1-dW1;
W12 = W12-dW12;
B1 = B1-dB1;
W2 = W2-dW2;
B2 = B2-dB2;
tempsume = tempsume + abs(e);
end
end
E(loopi) = tempsume;
end

figure(1)
plot(E,'-r')
hold on
grid on
Data1=-5:0.5:5;
Value1 = zeros(21,21);
for i = 1:21
for j = 1:21
x1 = Data1(i);
x2 = Data1(j);
Value1(i,j) = 100*(x2-x1^2)^2+(1-x1)^2;
end
end
Y1 = zeros(21,21);
for i = 1:21
for k = 1:21
x1= Data1(i);%输入层输入数据
x2= Data1(k);
hidein = x1*W1+x2*W12-B1;%隐含层的输入数据
hideout = zeros(20,1);%隐含层的输出数据
for j = 1:20
hideout(j) = sigmod(hidein(j));
end
y = W2*hideout-B2;%输出
Y1(i,k) = y;
e(i,k) = y-Value1(i,k);%误差
end
end
figure(2)
plot(e,'-g')
hold on
grid on

• 写回答
• 好问题 提建议
• 关注问题
• 收藏
• 邀请回答