Aula prática: Redes Neurais

48
Aula prática: Redes Neurais Tiago Pessoa Ferreira de Lima Teresa Bernarda Ludermir {tpfl2,tbl}@cin.ufpe.br

Transcript of Aula prática: Redes Neurais

Aula prática: Redes NeuraisTiago Pessoa Ferreira de Lima

Teresa Bernarda Ludermir

{tpfl2,tbl}@cin.ufpe.br

Objetivos

Apresentar um breve panorama de uma das principais ferramentas

disponíveis no mercado para se trabalhar com Redes Neurais Artificiais.

MATLAB

O que é?

Toolboxs:

Fuzzy Logic;

Global Optimization;

Image Processing;

Neural Network;

Etc.

MATLAB – Interface

MATLAB – Interface

MATLAB – Interface

MATLAB – Interface

MATLAB – Interface

MATLAB – O básico

Matrizes

Operadores

Aritméticos

Para Conjuntos

Relacionais

Lógicos

Scripts & Funções

Condicionais

Repetições

MATLAB – Matrizes

São definidos por colchetes.

“Espaço” ou “Vírgula” separam colunas;

“Ponto e vírgula” ou “Enter” separam linhas.

Exemplos:

>> vetor = [1, 2, 3]

vetor = 1 2 3

>> matriz = [1, 2, 3; 4, 5, 6]

matriz =

1 2 3

4 5 6

MATLAB – Matrizes

Algumas funções permitem a criação de matrizes:

zeros: cria uma matriz com 0’s

>> m = zeros(2)

m =

0 0

0 0

>> m = zeros(2,3)

m =

0 0 0

0 0 0

MATLAB – Matrizes

Algumas funções permitem a criação de matrizes:

ones: cria uma matriz com 1’s

>> m = ones(2)

m =

1 1

1 1

>> m = ones(2,3)

m =

1 1 1

1 1 1

MATLAB – Matrizes

Algumas funções permitem a criação de matrizes:

rand: cria uma matriz com números aleatórios (distribuição uniforme)

>> m = rand(2)

m =

0.8147 0.1270

0.9058 0.9134

>> m = rand(2,3)

m =

0.6324 0.2785 0.9575

0.0975 0.5469 0.9649

MATLAB – Matrizes

Algumas funções permitem a criação de matrizes:

randn: cria uma matriz com números aleatórios (distribuição normal)

>> m = randn(2)

m =

0.3591 -0.2273

-0.7943 1.5938

>> m = randn(2,3)

m =

0.1552 -0.3377 -0.7094

0.1786 -1.5250 -0.8666

MATLAB – Matrizes

Dúvidas em algumas dessas funções?

>> help randn

randn Normally distributed pseudorandom numbers. R = randn(N) returns an N-

by-N matrix containing pseudorandom values drawn from the standard

normal distribution. randn(M,N) or randn([M,N]) returns an M-by-N matrix.

randn(M,N,P,...) or randn([M,N,P,...]) returns an M-by-N-by-P-by-... array. randn

returns a scalar. randn(SIZE(A)) returns an array the same size as A.

MATLAB – Matrizes

Acessando os elementos de uma matriz

>> matriz = [1, 2, 3; 4, 5, 6; 7, 8, 9]

matriz =

1 2 3

4 5 6

7 8 9

>> matriz(3,2)

ans =

8

MATLAB – Matrizes

Transposta (‘)

>> matriz = [1, 2, 3; 4, 5, 6; 7, 8, 9]

matriz =

1 2 3

4 5 6

7 8 9

>> matriz'

ans =

1 4 7

2 5 8

3 6 9

MATLAB – Matrizes

Concatenação de matrizes

>> A = [1, 2];

>> B = [3, 4];

>> C = [A, B]

C =

1 2 3 4

>> D = [A; B]

D =

1 2

3 4

MATLAB – Matrizes

O operador dois pontos (:)

valorInicial : incremento : valorFinal

>> 5 : -1 : 1

ans =

5 4 3 2 1

valorInicial : valorFinal

>> 1 : 5

ans =

1 2 3 4 5

MATLAB – Operadores Aritméticos

>> A = [1 2; 4 5];

>> B = [3 1; 6 8];

>> C = A / B

C =

-0.2222 0.2778

0.1111 0.6111

>> D = A * B

D =

15 17

42 44

Operador Significado Exemplo

+ Adição de dois valores A = B + C

- Subtração de dois valores A = B - C

* Multiplicação de dois valores A = B * C

/ Quociente de dois valores (a direita) A = B / C

\ Quociente de dois valores (a esquerda) A = B \ C

^ Exponenciação A = B ^ C

MATLAB – Operadores para Conjuntos

>> A = [1 2; 4 5];

>> B = [3 1; 6 8];

>> C = A ./ B

