You are on page 1of 4

Họ và tên: Phạm Trung Kiên

MSSV: 20195062
Mã lớp: 141505

1. Code
% Initial weights and biases
w1 = rand(3,1);
b1 = rand(3,1);
w2 = rand(1,3);
b2 = rand;

p = -2:0.1:2;

y = 1 + cos(p*pi/4);

Q = length(p);

yn = [];
for i = 1:Q
a0 = p(i);

a1 = tansig(w1*a0+b1);
a2 = purelin(w2*a1+b2);
yn(i) = a2;
end

figure(1);
plot(p,y,'k',p,yn,'k--');
legend('Target','Network output');
xlabel('x');
ylabel('y');
grid on;

a = 0.01; % Learning rate


E = 10000; % Number of epochs
PI = zeros(1,E); % Store the cost function

for j = 1:E;
J = 0;
for i=1:Q
% Forward propagation
a0 = p(i);
a1 = tansig(w1*a0+b1);
a2 = purelin(w2*a1+b2);
t = y(i);
e = t - a2;

% Sensitivity backpropagation
s2 = -2*e;
s1 = ((diag(ones(3,1)))-diag(a1.^2))*w2'*s2;
% Weight update
w1 = w1 - a*s1*a0;
b1 = b1 - a*s1;
w2 = w2 - a*s2*a1';
b2 = b2 - a*s2;
end
yn = [];
for i = 1:Q
a0 = p(i);
a1 = tansig(w1*a0+b1);
a2 = purelin(w2*a1+b2);
yn(i) = a2;
e = y(i)-yn(i);
J = J + e^2;
end
PI(j)=J/Q; % Cost function after each epoch
end

% Plot network output after trainig


figure(2);
plot(p,y,'k',p,yn,'r--');
legend('Target','Trained network output')
xlabel('x');
ylabel('y');
grid on;

% Plot cost function


figure(3);
loglog(PI);
xlabel('No. of epochs');
ylabel('MSE');
grid on

2. Kết quả

You might also like