-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSinPX4_MLP.m
61 lines (49 loc) · 1.35 KB
/
SinPX4_MLP.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
% Solve an Input-Output Fitting problem with a Neural Network
close all;clear;clc;
%% Set inputs range
xmin = 0;
xmax = 8;
%% without noise
nsample = 15;
x = linspace(xmin,xmax,nsample);
y=sin(pi*x/4);
%% with noise
x1 = linspace(xmin,xmax,nsample);
y1 = sin(pi*x1/4); % model;
x = [x1,x1,x1,x1,x1,x1];
% x = x1;
x = x + randn(size(x))*.1;
y = sin(pi*x/4) + randn(size(x))*.1;
plot(x1,y1,'r','linewidth',3),hold on,plot(x,y,'.')
legend('Model','Noisy data')
%% Input & Target
inputs = x;
targets = y;
%% Create a Fitting Network
hiddenLayerSize = 5;
net = fitnet(hiddenLayerSize);
% Setup Division of Data for Training, Validation, Testing
net.divideParam.trainRatio = 70/100;
net.divideParam.valRatio = 15/100;
net.divideParam.testRatio = 15/100;
% network training function
% net.trainFcn = 'trainlm'; % Levenberg-Marquardt
net.trainFcn = 'trainbr'; % Bayesian Regularization
% Train the Network
net = train(net,inputs,targets);
% view(net)
%% Test MLP Network
xtest = linspace(xmin,xmax,17);
ytest = sin(pi*xtest/4);
output = net(xtest);
%% Compute error
mse_err = mse(ytest,output);
fprintf('Mean Squared Error of test data is %.4f \n',mse_err)
sse_err = sse(ytest,output);
fprintf('Sum of Squared Error of test data is %.4f \n',sse_err)
%% Plot result
figure
plot(xtest,ytest,'-*r');hold on;
plot(xtest,output,'--+');
xlim([xmin,xmax])
legend('Target','Output')