Exemplo do uso do MatLab para treinamento de uma rede

Como exemplo irei treinar uma rede neural (feed-forward backpropagation network) para aprender a função seno. Essa rede terá 2 camadas ocultas com três e dois neurônios, respectivamente.

%treinar o seno
P=0:.2:2*pi;
T=sin(P);
P
T

net = newff(P,T,[3 2]); %feed-forward backpropagation network.
%net = feedforwardnet([3 2]);
%net = configure(net,P,T);
view(net)

net.trainFcn = 'trainlm';
%traingd Gradient descent backpropagation
%traingda Gradient descent with adaptive learning rate backpropagation
%traingdm Gradient descent with momentum backpropagation
%traingdx Gradient descent with momentum and adaptive learning rate backpropagation
%trainlm Levenberg-Marquardt backpropagation

net.layers{1}.transferFcn = 'tansig';
%purelin Linear
%tansig Tangente hiperbolica
%logsig Sigmoide
%satlin Linear com saturacao
net.layers{2}.transferFcn = 'purelin';

net.trainParam.epochs=50; %Número máximo de iterações
net.trainParam.lr=0.05; %Taxa de aprendizagem
net.trainParam.goal=1e-4; %Erro desejado
net.trainParam.min_grad=1e-3;%Minimum performance gradient
net.trainParam.max_fail=6; %Maximum validation failures

Ptrain=P;
Ttrain=T;

%E=1;
%i=1;
%while E>0.01
% i

[net, tr]=train(net,Ptrain,Ttrain);
%tr
figure(1)
plotperf(tr)

%Ctrain = sim(net, Ptrain);
%E = 100*mean(abs((Ttrain-Ctrain)./Ttrain))
%i=i+1;
%end
%net
netopt=net;

%out=net(-2)
%sin(-2)
%out=net(test)
test=0.1:.1:2*pi;
out=sim(netopt,test)
figure(2)
plot(test,out,'ko',test,sin(test),'k:',Ptrain,sin(Ptrain),'r*')