%% sample data
t_s=linspace(-pi,pi,50);
f_s=sin(t_s);
figure
plot(t_s,f_s,'*r')
grid on
%% single layer perceptron
% Solve an Input-Output Fitting problem with a Neural Network
% This script assumes these variables are defined:
% t_s - input data.
% f_s - target data.
input_sample = t_s;
target = f_s;
% Choose a Training Function
trainFcn = 'trainlm'; % Levenberg-Marquardt backpropagation.
% Create a Fitting Network
hiddenLayerSize = 10;
net = fitnet(hiddenLayerSize,trainFcn);
% Setup Division of Data for Training, Validation, Testing
net.trainParam.showWindow=0;
net.divideParam.trainRatio = 70/100;
net.divideParam.valRatio = 15/100;
net.divideParam.testRatio = 15/100;
% % Train the Network
% [net,tr] = train(net,input_sample,target);
%
% % Test the Network
% y = net(input_sample);
% e = gsubtract(target,y);
% performance = perform(net,target,y)
%% train the net 10times and obtain 10 networks.The best will be selected
Num_Train=30;
for i=1:Num_Train
[NetWorks{i},NetTrain{i}]=train(net,input_sample,target);
Y{i}=NetWorks{i}(input_sample);
Er{i}=gsubtract(target,Y{i});
Pref(i)=perform(net,target,Y{i});
end
[val,id_best_net]=min(Pref);
disp(['The best net modified by re-train is number:',num2str(id_best_net)])
% View the Network
% view(net)
% Plots
% Uncomment these lines to enable various plots.
%figure, plotperform(tr)
%figure, plottrainstate(tr)
%figure, ploterrhist(e)
%figure, plotregression(t,y)
%figure, plotfit(net,x,t)
%% Check which is best fitting domain=[-pi:0.01:pi]
x_desire=-pi:0.01:pi;
for i=1:Num_Train
fit_v{i}=NetWorks{i}(x_desire);
end
figure
plot(t_s,f_s,'or')
hold on
plot(x_desire,fit_v{1},'m')
plot(x_desire,fit_v{2},'g')
plot(x_desire,fit_v{5},'b')
plot(x_desire,fit_v{7},'y')
plot(x_desire,fit_v{id_best_net},'r','LineWidth',2.5)
legend('sample data','networks 1','networks 2','networks 5','networks 7','best networks')
grid on
%% change the number of the layer
hiddenLayerSize = [10,5];
net_Lay = fitnet(hiddenLayerSize,trainFcn);
% Setup Division of Data for Training, Validation, Testing
net_Lay .trainParam.showWindow=0;
net_Lay .divideParam.trainRatio = 70/100;
net_Lay .divideParam.valRatio = 15/100;
net_Lay .divideParam.testRatio = 15/100;
Num_Train=30;
for i=1:Num_Train
[NetWorks_Lay{i},NetTrain_Lay{i}]=train(net_Lay ,input_sample,target);
Y_Lay{i}=NetWorks_Lay{i}(input_sample);
Er_Lay{i}=gsubtract(target,Y_Lay{i});
Pref_Lay(i)=perform(net,target,Y_Lay{i});
end
[val_lay,id_best_net_lay]=min(Pref_Lay);
disp(['The best net modified by lay is number:',num2str(id_best_net_lay)])
for i=1:Num_Train
fit_Lay_v{i}=NetWorks_Lay{i}(x_desire);
end
[val,val_lay]
figure
plot(t_s,f_s,'or')
hold on
plot(x_desire,fit_v{id_best_net},'r','LineWidth',2.5)
plot(x_desire,fit_Lay_v{id_best_net_lay},'g','LineWidth',2.5)
legend('sample data','modified by train','modified by layer')