laboratorio di fuzzy logic - unimi.it · laboratorio di fuzzy logic ruggero donida labati...

46
Laboratorio di Fuzzy Logic Ruggero Donida Labati Dipartimento di Tecnologie dell’Informazione via Bramante 65, 26013 Crema (CR), Italy [email protected]

Upload: trinhmien

Post on 20-May-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

Laboratorio di Fuzzy Logic

Ruggero Donida Labati

Dipartimento di Tecnologie dell’Informazionevia Bramante 65, 26013 Crema (CR), Italy

[email protected]

Quali problemi?

2© Ruggero Donida Labati 2010

Esempio applicativo 1/2

© Ruggero Donida Labati 2010 3

Esempio applicativo 2/2

© Ruggero Donida Labati 2010 4

Fuzzy Logic Toolbox™ 1/2

• Creazione di Fuzzy Inference Systems tramite– Interfaccia grafica

– M-files

• Possibilità di interagire con Simulink

• Esecuzione diretta di Standalone C

© Ruggero Donida Labati 2010 5

Fuzzy Logic Toolbox™ 2/2

• Conoscenze di base:– Membership Functions

– Logical Operations

– If-Then Rules

– Defuzzification Methods

• Fuzzy Clustering

• ANFIS

© Ruggero Donida Labati 2010 6

Membership Functions• Vengono fornite 11 diverse funzioni (mfdemo)

• Possibilità di definire ed utilizzare nuove funzioni

© Ruggero Donida Labati 2010 7

0

0.2

0.4

0.6

0.8

1trapmf gbellmf trimf gaussmf gauss2mf smf

0

0.2

0.4

0.6

0.8

1zmf psigmf dsigmf pimf sigmf

0

0.2

0.4

0.6

0.8

1trapmf gbellmf trimf gaussmf gauss2mf smf

0

0.2

0.4

0.6

0.8

1zmf psigmf dsigmf pimf sigmf

Logical Operations

© Ruggero Donida Labati 2010 8

If-Then Rules 1/3• Interpreting if-then rules is a three-part process.

– Fuzzify inputs: Resolve all fuzzy statements in the antecedent to a degree of membership between 0 and 1. If there is only one part to the antecedent, then this is the degree of support for the rule.

– Apply fuzzy operator to multiple part antecedents: If there are multiple parts to the antecedent, apply fuzzy logic operators and resolve the antecedent to a single number between 0 and 1. This is the degree of support for the rule.

– Apply implication method: Use the degree of support for the entire rule to shape the output fuzzy set. The consequent of a fuzzy rule assigns an entire fuzzy set to the output. This fuzzy set is represented by a membership function that is chosen to indicate the qualities of the consequent. If the antecedent is only partially true, (i.e., is assigned a value less than 1), then the output fuzzy set is truncated according to the implication method.

© Ruggero Donida Labati 2010 9

If-Then Rules 2/3

© Ruggero Donida Labati 2010 10

If-Then Rules 3/3

• Sintassi

– Verbose

• If (service is poor) or (food is rancid) then (tip is cheap)

– Symbolic

• If (service == poor) | (food == rancid) => (tip = cheap)

– Indexed

• 1 1, 1

© Ruggero Donida Labati 2010 11

• Vengono forniti 5 diversi metodi

• Possibilità di definire ed utilizzare nuovi metodi

Defuzzification Methods

© Ruggero Donida Labati 2010 12

Fuzzy Logic Toolbox™ GUI Tools

© Ruggero Donida Labati 2010 13

Implementare un sistema

© Ruggero Donida Labati 2010 14

Problema 1/2Given a number between 0 and 10 that represents the quality of service at a restaurant (where 10 is excellent), and another number between 0 and 10 that represents the quality of the food at that restaurant (again, 10 is excellent), what should the tip be?The starting point is to write down the three golden rules of tipping, based on years of personal experience in restaurants.1. If the service is poor or the food is rancid, then tip is cheap.2. If the service is good, then tip is average.3. If the service is excellent or the food is delicious, then tip is generous.Assume that an average tip is 15%, a generous tip is 25%, and a cheap tip is 5%.

© Ruggero Donida Labati 2010 15

Problema 2/2

Obviously the numbers and the shape of the curve are subject to local traditions, cultural bias, and so on, but the three rules are generally universal.

Il problema viene trattato in aula come esempio di utilizzo del toolkit. Problema trattato dall’Help di Matlab.

