redes neuronais · para implementar as redes do exercício 1 é necessário definir as topologias...
TRANSCRIPT
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Redes Neuronais
1Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Modelo do Perceptrão• Cada neurónio é composto por dois elementos:
• o primeiro adiciona os produtos entre os sinais de entrada e respectivos pesos
• este produto, representado por ‘a’ representa o valor de activação do neurónio• o segundo implementa uma função de transferência não linear (função
de activação)• y=f(a) representa a saída do elemento não linear e também a saída do neurónio
2Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Perceptron
3Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Exercício 1
4Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Exercício 1 (resolução)
5
1. E m p r i m e i r o l u g a r é n e c e s s á r i o d e fi n i r a fronteira de classificação, desenhando uma linha que separe os conjuntos de pon tos b rancos e de pontos pretos.
2. Em seguida será necessário encontrar os pesos e os bias W.
3. Os vectores de pesos devem ser ortogonais às fronteiras de decisão e apontar na direcção dos pontos a classificar como 1 (pontos pretos).
4. O comprimento dos vectores não é relevante.
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Exercício 1 (resolução)
6
Um conjunto possível de vectores de pesos seria:
Para calcular os bias para cada perceptrão é necessário escolher um ponto p pertencente à fronteira de decisão e resolver a seguinte equação:
Assim obtêm-se os seguintes biases:
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Feed-forward Neural Networks
7
• A neural network is composed of several artificial neurons with connections between them and disposed in layers.
• Several architectures exist - we will study the most common: the feedforward network.
• Its name derives from the fact that the neurons in each layer feed their output forward to the next layer until the neural network’s final output is produced.
Hidden layer
Input layer
Output layer
Feedforward network
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
RN Feedforward com uma camada
8Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Exercício 2
9
2. Use o p ro tó t ipo defin ido em feedforward1layer.pl para validar os resultados obtidos no exercício 1.
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Exercício 2 (resolução)
10
Para implementar as redes do exercício 1 é necessário definir as topologias respectivas no início do ficheiro feedforward1layer.pl:
Para obter a resposta da rede à entrada [ 2 -1 ] usa-se a seguinte query :
A resposta da primeira rede a esta entrada seria:
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
FF - Implementação (1)
% topologia:% 1 output node (n3), 2 input nodes (n1,n2)noded(n3,[(b3,0),(n1,3),(n2,0.2)]).
% Main predicate solve/1% Example of a query for a net with 2 input nodes:% ?- solve([2,3]).
solve(In):- findall(N,noded(N,_),LN), propag(In,LN,Out), report(LN,Out).
propag(_,[],[]).propag(In,[N|LN],[Out|LOut]):- noded(N,LW), findall(W,member((_,W),LW),LW1), sumproduct([1|In],LW1,A), % 1: bias input activation_function(A,Out), propag(In,LN,LOut).
11
feedforward1layer.pl
pesos
a = x1w1 + x2w2
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
FF - Implementação (2)
sumproduct([],[],0).sumproduct([H1|V1],[H2|V2],E):- sumproduct(V1,V2,E1), E is E1+H1*H2.
activation_function(A,0):-A<0,!.activation_function(_,1).
report([N|LN],[Out|LOut]):- write('Node '),write(N), write(': '),write(Out),nl,
report(LN,LOut).report([],[]).
12Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Aprendizagem RN 1 camada
Regra Delta
13
t – saída do exemplo de treino (valor esperado)y – saída do neurónioe – erro
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Exercício 3
14
3 . O p r o t ó t i p o q u e f o i d e fi n i d o e m f eed forward1 layer_de l taLearn ing .p l implementa uma rede neuronal de uma camada com aprendizagem. Use o protótipo para resolver os problemas descritos na alínea 1. Compare os vectores de pesos obtidos pelo algoritmo de aprendizagem com os vectores de pesos que obteve na alínea 1.
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Implementação (1)
:-dynamic examples/1.:-dynamic noded/2.
% 1 output node (n3), 2 input nodes (n1,n2)noded(n3,[(b3,_),(n1,_),(n2,_)]).
% Training examples% example(Inputs, Outputs)
example([1,2],[1]).example([-1,2],[0]).example([0,-1],[0]).example([-1,5],[0]).example([-1,6],[1]).
15
feedforward1layer_deltaLearning.pl
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Implementação (2)
16
solve(In):-
findall(N,noded(N,_),LN), findall((X,T),example(X,T),LEx), assert(examples(LEx)), initial_weights(LN),
% random weight generation learning(LEx,LN), % learning phase write('Weights:'),nl, findall(_,(noded(_,LW),write(LW),nl),_),
% show learning results propag(In,LN,Out), % propagation phase report(LN,Out).
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Implementação (3)
17
initial_weights([N|LN]):- retract(noded(N,LW)), init_weights(LW,LW1), assert(noded(N,LW1)), initial_weights(LN).initial_weights([]).
init_weights([(N,_)|LW],[(N,W)|LW1]):- W is rand(200)/100-1, init_weights(LW,LW1).init_weights([],[]).
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Implementação (4)
learning(LEx,LN):- learn(LEx,LN), converge(LEx,LN).
learn([(X,T)|LEx],LN):- propag(X,LN,Y), error(T,Y,E), update_weights(LN,X,E), learn(LEx,LN).learn([],_).
error([],[],[]).error([T|LT],[Y|LY],[E|LE]):- E is T-Y, error(LT,LY,LE).
18Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Implementação (5)
converge(LEx,LN):- converge1(LEx,LN),!.converge(LEx,LN):- learning(LEx,LN).
converge1([],_).converge1([(X,T)|LEx],LN):- propag(X,LN,Y), E is abs(T-Y), E==0, converge1(LEx,LN).
19Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Implementação (6)
20
update_weights([N|LN],X,[E|LE]):- retract(noded(N,LW)), update_weights1(LW,[1|X],E,LW1), assert(noded(N,LW1)), update_weights(LN,X,LE).update_weights([],_,[]).
update_weights1([(N,W)|LW],[X|LX],E,[(N,W1)|LW1]):- W1 is W+E*X, update_weights1(LW,LX,E,LW1).update_weights1([],[],_,[]).
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Implementação (7)
?- solve([5,5]).Weights:[ (b3,-3.11), (n1,5.04), (n2,1.45)]Node n3: 1
21
No Chimera, enviar um termo a outro agente equivale a agendar um evento nesse outro agente ("event posting").
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Exercício 5
22
5 . C o n s i d e r e o p r o b l e m a d e classificação não linear definido na Figura. Defina a topologia da rede e respect ivos pesos de modo a implementar esse classificador. Use o protótipo feedforwardmultilayer.pl para testar a rede.
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
RN Feedforward multi-camada
Perceptrão 3: define zona à direita da recta vermelhaPerceptrão 4: define zona acima da recta verdePerceptrão 5: implementa a função lógica and entre as duas zonas anteriores, definindo a zona cinzenta
23
?- solve([5,2]).NN output:Node n5 :1
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Implementação (1)
% Net topology
% processing layerslayers([l2,l3]).
% nodes of each layerlayer_nodes(l2,[n3,n4]).layer_nodes(l3,[n5]).
% the nodes of input layer does not perform processing
% the number of weights of each node must be equal to the number of nodes of the previous layer less 1 (bias input)
% the first weight of each node is the weight of the bias input
24
No Chimera, enviar um termo a outro agente equivale a agendar um evento nesse outro agente ("event posting").
feedforwardmultilayer.pl
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Implementação (2)
25
noded(n3,[(b3,-10),(n1,2),(n2,1)]).noded(n4,[(b4,-2),(n1,0),(n2,1)]).noded(n5,[(b5,-1.5),(n3,1),(n4,1)]).
% Main predicate solve/1% Example of a query for a net with 2 input nodes:% ?- solve([5,5]).
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Implementação (2)
solve(In):- propag(In,Out), write('NN output:'),nl, layers(Layers),reverse(Layers,[LayerOut|_]), layer_nodes(LayerOut,Nodes), report_out(Nodes,Out).
report_out([],[]).report_out([Node|Nodes],[Out|Outs]):- write('Node '), write(Node), write(' :'), write(Out), nl, report_out(Nodes,Outs).
propag(In,Out):- layers(L), propag(In,L,Out).
propag(In,[L1|LL],Out):- layer_nodes(L1,LNodes), process_layer_nodes(In,LNodes,Out1), propag(Out1,LL,Out).propag(Out,[],Out).
26Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Implementação (3)
process_layer_nodes(_,[],[]).process_layer_nodes(In,[N1|LNodes],[F1|Out]):- noded(N1,LW),linear(LW,LW1), sumproduct([1|In],LW1,A1), % 1: bias input activation_function(A1,F1), process_layer_nodes(In,LNodes,Out).
sumproduct([],[],0).sumproduct([H1|V1],[H2|V2],E):- sumproduct(V1,V2,E1), E is E1+H1*H2.
activation_function(E,0):-E<0,!.activation_function(_,1).
27Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Aprendizagem Backpropagation
Método de aprendizagem de RN multi-camada
28Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Aprendizagem Backpropagation
1.Propagação dos sinais de entrada ao longo da rede• Propagação através dos nós da camada de entrada
29Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Aprendizagem Backpropagation
30
• Propagação dos sinais de entrada ao longo da rede• Propagação através dos nós da camada oculta
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Aprendizagem Backpropagation
31
• Propagação dos sinais de entrada ao longo da rede• Propagação através dos nós da camada de saída
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Aprendizagem Backpropagation
32
• Determinação do erro de saída• O sinal de saída da rede ‘y’ é comparado com o valor desejado
‘t’ (target), obtido a partir dos dados de treino; a diferença é designada de sinal de erro ‘e’ dos neurónios da camada de saída
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Aprendizagem Backpropagation
33
2.Propagação inversa do erro• Não é possível determinar o erro dos neurónios internos porque os
seus valores de saída esperados não são conhecidos - resolvido com o algoritmo Backpropagation
• A ideia é propagar o erro aos nós da camada anterior, cujas saídas foram usadas como entradas do neurónio considerado.
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Aprendizagem Backpropagation
34
• Propagação inversa do erro• Este processo é aplicado em todas as camadas• Se os erros propagados provêm de vários neurónios, os erros
são somados
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Aprendizagem Backpropagation
35
3. Actualização dos pesos• Depois de calculado o erro de um neurónio, os pesos podem ser modificados• f’ representa a derivada da função de transferência do neurónio cujo peso é
actualizado• n afecta o ritmo de aprendizagem; este parâmetro pode variar ao longo da
aprendizagem (iniciar com um valor alto e diminuir à medida que a rede converge).
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Aprendizagem Backpropagation
36Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Exercício 6
37
O protótipo definido em prolognn.pl implementa uma rede multi-camada com aprendizagem backpropagation. Use o protótipo para resolver o problema descrito na alínea 5.
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Backpropagation – Implementação (1)
38
%% General parameters
learning_rate(0.5).
iteractions(40).
solution_threshold(0.5).
%% Activation function
activation_function(E,S):- sigmoid(E,S).
sigmoid(X,S):-S is 1/(1+exp(-X)).
%% Activation function derivative
derivative(A,D):- sigmoid(A,S), D is S*(1-S).
prolognn.pl
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Backpropagation – Implementação (2)
39
%% Problem parameters % Training data
example([1,1,0,1],[0]). example([0,1,1,0],[1]). example([0,0,0,0],[0]). … % Net topology
% processing layers layers([l2,l3]). % nodes of each layer layer_nodes(l2,[n5,n6]). layer_nodes(l3,[n7]).
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Backpropagation – Implementação (3)
40
% Initial weights (can be randomly generated)
% the nodes of input layer does not perform processing
% the number of weights of each node must be equal to the number of nodes of the previous layer less 1 (bias input)
% the first weight of each node is the weight of the bias input:
noded(n5,[(b5,0.22),(n1,0.23),(n2,0.26),(n3,0.27),(n4,0.211)]). noded(n6,[(b6,0.245),(n1,0.152),(n2,0.102),(n3,0.105),(n4,0.205)]). noded(n7,[(b7,0.2),(n5,0.12),(n6,0.112)]).
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Backpropagation – Implementação (3)
41
:-dynamic node/5.:-dynamic examples/1.
:-consult(nnlearn).:-consult(param).
% Main predicate solve/1% Example of a query for a net with 4 input nodes:% ?- solve([1,1,0,1]).
solve(In):- nl,write('Forward propagation'),nl, propag(In,Out), write('NN output:'),nl, layers(Layers),reverse(Layers,[LayerOut|_]), layer_nodes(LayerOut,Nodes), report_out(Nodes,Out).
report_out([],[]).report_out([Node|Nodes],[Out|Outs]):- write('Node '), write(Node), write(' :'), write(Out), nl, report_out(Nodes,Outs).
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Backpropagation – Implementação (4)
42
propag(In,Out):- layers(L), propag(In,L,Out).
propag(In,[L1|LL],Out):- layer_nodes(L1,LNodes), process_layer_nodes(In,LNodes,Out1), propag(Out1,LL,Out).propag(Out,[],Out).
process_layer_nodes(_,[],[]).process_layer_nodes(In,[N1|LNodes],[F1|Out]):- node(N1,_,LW,_,_),linear(LW,LW1), sumproduct([1|In],LW1,A1), % 1: bias input activation_function(A1,F1), retract(node(N1,_,_,_,_)), assert(node(N1,In,LW,A1,_)), process_layer_nodes(In,LNodes,Out).
...
Para cada c a m a d a , p r o c e s s a r os seus nós
Para cada nó, calcular a soma de produtos e c h a m a r a f u n ç ã o d e activação
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Backpropagation – Implementação (5)
43
% Main predicate for learning phase learn/0% ?- learn.
learn:- init, learn0(1), nl, write('*****************'), nl, write('End of learning phase'), nl, report_weights.
learn0(N):- iteractions(N),!.learn0(N):- write('##################'),nl, write('Iter:'),write(N),nl, examples(LE), learn1(1,LE), N1 is N+1, learn0(N1).
learn1(N,[E|LE]):- learn2(N,E), N1 is N+1, learn1(N1,LE).learn1(_,[]).
predicado learn
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Backpropagation – Implementação (6)
44
learn2(N,(X,T)):- propag(X,YL), % forward propagation dif(T,YL,EL), % calculate errors of output layer nodes layers(Layers),reverse(Layers,[LayerOut|Layers1]), set_errors(LayerOut,EL), % set errors of output layer nodes backerror(Layers1), % error back-propagation update(Layers), % weights update report(N,LayerOut,EL).
backerror([Layerl|Layers]):- layer_nodes(Layerl,LNodes), backerror1(LNodes), backerror(Layers).backerror([]).
backerror1([N|LNodes]):- forwardNodes(N,LNF), retract(node(N,In,W,A,_)), derivative(A,D), calc_sum_error(N,LNF,SumErr), E is SumErr*D, assert(node(N,In,W,A,E)), backerror1(LNodes).backerror1([]).
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Backpropagation – Implementação (7)
45
calc_sum_error(N,[NF|LN],SumErr):- node(NF,_,LW,_,E), member((N,W),LW), calc_sum_error(N,LN,SumErr1), SumErr is SumErr1+W*E.calc_sum_error(_,[],0).
forwardNodes(N,LN):- findall(X,(noded(X,L),member((N,_),L)),LN). set_errors(Layer,Errors):- layer_nodes(Layer,LNodes), set_errors1(LNodes,Errors).
set_errors1([N1|LNodes],[E|Errors]):- retract(node(N1,Inputs,W,A,_)), assert(node(N1,Inputs,W,A,E)), set_errors1(LNodes,Errors).set_errors1([],[]).
update([L|Layers]):- layer_nodes(L,Nodes), updateLayerW(Nodes), update(Layers).update([]).
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Backpropagation – Implementação (8)
46
updateLayerW([N|Nodes]):- retract(node(N,In,W,A,E)), updateNodeW([1|In],W,E,W1), % 1 - bias assert(node(N,In,W1,A,E)), updateLayerW(Nodes).updateLayerW([]).
updateNodeW([In|LIn],[(N,W)|LW],E,[(N,W1)|LW1]):- learning_rate(LR), W1 is W+LR*E*In, updateNodeW(LIn,LW,E,LW1).updateNodeW([],[],_,[]). dif([H1|T1],[H2|T2],[E|LE]):- E is H1-H2, dif(T1,T2,LE).dif([],[],[]).
Friday, April 5, 13
Apontamentos Aulas TP de Inteligência Artificial LEI/ISEP – Introdução às Redes Neuronais
Backpropagation – Implementação (9)
47
report(N,LayerOut,EL):- nl, write('Example '), write(N), write(' output nodes error:'), nl, layer_nodes(LayerOut,Nodes), report2(Nodes,EL).
report2([],[]).report2([Node|Nodes],[E|EL]):- write('Node '), write(Node), write(': '), write(E), nl, report2(Nodes,EL).
report_weights:- node(N,_,W,_,_), write('Node '), write(N), write(' - weights: '), write(W),nl, fail.report_weights.
init:- retractall(node(_,_,_,_,_)), findall(_,(noded(N,W),assert(node(N,_,W,_,_))),_), retractall(examples(_)), findall((X,T),example(X,T),LE), assert(examples(LE)).
Friday, April 5, 13