C =

0.3333 2.0000

0.6667 0.6250

>> D = A .* B

D =

3 2

24 40

Operador Significado Exemplo

.* Multiplicação de dois valores A = B .* C

./ Quociente de dois valores (a direita) A = B ./ C

.\ Quociente de dois valores (a esquerda) A = B .\ C

.^ Exponenciação A = B .^ C

MATLAB – Operadores Relacionais

>> X = 5;

>> X > 0

ans =

1

>> A = [1 2;3 4];

>> B = [1 3;3 5];

>> C = A == B

C =

1 0

1 0

Operador Significado Exemplo

> Maior do que X > 5

>= Maior ou igual a X >= 10

< Menor do que X < 5

<= Menor ou igual a X <= 10

== Igual a X == 0

~= Diferente de X ~= 0

MATLAB – Operadores Lógicos

>> X = 5;

>> X >= 0 && X <= 9

ans =

1

>> X >= 9 || X <= 0

ans =

0

>> X ~= 0

ans =

1

Operador Significado Exemplo

&& Operador E X >= 0 && X <= 9

|| Operador OU X >= 9 || X <= 0

~ Operador NEGAÇÃO X ~= 10

MATLAB – Scritps

Arquivo texto com a lista de

comandos a ser executado.

% Exemplo de um script

a = sin(0.5);

fprintf('a = %d\n', a);

MATLAB – Funções

Para criar uma função é preciso

que a primeira linha do arquivo

contenha a seguinte forma:

function [var1, var2, …, varN] =

nomeDaFuncao(param1,

param2, …, paramM);

function indice imc(peso, altura)

indice = peso / altura^2;

end

MATLAB – Condicionais

if

if expressaoCondicional

sequenciaDeComandos

end

if-else

if expressaoCondicional

sequenciaDeComandos

else

sequenciaDeComandos

end

MATLAB – Condicionais

switch

switch variavel

case valor1

sequenciaDeComandos

case {valor2, valor3, …}

sequenciaDeComandos

otherwise

sequenciaDeComandos

end

MATLAB – Repetições

while

while expressaoCondicional

sequenciaDeComandos

end

for

for variavel = valorInicial : incremento : valorFinal

sequenciaDeComandos

end

MATLAB – Repetições

parfor

parfor variavel = valorInicial : incremento : valorFinal

sequenciaDeComandos

end

* parfor só executa com o toolbox de processamento paralelo

MATLAB – Repetições

continue: interrompe a execução atual do laço, avançando para a sua

próxima iteração;

break: interrompe a execução do laço e o termina, avançando para a

primeira instrução fora do laço.

MATLAB – NNSTART

MATLAB – NPRTOOL

MATLAB – NPRTOOL

MATLAB – NPRTOOL

MATLAB – NPRTOOL

MATLAB – NPRTOOL

MATLAB – NPRTOOL

MATLAB – NPRTOOL

MATLAB – NPRTOOL

MATLAB – NPRTOOL

MATLAB – NPRTOOL

MATLAB – NPRTOOL

MATLAB – NPRTOOL

MATLAB – Script simples

% This script assumes these variables are defined:

%

% wineInputs - input data.

% wineTargets - target data.

inputs = wineInputs;

targets = wineTargets;

MATLAB – Script simples

% Create a Pattern Recognition Network

hiddenLayerSize = 10;

net = patternnet(hiddenLayerSize)

% Setup Division of Data for Training, Validation, Testing

net.divideParam.trainRatio = 70/100;

net.divideParam.valRatio = 15/100;

net.divideParam.testRatio = 15/100;

MATLAB – Script simples

% Train the Network

[net,tr] = train(net,inputs,targets);

% Test the Network

outputs = net(inputs);

errors = gsubtract(targets,outputs);

performance = perform(net,targets,outputs)

% View the Network

view(net)

MATLAB – Script avançado

% Choose Input and Output Pre/Post-Processing Functions

% For a list of all processing functions type: help nnprocess

net.inputs{1}.processFcns = {'removeconstantrows','mapminmax'};

net.outputs{2}.processFcns = {'removeconstantrows','mapminmax'};

% For help on training function 'trainscg' type: help trainscg

% For a list of all training functions type: help nntrain

net.trainFcn = 'trainscg'; % Scaled conjugate gradient

MATLAB – Projeto

Escolha uma base em UCI Machine Learning Repository e desenvolva um

artigo usando o template do IEEE contendo:

Introdução com a descrição do problema abordado;

Descrição dos 3 algoritmos de treinamento utilizados;

Experimentos e resultados com testes estatísticos;

Conclusão e trabalhos futuros.

UCI Machine Learning: https://archive.ics.uci.edu/ml/datasets.html

Template IEEE: https://www.ieee.org/conferences_events/conferences/publishing/templates.html