http://www.mathworks.com/help/toolbox/fuzzy/fp243dup9.html

© Ruggero Donida Labati 2010 16

Funzioni importanti• Eseguire GUI: fuzzy eventualeNomeFile• Caricare FIS: a = readfis('tipper.fis')• Eseguire FIS: evalfis([input1 input2 inputN], a)• Visualizzare struttura logica FIS: showfis(a)• Visualizzare sorgente: open tipper.fis

• Chiamate alle GUI:– fuzzy(a) displays the FIS Editor– mfedit(a) displays the Membership Function Editor– ruleedit(a) displays the Rule Editor– ruleview(a) displays the Rule Viewer– surfview(a) displays the Surface Viewer

• Visualizzare grafici:– plotfis(a)– plotmf(a,'input',1)– gensurf(a)– showrule(a)

© Ruggero Donida Labati 2010 17

Modalità testuale

• Esempio valutato in aulaa=newfis('tipper');a=addvar(a,'input','service',[0 10]); a=addmf(a,'input',1,'poor','gaussmf',[1.5 0]);a=addmf(a,'input',1,'good','gaussmf',[1.5 5]);a=addmf(a,'input',1,'excellent','gaussmf',[1.5 10]);a=addvar(a,'input','food',[0 10]);a=addmf(a,'input',2,'rancid','trapmf',[-2 0 1 3]);a=addmf(a,'input',2,'delicious','trapmf',[7 9 10 12]);a=addvar(a,'output','tip',[0 30]);a=addmf(a,'output',1,'cheap','trimf',[0 5 10]);a=addmf(a,'output',1,'average','trimf',[10 15 20]);a=addmf(a,'output',1,'generous','trimf',[20 25 30]);ruleList=[ ...1 1 1 1 22 0 2 1 13 2 3 1 2 ];a=addrule(a,ruleList);

© Ruggero Donida Labati 2009 18

Esercizio

• Svolgere autonomamente l’esercizio presente alla pagina web

http://info.iet.unipi.it/~lazzerini/sisd/EsercitazioneFuzzy.pdf

• La soluzione verrà discussa con il docente.

© Ruggero Donida Labati 2010 20

Fuzzy C-Means ClusteringFuzzy c-means (FCM) is a data clustering technique wherein each data point belongs to a cluster to some degree that is specified by a membership grade. This technique was originally introduced by Jim Bezdek in 1981 as an improvement on earlier clustering methods. It provides a method that shows how to group data points that populate some multidimensional space into a specific number of different clusters.

Esempi tratti:esempio 2D Tutorial di Matlabo http://www.mathworks.com/help/toolbox/fuzzy/fp310.html

esempio Iris delle Demo di Matlabo http://www.mathworks.com/products/fuzzylogic/demos.html?file=/products/

demos/shipping/fuzzy/irisfcm.html

© Ruggero Donida Labati 2010 21

Sugeno-Type Fuzzy Inference 1/3

• The first two parts of the fuzzy inference process, fuzzifying the inputs and applying the fuzzy operator, are exactly the same. The main difference between Mamdani and Sugeno is that the Sugeno output membership functions are either linear or constant.

© Ruggero Donida Labati 2010 22

Sugeno-Type Fuzzy Inference 2/3

A typical rule in a Sugeno fuzzy model has the form

If Input 1 = x and Input 2 = y, then Output is z = ax + by + c

For a zero-order Sugeno model, the output level z is a constant

(a=b =0).

The output level zi of each rule is weighted by the firing strength wi of the rule. For example, for an AND rule with Input 1 = x and Input 2 = y, the firing strength is

where F1,2 (.) are the membership functions for Inputs 1 and 2.

The final output of the system is the weighted average of all rule outputs, computed as

© Ruggero Donida Labati 2010 23

Sugeno-Type Fuzzy Inference 3/3

© Ruggero Donida Labati 2010 24

Sugeno-Type Fuzzy Inference: esempio

© Ruggero Donida Labati 2010 25

ANFIS• Suppose you want to apply fuzzy inference to a system for which

you already have a collection of input/output data that you would like to use for modeling, model-following, or some similar scenario. You do not necessarily have a predetermined model structure based on characteristics of variables in your system.

• In some modeling situations, you cannot discern what the membership functions should look like simply from looking at data. Rather than choosing the parameters associated with a given membership function arbitrarily, these parameters could be chosen so as to tailor the membership functions to the input/output data in order to account for these types of variations in the data values. In such cases, you can use the Fuzzy Logic Toolbox neuro-adaptive learning techniques incorporated in the anfis command.

© Ruggero Donida Labati 2010 26

ANFIS GUI• anfisedit

© Ruggero Donida Labati 2010 27

ANFIS: esercizi

• Verranno svolti in aula due esercizi proposti dal docente.

• Leggere ed eseguire autonomamente gli esempi presenti nel Tutorial Matlab nella sezione “anfis and the ANFIS Editor GUI”

o http://www.mathworks.com/help/toolbox/fuzzy/fp715dup12.html

© Ruggero Donida Labati 2010 28

Esempio 1: sinusoide 1/3• Calcolo dei dataset• Vettore di training (100 numeri casuali compresi tra 0 e 2π)

train_indata = rand(100,1) * 2 * pi; output_train= sin(train_indata);train_data = [train_indata output_train];

• Vettore di testingtest_indata = rand(100,1) * 2 * pi;output_test= sin(test_indata);test_data = [test_indata output_test];

• Plot dei datifigureplot (train_indata, output_train, 'x')hold onplot (test_indata, output_test, 'or')legend('Train', 'Test')

• Salvataggio datisave(‘datiSin', 'train_data', 'test_data');

© Ruggero Donida Labati 2010 29

Esempio 1: sinusoide 2/3

• Carico i dati nello workspace

load (‘datiSin’);

• Richiamo la GUI

anfisedit

• FIS ed addestramento con gli strumenti delle GUI

• Salvare FIS come ApproxSin.fis

© Ruggero Donida Labati 2010 30

Esempio 1: sinusoide 3/3• Controllo risultati• Load

load ('datiSin');mioFIS = readFis('ApproxSin');

• Esecuzione FISout_Train = evalfis(train_data(:,1),mioFIS);out_Test = evalfis(test_data(:,1),mioFIS);

• Dati di confronto correttixVere = 0: pi/100 : 2*pi;yVere = sin(xVere);

• Plotplot(xVere, yVere, 'g');hold onplot (train_data(:,1), out_Train, 'x')plot (test_data(:,1), out_Test, 'or')legend('Theoretical', 'Train', 'Test')

• StatistichemeanErrorTrain = mean(abs(train_data(:,2) - out_Train));meanErrorTest = mean(abs(test_data(:,2) - out_Test));varErrorTrain = var(abs(train_data(:,2) - out_Train));varErrorTest = var(abs(test_data(:,2) - out_Test));

© Ruggero Donida Labati 2010 31

Esempio 2: funzione non lineare 1/2• Output = (1+x0.5+y-1+z-1.5)• Input da 0 a 6• Dati Training

train_indata = 6*rand(100,3);output_train=(1+train_indata(:,1).^0.5+ … train_indata(:,2).^1+ train_indata(:,3).^(-1.5));train_data = [train_indata output_train];

• Dati Testtest_indata = 7*rand(100,3);output_test=(1+test_indata(:,1).^0.5+ test_indata(:,2).^1+ … test_indata(:,3).^(-1.5));test_data = [test_indata output_test];

• Plotfiguresubplot(411), plot(train_indata(:,1))title('Input x training')subplot(412), plot(train_indata(:,2))title('Input y training')subplot(413), plot(train_indata(:,3))title('Input z training')subplot(414), plot(output_train(:,1))title('Output training')

© Ruggero Donida Labati 2010 32

figuresubplot(411), plot(test_indata(:,1))title('Input x testing')subplot(412), plot(test_indata(:,2))title('Input y testing')subplot(413), plot(test_indata(:,3))title('Input z testing')subplot(414), plot(output_test(:,1))title('Output testing')

Esempio 2: funzione non lineare 2/2

• anfisedit

• Testare:– MF s = [4 4 4 4] gaussiane, output = linear, hybrid

training, 50 epoche;

– MF s triangolati;

– MF s = [2 2 2 2];

– 5 epoche;

– output = constant;

– …

© Ruggero Donida Labati 2010 33

Fuzzy image processing

• Diversi tipi di applicazioni:– fuzzy edge detection;

– fuzzy contrast adjustment;

– fuzzy image segmentation;

– fuzzy image enhancement;

– …

• Un metodo interessante consiste nella computazione di un FIS per ogni pixel dell’immagine.

© Ruggero Donida Labati 2010 34

Edge detectors

© Ruggero Donida Labati 2010 35

Fuzzy edge detector 4 pixel 1/2

© Ruggero Donida Labati 2010 36

1

2

3

4

5

6

7

8

9

Matlabmatrice(:)

IF THEN IF THEN

ELSE

Fuzzy edge detector 4 pixel 2/2

• La progettazione delle membership functionsè correllata al tipo di dettagli che si desidera risaltare.

• Valutazione di tre differenti tipologie di membership functions.

© Ruggero Donida Labati 2010 37

Fuzzy edge detector 4 pixel: elaborazione dell’immagine

img = imread('skull.tif');

% Conversione dell'immagine originale in doublecompresi tra 0 ed 1

img = double(img);

img = img ./ max(img(:));

dimY = size(img,1);

dimX = size(img,2);

figure

imshow(img,[])

title('Immagine Input')

% Calcolo del modulo del gradiente

[FX,FY] = gradient(double(img));

gradModule = sqrt((FX.^2)+(FY.^2));

© Ruggero Donida Labati 2010 38

figureimshow(gradModule,[])title('Modulo del gradiente')

imgGFuzzy4 = zeros(dimY, dimX);

gradiente4 = readfis('gradiente4C.fis')

% scansione dell'immagine pixel X pixelfor i = 2 : dimY-1

for j = 2 : dimX-1imgGFuzzy4(i,j) = evalfis([img(i-1, j), img(i, j-1),

img(i+1, j), img(i, j+1)], gradiente4);end

end

figureimshow(imgGFuzzy4,[])title('Gradiente fuzzy 4')

Fuzzy edge detector 8 pixel

© Ruggero Donida Labati 2010 39

1

2

3

4

5

6

7

8

9

Matlabmatrice(:)

IF THEN IF THEN

ELSE

Valutazione in laboratorio del codice fornito dal docente

Image enhancement

© Ruggero Donida Labati 2010 40

Fuzzy background removal 1/2

• If we interpret the image features as linguistic variables, then we can use fuzzy if-then rules to segment the image into different regions. A simple fuzzy segmentation rule may seem as follows:

– IF the pixel is darkAND its neighbourhood is also darkAND homogeneousTHEN it belongs to the background.

© Ruggero Donida Labati 2010 41

Fuzzy background removal 2/2

• Possibile utilizzare tre variabili:

• pixel = intensità del singolo pixel I(i,j)

• media = intensità media del vicinato del pixel I(i,j)

• devStandard = deviazione standard dell’intensitàdel vicinato del pixel I(i,j)

• Discussione dei parametri delle membership functions in base alle caratteristichedell’immagine testata

© Ruggero Donida Labati 2010 42

Fuzzy background removal: elaborazione dell’immagine

img = imread('cellula.jpg');

% Trasformazione dell'immagine originale in double compresi tra 0 ed 1

img = double(rgb2gray(img));

img = img ./ max(img(:));

dimY = size(img,1);

dimX = size(img,2);

figure

imshow(img,[])

title('Immagine Input')

% equalizzazione dell'istogramma

imgEq = histeq(img);

figure, imshow(imgEq,[])

title('Equalizzazione istogramma‘));

© Ruggero Donida Labati 2010 43

% calcolo delle immagini di media e varianzamedia = colfilt(img,[3 3],'sliding',@mean);devStandard = colfilt(img,[3 3],'sliding',@std);

% scansione dell'immagine pixel X pixelfor i = 1 : dimY

for j = 1 : dimXimgSfondo(i,j) = evalfis([img(i,j) media(i,j),

devStandard(i,j)], sfondo);end

end

figureimshow(imgSfondo,[])title('Sfondo fuzzy')

Controllori fuzzy: esercizi

• Vengono proposti i seguenti esercizi:

– http://www.dma.fi.upm.es/java/fuzzy/fuzzyinf/ejemplo1_en.htm

– http://www.dma.fi.upm.es/java/fuzzy/fuzzyinf/ejemplo2_en.htm

© Ruggero Donida Labati 2010 44

Letture consigliate

• S. N. Sivanandam, S. Sumathi, S. N. Deepa, “Introduction to Fuzzy Logic using MatLab,” Springer, 2007

• Help di Matlab inerente al “Fuzzy Logic Toolbox”

© Ruggero Donida Labati 2010 46