Está en la página 1de 133

Programación para la Inteligencia Artificial

Lisp en la IA

Dr. Alejandro Guerra-Hernández

Universidad Veracruzana
Centro de Investigación en Inteligencia Artificial
Sebastián Camacho 5, Xalapa, Ver., México 91000
mailto:aguerra@uv.mx
https://www.uv.mx/personal/aguerra/pia

Maestría en Inteligencia Artificial 2020

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 1 / 133


Contenido

1 Bioinformática: Significancia de los Codones en el Código Genético

2 Arboles de Decisión: CL-ID3

3 Filtrado colaborativo: Rankings y Recomendaciones

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 2 / 133


Bioinformática Código Genético Universal

DNA, Codones y Nucleótidos

I El Código Genético Universal suele representarse como un mapa de 64


codones a 20 aminoácidos.
I Un codón es una tripleta de nucleótidos hN1 , N2 , N3 i donde
Ni ∈ {A, C , G, T , }
I Los nucleótidos incluyen: Adenina (A), Citosina (C), Guanina (G),
Timina (T).

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 3 / 133


Bioinformática Código Genético Universal

Gráficamente

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 4 / 133


Bioinformática Código Genético Universal

Código Genético Universal

I Observen que el prompt ha cambiado al paquete :bioinfo.


1 BIOINFO > ( print-tensor bioinfo ::* gc-tensor *)
2 (( T T T ) PHE ) (( T C T ) SER ) (( T A T ) TYR ) (( T G T) CYS )
3 (( T T C ) PHE ) (( T C C ) SER ) (( T A C ) TYR ) (( T G C) CYS )
4 (( T T A ) LEU ) (( T C A ) SER ) (( T A A ) TER ) (( T G A) TER )
5 (( T T G ) LEU ) (( T C G ) SER ) (( T A G ) TER ) (( T G G) TRP )
6 (( C T T ) LEU ) (( C C T ) PRO ) (( C A T ) HIS ) (( C G T) ARG )
7 (( C T C ) LEU ) (( C C C ) PRO ) (( C A C ) HIS ) (( C G C) ARG )
8 (( C T A ) LEU ) (( C C A ) PRO ) (( C A A ) GLN ) (( C G A) ARG )
9 (( C T G ) LEU ) (( C C G ) PRO ) (( C A G ) GLN ) (( C G G) ARG )
10 (( A T T ) ILE ) (( A C T ) THR ) (( A A T ) ASN ) (( A G T) SER )
11 (( A T C ) ILE ) (( A C C ) THR ) (( A A C ) ASN ) (( A G C) SER )
12 (( A T A ) ILE ) (( A C A ) THR ) (( A A A ) LYS ) (( A G A) ARG )
13 (( A T G ) MET ) (( A C G ) THR ) (( A A G ) LYS ) (( A G G) ARG )
14 (( G T T ) VAL ) (( G C T ) ALA ) (( G A T ) ASP ) (( G G T) GLY )
15 (( G T C ) VAL ) (( G C C ) ALA ) (( G A C ) ASP ) (( G G C) GLY )
16 (( G T A ) VAL ) (( G C A ) ALA ) (( G A A ) GLU ) (( G G A) GLY )
17 (( G T G ) VAL ) (( G C G ) ALA ) (( G A G ) GLU ) (( G G G) GLY )
18 T

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 5 / 133


Bioinformática Significancia

Significancia

I La significancia de un nucleótido Ni , es fuertemente dependiente de


su posición en el codón.
I Generalmente N2 > N1 > N3 .
I Con mayor probabilidad, mutaciones en N3 producirán el mismo
aminoácido, u otro con propiedades físico-químicas similares; no así
en N2 .
I La significancia también está relacionada con las propiedades
físico-químicas de las bases.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 6 / 133


Bioinformática Significancia

Propiedades Físico-Químicas

I Es posible representar el Código Genético como una 6-tupla de la


forma hC1 , H1 , C2 , H2 , C3 , H3 i.
I Ci representa la naturaleza química del nucleótido Ni , es decir, si es
una pirimidina (Y ) o una purina (R).
I Hi representa la fuerza del enlace de hidrógeno del nucleótido Ni y su
complemento, es decir, enlace fuerte (S) o débil (W ).

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 7 / 133


Bioinformática Significancia

Pirimidinas: Timina y Citosina

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 8 / 133


Bioinformática Significancia

Purinas: Adenina y Guanina

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 9 / 133


Bioinformática Significancia

Fuerza de los Enlaces

A=T enlace débil (doble enlace de hidrógeno)


G=C enlace fuerte (triple enlace de hidrógeno)

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 10 / 133


Bioinformática Significancia

Significancia de estas Propiedades

I M.A. Jiménez-Montaño propone el siguiente orden de significancia:


C 2 > H2 > C 1 > H1 > C 3 > H3 .
I R. Swanson propone un orden alternativo: :
C 2 > C 1 > H2 > H1 > C 3 > H3 .
I ¿Cual es el bueno?
I Siguiendo a Mac Dónaill y Manktelow [3], Guerra-Hernández,
Mora-Basáñez y Jiménez-Montaño [2] proponen un enfoque
cuantitativo para establecer tales ordenamientos.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 11 / 133


Bioinformática Metodología

Cuantificando la Similitud

I Se propone mutar un nucleótido seleccionado ó una de sus


propiedades y cuantificar el efecto de tal cambio..
I La matriz PAM250 es una métrica ampliamente usada en análisis de
similitud de secuencias genéticas.
I El elemento sij ∈ PAM250 es una cuantificación de la probabilidad de
que un aminoácido i mute a j sobre un periodo evolutivo. Valores más
pequeños (o negativos) reflejan disimilitud.
I Se pueden considerar otras matrices de similitud.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 12 / 133


Bioinformática Metodología

Significancia de la posición de los nucleótidos

1. Una posición i ∈ {1, 2, 3} es seleccionada.


2. 12 mapeos son posibles: T → {C , A, G}; C → {A, G, T };
A → {G, T , C }; G → {T , C , A}.
3. Los mapeos se aplican a los 64 codones en la posición i, resultando en
un código genético modificado Gcode 0 .
4. Los elementos sij de la matriz de similitud dan un valor numérico que
mide la similitud de los aminoácidos i y j.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 13 / 133


Bioinformática Metodología

Continuación...

5. La significancia global S de un mapeo es computada a partir de los


valores sij , sumados en los 64 codones::
X
S= sGCodei Gcodej0 (1)
i,j=1...64
P
6. La significancia promedio i=1...3 Si /12 se obtiene considerando los
12 posibles mapeos para cada posición de los nucleótidos.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 14 / 133


Bioinformática Metodología

Significancia de las propiedades de los nucleótidos

1. Una i ∈ {1, 2, 3} y una propiedad del nucleótido Ci o Hi son


seleccionados.
2. Dos mapeos son posibles, dependiendo de la propiedad seleccionada:
fC : {R → Y , Y → R} o fH : {W → S, S → W }. Basicamente, esto
se corresponde con un cambio de bit de la propiedad seleccionada..
3. El mapeo correspondiente se aplica a los 64 codones en el Código
Genético, resultando en un código modificado. table GCode 0 . Se
procede como en los pasos 4 y 5 del experimento anterior.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 15 / 133


Bioinformática Resultados

Exp. 1: Similitud para las posiciones

I Como se esperaba N2 > N1 > N3 para todas las matrices


consideradas:
Matriz N1 N2 N3
PAM250 235.91 220.08 281.08
BLOSUM62 242.25 220.83 292.17
Prlić 157.48 142.38 185.40
Miyazawa 27.26 21.91 31.96
Sánchez 87.69 90.88 73.14

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 16 / 133


Bioinformática Resultados

Exp. 2: Similitud para las propiedades físico-químicas

I Valores y ordenes obtenidos:

Matriz C1 H1 C2 H2 C3 H3
PAM250 -16.00 16.00 -60.00 -32.00 122.00 276.00
BLOSUM62 -2.00 1.00 -76.00 -66.00 162.00 302.00
Prlić 18.14 29.34 -26.93 -30.83 111.54 189.84
Miyazawa 7.06 7.02 -18.71 -13.70 21.06 30.70
Sánchez 173.79 135.56 196.88 140.20 100.42 70.88

Matriz Orden
PAM250 C2 > H2 > C1 > H1 > C3 > H3
BLOSUM62 C2 > H2 > C1 > H1 > C3 > H3
Prlić C2 > H2 > C1 > H1 > C3 > H3
Miyazawa C2 > H2 > H1 > C1 > C3 > H3
Sánchez C2 > C1 > H2 > H1 > C3 > H3

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 17 / 133


Bioinformática Paquetes

Paquetes

I Definición y carga
1 ( defpackage " BIOINFO "
2 (: a d d- u s e - d e f au l t s t )
3 (: use " CAPI " ))
4
5 ( in-package : bioinfo )

I Es necesario declarar el paquete y moverse dentro de él, antes de


continuar con el resto de la implementación.
I CAPI es la librería para el diseño de interfaces gráficas de LispWorks.
I Un paquete puede verse como un mapeo entre cadenas de texto y
símbolos.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 18 / 133


Bioinformática Paquetes

Nombres y paquetes

Símbolos no calificados. No contienen : en su nombre. Hacen referencia al


símbolo que denotan en el paquete actual.
Ejemplo: *gc-tensor*
Símbolos calificados. Contienen al menos un : en su nombre. Hacen
referencia al símbolo en un paquete dado. Pueden
ser:
Símbolo externo. Explicitamente exportado por
el paquete.
Ejemplo: bioinfo:*gc-tensor*
Símbolo interno. No exportado por el paquete.
Ejemplo: bioinfo::*gc-tensor*

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 19 / 133


Bioinformática Paquetes

Otras funciones sobre paquetes

I La variable especial *package* contiene el paquete actual:


1 CL - USER > * package *
2 # < The COMMON - LISP - USER package , 23/64 internal , 0/4 external >
3 CL - USER > ( in - package " bioinfo ")
4 # < The bioinfo package , 0/16 internal , 0/16 external >
5 BIOINFO > * package *
6 # < The bioinfo package , 0/16 internal , 0/16 external >

I La directiva :export exporta símbolos.


I Los paquete pueden organizarse por capas , usando use-package.
I Vean el capítulo 21 del libro de Seibel [7].

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 20 / 133


Bioinformática Implementación de la solución

Código Genético Universal

I Recuerden que estamos en el paquete :bioinfo


1 ( defvar * gc-tensor *
2 " The genetic code tensor A ( universal genetic code ) "
3 ’((( t t t ) phe ) (( t c t ) ser ) (( t a t ) tyr ) (( t g t ) cys )
4 (( t t c ) phe ) (( t c c ) ser ) (( t a c ) tyr ) (( t g c ) cys )
5 (( t t a ) leu ) (( t c a ) ser ) (( t a a ) ter ) (( t g a ) ter )
6 (( t t g ) leu ) (( t c g ) ser ) (( t a g ) ter ) (( t g g ) trp )
7 (( c t t ) leu ) (( c c t ) pro ) (( c a t ) his ) (( c g t ) arg )
8 (( c t c ) leu ) (( c c c ) pro ) (( c a c ) his ) (( c g c ) arg )
9 (( c t a ) leu ) (( c c a ) pro ) (( c a a ) gln ) (( c g a ) arg )
10 (( c t g ) leu ) (( c c g ) pro ) (( c a g ) gln ) (( c g g ) arg )
11 (( a t t ) ile ) (( a c t ) thr ) (( a a t ) asn ) (( a g t ) ser )
12 (( a t c ) ile ) (( a c c ) thr ) (( a a c ) asn ) (( a g c ) ser )
13 (( a t a ) ile ) (( a c a ) thr ) (( a a a ) lys ) (( a g a ) arg )
14 (( a t g ) met ) (( a c g ) thr ) (( a a g ) lys ) (( a g g ) arg )
15 (( g t t ) val ) (( g c t ) ala ) (( g a t ) asp ) (( g g t ) gly )
16 (( g t c ) val ) (( g c c ) ala ) (( g a c ) asp ) (( g g c ) gly )
17 (( g t a ) val ) (( g c a ) ala ) (( g a a ) glu ) (( g g a ) gly )
18 (( g t g ) val ) (( g c g ) ala ) (( g a g ) glu ) (( g g g ) gly )))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 21 / 133


Bioinformática Implementación de la solución

Probanndo paquete

I Si forzamos el asunto con bioinfo::*gc-tensor* obtendremos la


matriz, pero con todos sus símbolos calificados explícitamente:
1 CL - USER > bioinfo ::* gc - tensor *
2 ((( T T T ) BIOINFO :: PHE ) (( T BIOINFO :: C T ) BIOINFO :: SER ) ...

I Si nos movemos a :bioinfo, la matriz puede accederse como se hace


normalmente:
1 CL - USER > ( in - package : bioinfo )
2 # < The BIOINFO package , 25/64 internal , 0/16 external >
3 BIOINFO > * gc - tensor *
4 ((( T T T ) PHE ) (( T C T ) SER ) ...

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 22 / 133


Bioinformática Implementación de la solución

Matriz PAM250 I

I La distancia entre el aminoácido del renglón y la columna:


1 ( defvar * pam250 *
2 ; ;; Dayhoff PAM250 ( percent a c c e p t e d m u t a t i o n s ) as r e p o r t e d
3 ; ;; by Mac Donaill , M o l e c u l a r S i m u l a t i o n 30(5) p .269
4 ’(( 2 -2 0 0 -2 0 0 1 -1 -1 -2 -1 -1 -4 1 1 1 -6 -3
5 (-2 6 0 -1 -4 1 -1 -3 2 -2 -3 3 0 -4 0 0 -1 2 -4 -
6 ( 0 0 2 2 -4 1 1 0 2 -2 -3 1 -2 -4 -1 1 0 -4 -2 -
7 ( 0 -1 2 4 -5 2 3 1 1 -2 -4 0 -3 -6 -1 0 0 -7 -4 -
8 (-2 -4 -4 -5 12 -5 -5 -3 -3 -2 -6 -5 -5 -4 -3 0 -2 -8 0 -
9 ( 0 1 1 2 -5 4 2 -1 3 -2 -2 1 -1 -5 0 -1 -1 -5 -4 -
10 ( 0 -1 1 3 -5 2 4 0 1 -2 -3 0 -2 -5 -1 0 0 -7 -4 -
11 ( 1 -3 0 1 -3 -1 0 5 -2 -3 -4 -2 -3 -5 -1 1 0 -7 -5 -
12 (-1 2 2 1 -3 3 1 -2 6 -2 -2 0 -2 -2 0 -1 -1 -3 0 -
13 (-1 -2 -2 -2 -2 -2 -2 -3 -2 5 2 -2 2 1 -2 -1 0 -5 -1
14 (-2 -3 -3 -4 -6 -2 -3 -4 -2 2 6 -3 4 2 -3 -3 -2 -2 -1
15 (-1 3 1 0 -5 1 0 -2 0 -2 -3 5 0 -5 -1 0 0 -3 -4 -
16 (-1 0 -2 -3 -5 -1 -2 -3 -2 2 4 0 6 0 -2 -2 -1 -4 -2
17 (-3 -4 -3 -6 -4 -5 -5 -5 -2 1 2 -5 0 9 -5 -3 -3 0 7 -
18 ( 1 0 0 -1 -3 0 -1 0 0 -2 -3 -1 -2 -5 6 1 0 -6 -5 -
19 ( 1 0 1 0 0 -1 0 1 -1 -1 -3 0 -2 -3 1 2 1 -2 -3 -

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 23 / 133


Bioinformática Implementación de la solución

Matriz PAM250 II

20 ( 1 -1 0 0 -2 -1 0 0 -1 0 -2 0 -1 -3 0 1 3 -5 -3
21 (-6 2 -4 -7 -8 -5 -7 -7 -3 -5 -2 -3 -4 0 -6 -2 -5 17 0 -
22 (-3 -4 -2 -4 0 -4 -4 -5 0 -1 -1 -4 -2 7 -5 -3 -3 0 10 -
23 ( 0 -2 -2 -2 -2 -2 -2 -1 -2 4 2 -2 2 -1 -1 -1 0 -6 -2
24 ) " PAM250 matrix " )

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 24 / 133


Bioinformática Implementación de la solución

Indexación de los aminoácidos I

I Regresa el índice para consultar la matriz de distancia:


1 ( defun index ( aa )
2 ; ; Get the index in a matrix
3 ( cond (( or ( equal aa ’A )
4 ( equal aa ’ ALA )) 0)
5 (( or ( equal aa ’R )
6 ( equal aa ’ ARG )) 1)
7 (( or ( equal aa ’N )
8 ( equal aa ’ ASN )) 2)
9 (( or ( equal aa ’D )
10 ( equal aa ’ ASP )) 3)
11 (( or ( equal aa ’C )
12 ( equal aa ’ CYS )) 4)
13 (( or ( equal aa ’Q )
14 ( equal aa ’ GLN )) 5)
15 (( or ( equal aa ’E )
16 ( equal aa ’ GLU )) 6)
17 (( or ( equal aa ’G )
18 ( equal aa ’ GLY )) 7)
19 (( or ( equal aa ’H )

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 25 / 133


Bioinformática Implementación de la solución

Indexación de los aminoácidos II

20 ( equal aa ’ HIS )) 8)
21 (( or ( equal aa ’I )
22 ( equal aa ’ ILE )) 9)
23 (( or ( equal aa ’L )
24 ( equal aa ’ LEU )) 10)
25 (( or ( equal aa ’K )
26 ( equal aa ’ LYS )) 11)
27 (( or ( equal aa ’M )
28 ( equal aa ’ MET )) 12)
29 (( or ( equal aa ’F )
30 ( equal aa ’ PHE )) 13)
31 (( or ( equal aa ’P )
32 ( equal aa ’ PRO )) 14)
33 (( or ( equal aa ’S )
34 ( equal aa ’ SER )) 15)
35 (( or ( equal aa ’T )
36 ( equal aa ’ THR )) 16)
37 (( or ( equal aa ’W )
38 ( equal aa ’ TRP )) 17)
39 (( or ( equal aa ’Y )
40 ( equal aa ’ TYR )) 18)

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 26 / 133


Bioinformática Implementación de la solución

Indexación de los aminoácidos III

41 (( or ( equal aa ’V )
42 ( equal aa ’ VAL )) 19)
43 (( equal aa ’ ter ) 20)))

I De manera que:
1 BIOINFO > ( index ’ val )
2 19
3 BIOINFO > ( index ’ ter )
4 20

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 27 / 133


Bioinformática Implementación de la solución

Distancias entre aminoácidos I

I Ahora podemos computar la distancia entre dos aminoácidos. Hay


que poner especial cuidado con los terminadores.
1 ( defun get-dist ( aai aaj & optional matrix )
2 ; ;; Get pam250 value in PAM for a m i n o a c i d aai s u b s t i t u t e d by
3 ; ;; a m i n o a c i d s can be coded with one letter or three letters .
4 ; ;; ter to ter = 1 and amino to ter ( and v i c e v e r s a ) = -8
5
6 ( let (( matrix ( cond (( null matrix ) * pam250 *)
7 ( t matrix ))))
8 ( cond (( and ( equal aai ’ ter ) ; ; ter to ter t r a n s i t i o n
9 ( equal aaj ’ ter ))
10 ( cond (( equal matrix * pam250 *) 1)
11 (( equal matrix * codegen *) 0)
12 (( equal matrix * miyazawa *) 0)
13 (( equal matrix * prlic *) 0)
14 (( equal matrix * blosum62 *) 0)
15 (( equal matrix * robersy-grau *)
16 ( nth ( index aaj )
17 ( nth ( index aai ) matrix )))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 28 / 133


Bioinformática Implementación de la solución

Distancias entre aminoácidos II


18 ( t ( error " matrix not defined " ))))
19 (( or ( equal aai ’ ter ) ; ;; amino to ter or ter to amin
20 ( equal aaj ’ ter ))
21 ( cond (( equal matrix * pam250 *) -8)
22 (( equal matrix * codegen *) 6)
23 (( equal matrix * miyazawa *) -1.01)
24 (( equal matrix * prlic *) 0)
25 (( equal matrix * blosum62 *) 0)
26 (( equal matrix * robersy-grau *)
27 ( nth ( index aaj )
28 ( nth ( index aai ) matrix )))
29 ( t ( error " matrix not defined " ))))
30 ( t ( nth ( index aaj )
31 ( nth ( index aai ) matrix ))))))

I De manera que:
1 BIOINFO > ( get-dist ’ val ’ arg )
2 -2
3 BIOINFO > ( get-dist ’ val ’ arg * blosum62 *)
4 -3

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 29 / 133


Bioinformática Implementación de la solución

Distancias entre aminoácidos III

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 30 / 133


Bioinformática Implementación de la solución

Nucleotidos a aminoácidos y viceversa

I Funciones de conversión:
1 ( defun aa-to-nnn ( aa )
2 ; ;; Gets the n u c l e o t i d e s of the a m i n o a c i d
3 ( remove-if # ’( lambda ( aminoacid )
4 ( not ( equal ( cadr aminoacid ) aa )))
5 * gc-tensor *))
6
7 ( defun nnn-to-aa ( nnn )
8 ; ;; Gets the a m i n o a c i d from the n u c l e o t i d e s
9 ( car ( member-if # ’( lambda ( aminoacid )
10 ( equal ( car aminoacid ) nnn ))
11 * gc-tensor *)))

I Corrida
1 BIOINFO > ( aa-to-nnn ’ val )
2 ((( G T T ) VAL ) (( G T C ) VAL ) (( G T A ) VAL ) (( G T G ) VAL ))
3 BIOINFO > ( nnn-to-aa ’( g t t ))
4 (( G T T ) VAL )

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 31 / 133


Bioinformática Implementación de la solución

Imprimer tensores

I Función para imprimir tensores en 4 columnas:


1 ( defun print-tensor ( tensor )
2 ( cond (( null tensor ) t )
3 ( t ( progn
4 ( format t " ~ a ~ a ~ a ~ a ~ %"
5 ( car tensor ) ( cadr tensor )
6 ( caddr tensor ) ( cadddr tensor ))
7 ( print-tensor ( cddddr tensor ))))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 32 / 133


Bioinformática Interfaz gráfica

Interfaz gráfica

I ¿Como podemos programar una interfaz como la siguiente?

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 33 / 133


Bioinformática Interfaz gráfica

CAPI

I Se trata de una librería orientada a objetos que debe importarse


dentro del paquete principal de nuestra aplicación.
I contain puede usarse para ver resultados rápidamente:
1 CL - USER > ( make - instance ’ capi : push - button
2 : data " Button ")
3 CL - USER > ( capi : contain *)

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 34 / 133


Bioinformática Interfaz gráfica

Botones de la interfaz I

I Podemos definir así los botones de la interfaz:


1 ( setq run-s-nnn ( make-instance ’ push-button
2 : text " S-nnn "
3 : callback ’ s-nnn-message
4 : v i s i b l e - m i n - w i d t h ’(: character 7)))
5
6 ( setq run-s-6-bits ( make-instance ’ push-button
7 : text " S-6-bits "
8 : callback ’ s - 6 - b i t s - m e s s a g e
9 : v i s i b l e - m i n - w i d t h ’(: character 7)))
10
11 ( setq run-s * ( make-instance ’ push-button
12 : text " S * "
13 : callback ’s *- message
14 : v i s i b l e - m i n - w i d t h ’(: character 7))
15
16 ( setq exit ( make-instance ’ push-button
17 : text " Salir "
18 : callback # ’( lambda ( data interface )
19 ( qui t-interf ace interface ))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 35 / 133


Bioinformática Interfaz gráfica

Botones de la interfaz II

20 : v i s i b l e - m i n - w i d t h ’(: character 7)))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 36 / 133


Bioinformática Interfaz gráfica

Funciones que llaman los botones I

I Y las funciones que invocan los :callback


1 ( defun s-nnn-message ( data interface )
2 ( declare ( ignore data interface ))
3 ( apply-in-pane-process
4 output
5 # ’( setf d i s p l a y - p a n e - t e x t )
6 ( format nil " Los valores por cod ó n son : ~ %~ %~9: @ < S1 ~ >~9
7 :@ < S2 ~ >~9: @ < S3 ~ >~ %~9: @ <~6 ,3 F ~ >~9: @ <~6 ,3 F ~ >~9: @
8 ( S-nnn 1 ( eval * option *))
9 ( S-nnn 2 ( eval * option *))
10 ( S-nnn 3 ( eval * option *)))
11 output ))
12
13 ( defun s - 6 - b i t s-m e s s a g e ( data interface )
14 ( declare ( ignore data interface ))
15 ( apply-in-pane-process
16 output
17 # ’( setf d i s p la y - p a n e - t e x t )
18 ( format nil " Los valores por bit son :~ %~ %~9: @ < C1 ~ >~9: @ < H1 ~ >~
19 @ < C2 ~ >~9: @ < H2 ~ >~9: @ < C3 ~ >~9: @ < H3 ~ >~ %~9: @ <~6 ,3 F ~

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 37 / 133


Bioinformática Interfaz gráfica

Funciones que llaman los botones II

20 @ <~6 ,3 F ~ >~9: @ <~6 ,3 F ~ >~9: @ <~6 ,3 F ~ >~9: @ <~6 ,3 F ~ >~9


21 @ <~6 ,3 F ~ > "
22 ( S-6bits 1 ( eval * option *))
23 ( S-6bits 2 ( eval * option *))
24 ( S-6bits 3 ( eval * option *))
25 ( S-6bits 4 ( eval * option *))
26 ( S-6bits 5 ( eval * option *))
27 ( S-6bits 6 ( eval * option *)))
28 output ))
29
30 ( defun s *- message ( data interface )
31 ( declare ( ignore data interface ))
32 ( apply-in-pane-process
33 output
34 # ’( setf d i s p la y - p a n e - t e x t )
35 ( format nil " Los valores por cod ó n son : ~ %~ %~9: @ < S1 ~ >~9: @ < S
36 ~9: @ < S3 ~ >~ %~9: @ <~6 ,3 F ~ >~9: @ <~6 ,3 F ~ >~9: @ <~6 ,3 F ~ >
37 ( S * 1 ( eval * option *))
38 ( S * 2 ( eval * option *))
39 ( S * 3 ( eval * option *)))
40 output ))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 38 / 133


Bioinformática Interfaz gráfica

Funciones que llaman los botones III

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 39 / 133


Bioinformática Interfaz gráfica

Formateo de botones

I Ahora podemos formatear los botones en un renglón:


1 ( setq buttons
2 ( make-instance ’ row-layout
3 : description ( list run-s-nnn run-s-6-bits run-s * exit )

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 40 / 133


Bioinformática Interfaz gráfica

Elección de matriz

I Para elegir la matriz de similitud que se usará, podemos usar un panel


de opciones:
1 ( defun set-option ( data interface )
2 ( setq * option * data ))
3
4 ( setq options ( make-instance ’ option-pane
5 : items * options *
6 : selected-item * pam250 *
7 : s e l e c t i o n - c a l l b a c k ’ set-option
8 : title " Matriz de similitud : " ))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 41 / 133


Bioinformática Interfaz gráfica

Panel de salida

I y para desplegar los resultados un panel de display llamado output


porque es ahí donde las acciones de los botones despliegan sus
resultados:
1 ( setq output
2 ( make-instance ’ display-pane
3 : font ( gp : m a k e - f o n t - d e s c r i p t i o n
4 : family " Courier New "
5 : size 12)
6 : foreground : navy
7 : text ’( " Bienvenido a Bioinfo UV / CIIA aguerr
8 : v i s i b l e - m i n - h e i g h t ’(: character 5)))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 42 / 133


Bioinformática Interfaz gráfica

Despliegue de la interfaz

I Finalmente contain despliega toda la interfaz:


1 ( contain
2 ( make-instance ’ column-layout
3 : description ( list options output buttons )))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 43 / 133


Bioinformática Ejecutable

Script para crear un ejecutable


I El script debe cargarse desde el IDE de LispWorks.
1 ; ;; A u t o m a t i c a l l y g e n e r a t e d d e l i v e r y script
2
3 ( in-package " CL-USER " )
4
5 ( l o a d - a l l - p a t c hes )
6
7 ; ;; Load the a p p l i c a t i o n :
8
9 ( compile-file " ~/ Dropbox / code / lisp / pia / cap07 / biinfo / bioinfo . lsp
10 ( load " ~/ Dropbox / code / lisp / pia / cap07 / bioinfo / bioinfo " )
11
12 ; ;; Load the example file that defines W R I T E - M A C O S - A P P L I C A T I O N -
13 ; ;; to create the bundle .
14
15 ( compile-file
16 ( sys : example-file " configuration / m a c o s - a p p l i c a t i o n - b u n d l e . lisp
17 : load t )
18
19 ( deliver ’| BIOINFO |:: start
20 ( when ( s a v e - a r g u m e n t - r e a l - p )
21 ( write-macos-application-bundle
Dr. Alejandro
22 Guerra-Hernández (UV)
" ~/ DropboxProgramación
/ code /paralispla IA MIA
/ pia / cap07 / bioinfo 2020 44./ app
/ bioinfo 133 "
Arboles de Decisión: CL-ID3 Conceptos básicos

Arboles de Decisión

I Los árboles de decisión representan hipótesis sobre una clase, como


una conjunción de disyunciones de atributos proposicionales.
I Recordando un buen día para jugar tenis [4]:
Atributo

Cielo Clase

Valor
nublado
soleado lluvioso

Húmedad si Viento

alta normal fuerte débil

no si no si

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 45 / 133


Arboles de Decisión: CL-ID3 Conceptos básicos

Ejemplos de entrenamiento
I Representación proposicional (atributo-valor)

Día Cielo Temperatura Humedad Viento Jugar-tenis?


1 soleado calor alta débil no
2 soleado calor alta fuerte no
3 nublado calor alta débil si
4 lluvia templado alta débil si
5 lluvia frío normal débil si
6 lluvia frío normal fuerte no
7 nublado frío normal fuerte si
8 soleado templado alta débil no
9 soleado frío normal débil si
10 lluvia templado normal débil si
11 soleado templado normal fuerte si
12 nublado templado alta fuerte si
13 nublado calor normal débil si
14 lluvia templado alta fuerte no

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 46 / 133


Arboles de Decisión: CL-ID3 Conceptos básicos

Clasificación

I Algoritmo:
1: function clasifica(E: ejemplo, A: árbol)
2: Clase ← valor-atributo(raíz(A),E);
3: if es-hoja(raíz(A)) then
4: return Clase
5: else
6: clasifica(E, sub-árbol(A,Clase));
7: end if
8: end function

I Dado el árbol de la página anterior, el siguiente caso:


hCielo = soleado, Temperatura = caliente, Humedad = alta, Viento = fuertei

se clasifica como un día en el que no se jugará tenis.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 47 / 133


Arboles de Decisión: CL-ID3 Conceptos básicos

Inducción de árboles de decisión

I El algoritmo propuesto por Quinlan [5]


1: function ID3(E: ejemplos, A: atributos, C: clase)
2: AD ← ∅; Clase ← clase-mayoritaria(C,E);
3: if E = ∅ then return AD;
4: else if misma-clase(E,C) then return AD ← Clase;
5: else if A = ∅ then return AD ← Clase;
6: else
7: Mejor-Partición ← mejor-partición(E, A);
8: Mejor-Atributo ← primero(Mejor-Partición);
9: AD ← Mejor-Atributo;
10: for all Partición ∈ resto(Mejor-Partición) do
11: Valor-Atributo ← primero(Partición);
12: Sub-E ← resto(Partición);
13: agregar-rama(AD, Valor-Atributo, ID3(Sub-E, {A \ Mejor-Atributo}, C));
14: end for
15: end if
16: end function

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 48 / 133


Arboles de Decisión: CL-ID3 Conceptos básicos

Entropía

I Si los posibles n valores del atributo v , ocurren con probabilidades


P(vi,...,n ), entonces el contenido de información, o entropía, E está
dado por:
n
X
E (P(vi ), . . . , P(vn )) = −P(vi ) log2 P(vi )
i=1

I En nuestro caso, de 14 ejemplos 9 son positivos y 5 son negativos:

9 5
E( , ) = 0,940
14 14

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 49 / 133


Arboles de Decisión: CL-ID3 Conceptos básicos

Ganancia de información

I Es la reducción de la entropía causada por particionar un conj. de


entrenamiento S, con respecto a un atributo a ∈ A:
X |Sv |
ganancia(S, a) = E (S) − E (Sv )
v ∈a |S|

I Observen que el segundo término de ganancia/2, es la entropía con


respecto al atributo a.
I Ejemplo:
ganancia(S, cielo) = 0,24674976

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 50 / 133


Arboles de Decisión: CL-ID3 Conceptos básicos

Mejor atributo

I Aquel que maximiza la ganancia de información:


1 Information gain of attribute CIELO : 0.24674976
2 Information gain of attribute TEMPERATURA : 0.029222548
3 Information gain of attribute HUMEDAD : 0.15183544
4 Information gain of attribute VIENTO : 0.048126936
5 Highest information gain : 0.24674976

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 51 / 133


Arboles de Decisión: CL-ID3 Representaciones

Arboles de Decisión

I Podemos representarlos como una lista de listas:


1 CL - USER > ( setq arbol ’( cielo
2 ( soleado ( humedad
3 ( normal si )
4 ( alta no )))
5 ( nublado si )
6 ( lluvia ( viento
7 ( fuerte no )
8 ( debil si )))))
9
10 ( CIELO ( SOLEADO ( HUMEDAD ( NORMAL SI ) ( ALTA NO )))
11 ( NUBLADO SI ) ( LLUVIA ( VIENTO ( FUERTE NO ) ( DEBIL SI ))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 52 / 133


Arboles de Decisión: CL-ID3 Representaciones

Funciones de acceso al árbol

I Algunas funciones básicas de acceso:


1 ( defun root ( tree )
2 " Returns the root of the decision tree "
3 ( car tree ))
4
5 ( defun sub-tree ( tree value )
6 " Returns the sub-tree under the branch labeled as value "
7 ( second ( assoc value ( cdr tree ))))
8
9 ( defun leaf-p ( tree )
10 " Verifies if tree is a leaf "
11 ( atom tree ))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 53 / 133


Arboles de Decisión: CL-ID3 Representaciones

Ejemplos

I Dado nuestro árbol inicial tenemos que:


1 CL - USER > ( root arbol )
2 CIELO
3 CL - USER > ( sub - tree arbol ’ soleado )
4 ( HUMEDAD ( NORMAL SI ) ( ALTA NO ))
5 CL - USER > ( sub - tree arbol ’ nublado )
6 SI
7 CL - USER > ( leaf ( sub - tree arbol ’ soleado ))
8 NIL
9 CL - USER > ( leaf ( sub - tree arbol ’ nublado ))
10 T

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 54 / 133


Arboles de Decisión: CL-ID3 Representaciones

¿Cómo funciona assoc?

I Regresa el primer cons de su segundo argumento (una lista), cuyo


car es igual a su primer argumento.
I Hay variantes assoc-if y assoc-if-not.
1 CL - USER > ( assoc ’ uno ’(( uno 1) ( dos 2) ( tres 3)))
2 ( UNO 1)
3 CL - USER > ( assoc ’ dos ’(( uno 1) ( dos 2) ( tres 3)))
4 ( DOS 2)
5 CL - USER > ( assoc ’ lluvia ( cdr arbol ))
6 ( LLUVIA ( VIENTO ( FUERTE NO ) ( DEBIL SI )))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 55 / 133


Arboles de Decisión: CL-ID3 Representaciones

Imprimiendo un árbol de decisión

I Observen el uso de loop y terpri:


1 ( defun print-tree ( tree & optional ( depth 0))
2 ( mytab depth )
3 ( format t " ~ A~ %" ( first tree ))
4 ( loop for subtree in ( cdr tree ) do
5 ( mytab (+ depth 1))
6 ( format t " - ~ A " ( first subtree ))
7 ( if ( atom ( second subtree ))
8 ( format t " - > ~ A~ %" ( second subtree ))
9 ( progn
10 ( terpri )
11 ( print-tree ( second subtree ) (+ depth 5))))))
12
13 ( defun mytab ( n )
14 ( loop for i from 1 to n do ( format t " " )))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 56 / 133


Arboles de Decisión: CL-ID3 Representaciones

Ejemplo

I Imprimiendo nuestro árbol:


1 CL - USER > ( print - tree arbol )
2 CIELO
3 - SOLEADO
4 HUMEDAD
5 - NORMAL -> SI
6 - ALTA -> NO
7 - NUBLADO -> SI
8 - LLUVIA
9 VIENTO
10 - FUERTE -> NO
11 - DEBIL -> SI
12 NIL

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 57 / 133


Arboles de Decisión: CL-ID3 Representaciones

Ejemplos de entrenamiento

I Aunque los ejemplos también pueden representarse como una lista de


listas, esto no es buena idea.
I Necesitamos una representación que nos permita relacionar el valor de
un atributo en un ejemplo dado.
I Ejemplo: Supongan que *examples* es mi repositorio de ejemplos:
1 CL - USER > ( get - value ’ cielo ( car * examples *))
2 LLUVIA

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 58 / 133


Arboles de Decisión: CL-ID3 Representaciones

Ejemplos, atributos y valores

I Las bases para la indexación son las siguientes:


1 ( defun put-value ( attr inst val )
2 ( setf ( get inst attr ) val ))
3
4 ( defun get-value ( attr inst )
5 ( get inst attr ))

I Ejemplo:
1 CL - USER > ( put - value ’ nombre ’ ej1 ’ alejandro )
2 ALEJANDRO
3 CL - USER > ( get - value ’ nombre ’ ej1 )
4 ALEJANDRO
5 CL - USER > ( setq * ejemplos * nil )
6 NIL
7 CL - USER > ( push ’ ej1 * ejemplos *)
8 ( EJ1 )
9 CL - USER > ( get - value ’ nombre ( car * ejemplos *))
10 ALEJANDRO

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 59 / 133


Arboles de Decisión: CL-ID3 Representaciones

Archivos de ejemplos: ARFF y CSV

I Un archivo tenis.arff:
@RELATION jugar-tenis

@ATTRIBUTE cielo {soleado,nublado,lluvia}


@ATTRIBUTE temperatura {calor,templado,frio}
@ATTRIBUTE humedad {alta,normal}
@ATTRIBUTE viento {debil,fuerte}
@ATTRIBUTE jugar-tenis {si,no}

@DATA

soleado, calor, alta, debil, no


soleado, calor, alta, fuerte, no
nublado, calor, alta, debil, si
lluvia, templado, alta, debil, si
...

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 60 / 133


Arboles de Decisión: CL-ID3 Librerías ASDF2

With a little help from your friends

I ASFD2 (Another System Definition Facility 2) es una herramienta


para describir como están organizados los archivos fuente de un
sistema Lisp.
I En particular sus dependencias.
I Quicklisp es una herramienta que nos permite instalar librerías que
han sido definidas usando ASDF2.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 61 / 133


Arboles de Decisión: CL-ID3 Librerías ASDF2

Instalando librerías: trivial-shell

I trivial-shell permite ejecutar comandos del shell de Unix.


I Su instalación con quicklisp es como sigue:
1 CL - USER > ( ql : quickload " trivial - shell ")
2 To load " trivial - shell ":
3 Install 1 Quicklisp release :
4 trivial - shell
5 ; Fetching # < QL - HTTP : URL
6 " http :// beta . quicklisp . org / archive / trivial - shell /
7 2011 -05 -22/ trivial - shell -20110522 - http . tgz " >
8 ; 13.61 KB
9 ==================================================
10 13 ,937 bytes in 0.00 seconds (13610.35 KB / sec )
11 ; Loading " trivial - shell "
12 [ package com . metabang . trivial - timeout ]............
13 [ package trivial - shell ]..
14 (" trivial - shell ")

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 62 / 133


Arboles de Decisión: CL-ID3 Librerías ASDF2

Ejecutando comandos shell: grep

I De forma que podemos usar egrep para extraer líneas del archivo
ARFF:
1 CL - USER > ( trivial - shell : shell - command
2 " egrep \" @ATTR \" tenis . arff ")
3 " @ATTRIBUTE cielo { soleado , nublado , lluvia }
4 @ATTRIBUTE temperatura { calor , templado , frio }
5 @ATTRIBUTE humedad { alta , normal }
6 @ATTRIBUTE viento { debil , fuerte }
7 @ATTRIBUTE jugar - tenis { si , no }
8 "
9 NIL
10 0

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 63 / 133


Arboles de Decisión: CL-ID3 Librerías ASDF2

Partiendo cadenas: split-sequence

I Podemos llamar a split-sequence para partir cadenas de texto:


1 CL - USER > ( ql : quickload " split - sequence ")
2 To load " split - sequence ":
3 Load 1 ASDF system :
4 split - sequence
5 ; Loading " split - sequence "
6
7 (" split - sequence ")
8 CL - USER > ( split - sequence : split - sequence #\ , " hola , que , tal ")
9 (" hola " " que " " tal ")
10 14

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 64 / 133


Arboles de Decisión: CL-ID3 Librerías ASDF2

Ensamblando cajitas

I Podemos usar estas facilidades para leer las líneas del archivo ARFF:
1 CL - USER > ( split - sequence : split - sequence #\ Newline
2 ( trivial - shell : shell - command
3 " egrep \" @ATTR \" tenis . arff "))
4 (" @ATTRIBUTE cielo { soleado , nublado , lluvia }"
5 " @ATTRIBUTE temperatura { calor , templado , frio }"
6 " @ATTRIBUTE humedad { alta , normal }" " @ATTRIBUTE viento { debil , fuerte }"
7 " @ATTRIBUTE jugar - tenis { si , no }" "")
8 184

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 65 / 133


Arboles de Decisión: CL-ID3 Carga de Archivos

Variables globales

I Definamos variables globales para nuestro ambiente de trabajo:


1 ( defvar * attributes * nil " The attributes of the problem " )
2 ( defvar * domains * nil " The domain of the attributes " )
3 ( defvar * target * nil " The target concept " )
4 ( defvar * examples * nil " The training set " )
5 ( defvar * trace * nil " Trace the computations " )

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 66 / 133


Arboles de Decisión: CL-ID3 Carga de Archivos

Datos crudos

I Leyendo los datos del conjunto de entrenamiento (líneas que no


comienzan con salto de línea o arroba o punto y coma):
1 ( defun get-data ( arff )
2 ( mapcar # ’( lambda ( x )
3 ( mapcar # ’ r e a d - f r o m - s t r i n g
4 ( spl it-seque nce : sp lit-sequ ence #\ , x )))
5 ( butlast
6 ( spl it-seque nce : sp lit-sequ ence
7 #\ Newline
8 ( trivial-shell : shell-command
9 ( concatenate ’ string
10 " egrep - v \"^ $ |[ @ %]\" "
11 arff ))))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 67 / 133


Arboles de Decisión: CL-ID3 Carga de Archivos

Ejemplo

I Leyendo los ejemplos de entrenamiento:


1 CL - USER > ( get - data " tenis . arff ")
2 (( SOLEADO CALOR ALTA DEBIL NO ) ( SOLEADO CALOR ALTA FUERTE NO ) ( NUBLADO
3 CALOR ALTA DEBIL SI ) ( LLUVIA TEMPLADO ALTA DEBIL SI ) ( LLUVIA FRIO
4 NORMAL DEBIL SI ) ( LLUVIA FRIO NORMAL FUERTE NO ) ( NUBLADO FRIO NORMAL
5 FUERTE SI ) ( SOLEADO TEMPLADO ALTA DEBIL NO ) ( SOLEADO FRIO NORMAL DEBIL
6 SI ) ( LLUVIA TEMPLADO NORMAL DEBIL SI ) ( SOLEADO TEMPLADO NORMAL FUERTE
7 SI ) ( NUBLADO TEMPLADO ALTA FUERTE SI ) ( NUBLADO CALOR NORMAL DEBIL SI )
8 ( LLUVIA TEMPLADO ALTA FUERTE NO ))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 68 / 133


Arboles de Decisión: CL-ID3 Carga de Archivos

Clase a predecir

I Recuperando la clase a predecir (target):


1 ( defun get-target ( arff )
2 ( r e a d - f r o m - s t rin g
3 ( car
4 ( cdr ( split-se quence : split-s equence
5 #\ Space
6 ( car
7 ( butlast
8 ( spl it-seque nce : sp lit-sequ ence
9 #\ Newline
10 ( trivial-shell : shell-command
11 ( concatenate ’ string
12 " egrep \" @rel | @REL \" "
13 arff ))))))))))

1 CL - USER > ( get - target " tenis . arff ")


2 JUGAR - TENIS
3 11

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 69 / 133


Arboles de Decisión: CL-ID3 Carga de Archivos

Dominios

I Obteniendo el dominio de un atributo:


1 ( defun get-domain ( attribute )
2 ( nth ( position attribute * attributes *)
3 * domains *))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 70 / 133


Arboles de Decisión: CL-ID3 Carga de Archivos

Todo junto

I Leyendo un ARFF:
1 ( defun id3-load ( arff )
2 ( let (( data ( get-data arff ))
3 ( attribs-doms ( g e t - a t t r i b s - d o m s arff )))
4 ( setf * gensym -counter * 1)
5 ( setf * attributes * ( mapcar # ’ car attribs-doms ))
6 ( setf * domains * ( mapcar # ’ cadr attribs-doms ))
7 ( setf * target * ( get-target arff ))
8 ( loop for d in data do
9 ( let (( ej ( gensym " ej " )))
10 ( push ej * examples *)
11 ( loop for attrib in * attributes *
12 as v in d do
13 ( put-value attrib ej v ))))
14 ( format t " Training set initialized " )))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 71 / 133


Arboles de Decisión: CL-ID3 Carga de Archivos

Ejemplo

I Cargando los ejemplos de tenis:


1 CL - USER > ( id3 - load " tenis . arff ")
2 Training set initialized
3 NIL
4 CL - USER > * examples *
5 (#:| ej14 | #:| ej13 | #:| ej12 | #:| ej11 | #:| ej10 | #:| ej9 | #:| ej8 | #:| ej7 |
6 #:| ej6 | #:| ej5 | #:| ej4 | #:| ej3 | #:| ej2 | #:| ej1 |)
7 CL - USER > * attributes *
8 ( CIELO TEMPERATURA HUMEDAD VIENTO JUGAR - TENIS )
9 CL - USER > * domains *
10 (( SOLEADO NUBLADO LLUVIA ) ( CALOR TEMPLADO FRIO ) ( ALTA NORMAL )
11 ( DEBIL FUERTE ) ( SI NO ))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 72 / 133


Arboles de Decisión: CL-ID3 Carga de Archivos

Y el reseteo

I Limpiando las variables globales:


1 ( defun id3-reset ()
2 ( setf * examples * nil
3 * target * nil
4 * attributes * nil
5 * domains * nil
6 * trace * nil
7 * root * nil )
8 ( format t " The ID3 setting has been reset . " ))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 73 / 133


Arboles de Decisión: CL-ID3 Mejoras

Definición de un sistema ASDF: cl-id3.asd

1 ( asdf : defsystem : cl-id3


2 : depends-on (: split-sequence )
3 : components ((: file " cl-id3-package " )
4 (: file " cl -id3-algor ithm "
5 : depends-on ( " cl-id3-package " ))
6 (: file " cl-id3-load "
7 : depends-on ( " cl-id3-package "
8 " cl-id3-algorithm " ))
9 (: file " cl -id3-classify "
10 : depends-on ( " cl-id3-package "
11 " cl-id3-algorithm "
12 " cl-id3-load " ))
13 (: file " c l - i d 3 - c r o s s - v a l i d a t i o n "
14 : depends-on ( " cl-id3-package "
15 " cl-id3-algorithm "
16 " cl-id3-load "
17 " cl-id3-classify " ))
18 (: file " cl-id3-gui "
19 : depends-on ( " cl-id3-package "
20 " cl-id3-algorithm "
21 " cl-id3-load "
22 " cl-id3-classify "
23 " c l - i d 3 - c r o s s - v a l i d a t i o n " ))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 74 / 133


Arboles de Decisión: CL-ID3 Mejoras

Definiendo un paquete: cl-id3-package

1 ( defpackage : cl-id3
2 (: use : cl : capi : split-s equence )
3 (: export : load-file
4 : induce
5 : print-tree
6 : classify
7 : classify-new-instance
8 : c r o s s - v a l i d a t io n
9 : gui ))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 75 / 133


Arboles de Decisión: CL-ID3 Mejoras

Leyendo archivos: cl-id3-load

1 ( in-package : cl-id3 )
2
3 ; ;; A u x i l i a r f u n c t i o n s
4
5 ( defun r e a d - l i n e s - f r o m - f i l e ( file )
6 " It reads the FILE into a list of strings "
7 ( remove-if ( lambda ( x ) ( equal x " " ))
8 ( wit h-open-f ile ( in file )
9 ( loop for line = ( read-line in nil ’ end )
10 until ( eq line ’ end ) collect line ))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 76 / 133


Arboles de Decisión: CL-ID3 Mejoras

Portabilidad: Bye, bye grep

1 ( defun arff-get-data ( lines )


2 " It extracts the value for * data * from the lines of a ARFF file "
3 ( mapcar # ’( lambda ( x )
4 ( mapcar # ’ r e a d - f r o m - s t r i n g
5 ( spl it-seque nce #\ , x )))
6 ( remove-if
7 ( lambda ( x ) ( string-equal " @ " ( subseq x 0 1)))
8 lines )))
9
10 ( defun csv-get-data ( lines )
11 " It extracts the value for * data * from the lines of a CSV file "
12 ( mapcar # ’( lambda ( x )
13 ( mapcar # ’ r e a d - f r o m - s t r i n g
14 ( spl it-seque nce #\ , x ))) ( cdr lines )))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 77 / 133


Arboles de Decisión: CL-ID3 Mejoras

Ejemplo:

I Ejecutando arff-get-data (más cajitas):


1 CL - ID3 > ( arff - get - data ( read - lines - from - file " tenis . arff "))
2 (( SOLEADO CALOR ALTA DEBIL NO ) ( SOLEADO CALOR ALTA FUERTE NO ) ( NUBLADO
3 CALOR ALTA DEBIL SI ) ( LLUVIA TEMPLADO ALTA DEBIL SI ) ( LLUVIA FRIO
4 NORMAL DEBIL SI ) ( LLUVIA FRIO NORMAL FUERTE NO ) ( NUBLADO FRIO NORMAL
5 FUERTE SI ) ( SOLEADO TEMPLADO ALTA DEBIL NO ) ( SOLEADO FRIO NORMAL DEBIL
6 SI ) ( LLUVIA TEMPLADO NORMAL DEBIL SI ) ( SOLEADO TEMPLADO NORMAL FUERTE
7 SI ) ( NUBLADO TEMPLADO ALTA FUERTE SI ) ( NUBLADO CALOR NORMAL DEBIL SI )
8 ( LLUVIA TEMPLADO ALTA FUERTE NO ))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 78 / 133


Arboles de Decisión: CL-ID3 Mejoras

Load
1 ( defun load-file ( file )
2 " It initializes the learning setting from FILE "
3 ( labels (( get-examples ( data )
4 ( loop for d in data do
5 ( let (( ej ( gensym " ej " )))
6 ( setf * examples * ( cons ej * examples *))
7 ( loop for attrib in * attributes *
8 as v in d do
9 ( put-value attrib ej v ))))))
10 ( if ( probe-file file )
11 ( let (( file-ext ( car ( last ( split-sequence #\. file ))))
12 ( file-lines ( r e a d - l i n e s - f r o m - f i l e file )))
13 ( reset )
14 ( cond
15 (( equal file-ext " arff " )
16 ( let (( attribs-doms ( a r f f - g e t - a t t r i b s - d o m s file-lines )))
17 ( setf * attributes * ( mapcar # ’ car attribs-doms ))
18 ( setf * domains * ( mapcar # ’ cadr attribs-doms ))
19 ( setf * target * ( arff-get-target file-lines ))
20 ( setf * data * ( arff-get-data file-lines ))
21 ( get-examples * data *)
22 ( format t " Training setting initialized after ~ s.~ %" file )))
23 (( equal file-ext " csv " )
24 ( let (( attribs-doms ( c s v - g e t - a t t r i b s - d o m s file-lines )))
25 ( setf * attributes * ( mapcar # ’ car attribs-doms ))
26 ...
27 ( t ( error " File ’ s ~ s extension can not be determined . " file ))))
28 ( error " File ~ s does not exist .~ %" file ))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 79 / 133


Arboles de Decisión: CL-ID3 Mejoras

Ejemplo

I Cargando un archivo:
1 CL - ID3 > ( load - file " tenis . arff ")
2 The ID3 setting has been reset .
3 Training setting initialized after " tenis . arff ".
4 NIL
5 CL - ID3 > * target *
6 JUGAR - TENIS
7 CL - ID3 > * attributes *
8 ( CIELO TEMPERATURA HUMEDAD VIENTO JUGAR - TENIS )
9 CL - ID3 > * examples *
10 (#:| ej14 | #:| ej13 | #:| ej12 | #:| ej11 | #:| ej10 | #:| ej9 | #:| ej8 |
11 #:| ej7 | #:| ej6 | #:| ej5 | #:| ej4 | #:| ej3 | #:| ej2 | #:| ej1 |)

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 80 / 133


Arboles de Decisión: CL-ID3 ID3

Algoritmo principal

1 ( defun id3 ( examples attribs )


2 " It induces a decision tree runing ID3 over EXAMPLES and ATTRIBS ) "
3 ( let (( c lass-by- default ( get-value * target * ( car examples ))))
4 ( cond
5 ; ; Stop criteria
6 (( s a m e -c l a ss - va l u e- p * target *
7 clas s-by-default
8 examples ) class-by-default )
9 ; ; Failure
10 (( null attribs ) ( t a r g e t - m o s t - c o m m o n - v a l u e examples ))
11 ; ; R e c u r s i v e call
12 ( t ( let * (( partition ( best-partition attribs examples ))
13 ( node ( first partition )))
14 ( cons node
15 ( loop for branch in ( cdr partition ) collect
16 ( list ( first branch )
17 ( id3 ( cdr branch )
18 ( remove node attribs ))))))))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 81 / 133


Arboles de Decisión: CL-ID3 ID3

¿Todos somos de la misma clase?

I Criterio terminal:
1 ( defun s a m e - c l a s s - v a l u e - p ( attrib value examples )
2 " Do all EXAMPLES have the same VALUE for a given ATTRIB ? "
3 ( every # ’( lambda ( e )
4 ( eq value
5 ( get-value attrib e )))
6 examples ))

I Ejemplo:
1 CL - ID3 > ( same - class - value - p * target * ’ si * examples *)
2 NIL
3 CL - ID3 > ( same - class - value - p * target * ’ no * examples *)
4 NIL

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 82 / 133


Arboles de Decisión: CL-ID3 ID3

Valor mayoritario de Clase

1 ( defun t a r g e t - m o s t - c o m m o n - v a l u e ( examples )
2 " It gets the most common value for * target * in EXAMPLES "
3 ( let (( domain ( get-domain * target *))
4 ( vals ( mapcar # ’( lambda ( x ) ( get-value * target * x ))
5 examples )))
6 ( caar ( sort ( loop for v in domain collect
7 ( list v ( count v vals )))
8 # ’( lambda ( x y ) ( >= ( cadr x )
9 ( cadr y )))))))

1 CL - ID3 > ( target - most - common - value * examples *)


2 SI

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 83 / 133


Arboles de Decisión: CL-ID3 ID3

Partición

1 ( defun get-partition ( attrib examples )


2 " It gets the partition induced by ATTRIB in EXAMPLES "
3 ( let ( result vlist v )
4 ( loop for e in examples do
5 ( setq v ( get-value attrib e ))
6 ( if ( setq vlist ( assoc v result ))
7 ; ;; value v existed , the example e is added
8 ; ;; to the cdr of vlist
9 ( rplacd vlist ( cons e ( cdr vlist )))
10 ; ;; else a pair ( v e ) is added to result
11 ( setq result ( cons ( list v e ) result ))))
12 ( cons attrib result )))

1 CL - ID3 > ( get - partition ’ cielo * examples *)


2 ( CIELO ( SOLEADO #:| ej1 | #:| ej2 | #:| ej8 | #:| ej9 | #:| ej11 |)
3 ( NUBLADO #:| ej3 | #:| ej7 | #:| ej12 | #:| ej13 |)
4 ( LLUVIA #:| ej4 | #:| ej5 | #:| ej6 | #:| ej10 | #:| ej14 |))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 84 / 133


Arboles de Decisión: CL-ID3 ID3

Entropía

1 ( defun entropy ( examples attrib )


2 " It computes the entropy of EXAMPLES with respect to an ATTRIB "
3 ( let (( partition ( get-partition attrib examples ))
4 ( n u m b e r - o f - e x a m p l e s ( length examples )))
5 ( apply # ’+
6 ( mapcar # ’( lambda ( part )
7 ( let * (( size-part ( count-if # ’ atom
8 ( cdr part )))
9 ( proportion
10 ( if ( eq size-part 0) 0
11 (/ size-part
12 n u m b e r - o f - e x a m p l e s ))))
13 (* -1.0 proportion ( log proportion 2))))
14 ( cdr partition )))))

1 CL - ID3 > ( entropy * examples * ’ jugar - tenis )


2 0.9402859

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 85 / 133


Arboles de Decisión: CL-ID3 ID3

Ganancia de Información

1 ( defun i n fo r m a t i o n - g a i n ( examples attribute )


2 " It computes i n f o r m a t i o n - g a in for an ATTRIBUTE in EXAMPLES "
3 ( let (( parts ( get-partition attribute examples ))
4 ( no-examples ( count-if # ’ atom examples )))
5 (- ( entropy examples * target *)
6 ( apply # ’+
7 ( mapcar
8 # ’( lambda ( part )
9 ( let * (( size-part ( count-if # ’ atom
10 ( cdr part )))
11 ( proportion ( if ( eq size-part 0) 0
12 (/ size-part
13 no-examples ))))
14 (* proportion ( entropy ( cdr part ) * target *))))
15 ( cdr parts ))))))

1 CL - ID3 > ( information - gain * examples * ’ cielo )


2 0.2467497

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 86 / 133


Arboles de Decisión: CL-ID3 ID3

Mejor partición

1 ( defun be st-partition ( attributes examples )


2 " It computes one of the best partitions induced by ATTRIBUTES over EXAMPLES "
3 ( let * (( info-gains
4 ( loop for attrib in attributes collect
5 ( let (( ig ( informatio n-gain examples attrib ))
6 ( p ( get-partition attrib examples )))
7 ( when * trace *
8 ( format t " Partici ó n inducida por el atributo ~ s :~ %~ s~ %"
9 attrib p )
10 ( format t " Ganancia de informaci ó n : ~ s~ %"
11 ig ))
12 ( list ig p ))))
13 ( best ( cadar ( sort info-gains # ’( lambda ( x y ) ( > ( car x ) ( car y )))))))
14 ( when * trace * ( format t " Best partition : ~ s ~ %-------------~ % " best ))
15 best ))

1 CL - ID3 > ( best - partition ( remove * target * * attributes *)


2 * examples *)
3 ( CIELO ( SOLEADO #:| ej1 | #:| ej2 | #:| ej8 | #:| ej9 | #:| ej11 |)
4 ( NUBLADO #:| ej3 | #:| ej7 | #:| ej12 | #:| ej13 |)
5 ( LLUVIA #:| ej4 | #:| ej5 | #:| ej6 | #:| ej10 | #:| ej14 |))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 87 / 133


Arboles de Decisión: CL-ID3 ID3

Induciendo un árbol

1 ( defun induce (& optional ( examples * examples *))


2 " It induces the decision tree using learning setting "
3 ( when ( not ( member * target * * attributes *))
4 ( error " The target is defined incorrectly : Maybe Weka modified
5 ( id3 examples ( remove * target * * attributes *)))

1 CL - ID3 > ( induce )


2 ( CIELO ( SOLEADO ( HUMEDAD ( NORMAL SI ) ( ALTA NO )))
3 ( NUBLADO SI ) ( LLUVIA ( VIENTO ( FUERTE NO ) ( DEBIL SI ))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 88 / 133


Arboles de Decisión: CL-ID3 ID3

Y con print-tree

1 CL - ID3 > ( print - tree ( induce ))


2 CIELO
3 - SOLEADO
4 HUMEDAD
5 - NORMAL -> SI
6 - ALTA -> NO
7 - NUBLADO -> SI
8 - LLUVIA
9 VIENTO
10 - FUERTE -> NO
11 - DEBIL -> SI
12 NIL

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 89 / 133


Arboles de Decisión: CL-ID3 ID3

Cargando el sistema ASDF

I Hemos especificado como compilar cl-id3 como un sistema ASDF.


I La forma más fácil de cargar el sistema es creando una liga simbólica
a este archivo en el directorio quicklisp:
1 > ln -s ~/ Documents / cursos / pia / codigo / lisp / cap07 / cl - id3 / cl - id3 . asd cl - id3 . asd

I Podemos entonces cargar el sistema desde lisp:


1 CL-USER > ( asdf : operate ’ asdf : load-op ’ cl-id3 )

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 90 / 133


Arboles de Decisión: CL-ID3 ID3

Prueba

1 CL-USER > ( cl-id3 : load-file " tenis . csv " )


2 The ID3 setting has been reset .
3 Training set initialized after " tenis . csv " .
4 NIL
5 CL-USER > cl-id3 ::* attributes *
6 ( CIELO HUMEDAD TEMPERATURA VIENTO JUGAR-TENIS )
7 CL-USER > ( cl-id3 : print-tree ( cl-id3 : induce ))
8 CIELO
9 - SOLEADO
10 TEMPERATURA
11 - NORMAL - > SI
12 - ALTA - > NO
13 - NUBLADO - > SI
14 - LLUVIA
15 VIENTO
16 - FUERTE - > NO
17 - DEBIL - > SI
18 NIL

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 91 / 133


Arboles de Decisión: CL-ID3 GUI

La interfaz gráfica del sistema

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 92 / 133


Arboles de Decisión: CL-ID3 GUI

capi:contain

I Podemos probar codigo de la GUI como sigue:


1 CL - USER > ( capi : contain ( capi : display - message
2 " CL - ID3 ~ %~ % Universidad Veracruzana ~ % Departamento de Inteligenci
3 Artificial ~ % Sebasti á n Camacho No 5~ % Xalapa , Ver . ,
4 M é xico 91000~ % http :// www . uv . mx / aguerra ~ % aguerra@uv . mx "))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 93 / 133


Arboles de Decisión: CL-ID3 GUI

Variables globales (habilitar menus)

1 ( defvar * examples-on * nil " t enables the examples menu " )


2 ( defvar * attributes-on * nil " t enables the attributes menu " )
3 ( defvar * induce-on * nil " t enables the induce menu " )
4 ( defvar * classify-on * nil " t enables the classify menu " )
5 ( defvar * c r o s s - v a l i d a t i o n - o n * nil " t enables the c r o s s - va l i d a t i o n m

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 94 / 133


Arboles de Decisión: CL-ID3 GUI

Ventana principal: paneles de texto

1 ( d e f i n e - i n t erface cl-id3-gui ()
2 ()
3 (: panes
4 ( sour ce-id-pane text-input-pane
5 : accessor source-id-pane
6 : text " "
7 : enabled nil )
8 ( n u m - a t t r i b u t e s - p a n e text-input-pane
9 : accessor n u m - a t t r i b u t e s - p a n e
10 : text " "
11 : enabled nil )
12 ( n u m - e x a mpl es -pa ne text- input-pane
13 : accessor n um -ex am ple s- pan e
14 : text " "
15 : enabled nil )
16 ( class-pane text-input-p ane
17 : accessor class-pane
18 : text " "
19 : enabled nil )
20 ( e ff i ci ency-pane text-input-pane
21 : text " "
22 : enabled nil )
23 ( k-value-pane text-input-pane
24 : text " 0 " )...

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 95 / 133


Arboles de Decisión: CL-ID3 GUI

Ventana principal: Otros paneles

1 ...
2 ( tree-pane graph-pane
3 : title " Decision Tree "
4 : title-position : frame
5 : c hi ldr en -fu nc tio n ’ node-children
6 : ed g e- p a ne - fu n c ti o n
7 # ’( lambda ( self from to )
8 ( declare ( ignore self from ))
9 ( make-instance
10 ’ labelled-arrow-pinboard-object
11 : data ( princ-to-string ( node-from-label to ))))
12 : v is ibl e- min -w idt h 450
13 : layout-funct ion : top-down )
14 ( state-pane title-pane
15 : accessor state-pane
16 : text " Welcome to CL-ID3 . " )) ...

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 96 / 133


Arboles de Decisión: CL-ID3 GUI

Ventana principal: Menus 1

1 ...
2 (: menus
3 ( file-menu
4 " File "
5 (( " Open " : se l ec t i on - ca l l ba c k ’ gui-load-file
6 : accelerator #\ o )
7 ( " Quit " : s el e ct i o n- c al l b ac k ’ gui-quit
8 : accelerator #\ q )))
9 ( view-menu
10 " View "
11 (( " Attributes " : s e l ec t i o n - ca l lb a ck ’ g u i - v i e w - a t t r i b u t e s
12 : accelerator #\ a
13 : enabled -function # ’( lambda ( menu )
14 ( declare ( ignore menu )) * attributes-on *))
15 ( " Examples " : s el e c ti o n- c a ll b ac k ’ gu i- vie w- exa mp les
16 : accelerator #\ e
17 : enabled-f unction # ’( lambda ( menu )
18 ( declare ( ignore menu )) * examples-on *))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 97 / 133


Arboles de Decisión: CL-ID3 GUI

Ventana principal: Menus 2

1 ...
2 ( id3-menu
3 " id3 "
4 (( " Induce " : s e le c t io n -c a ll b a ck ’ gui-induce
5 : accelerator #\ i
6 : en abled-function # ’( lambda ( menu )
7 ( declare ( ignore menu )) * induce-on *))
8 ( " Classify " : s el e c ti o n- c a ll b ac k ’ gui-classify
9 : accelerator #\ k
10 : enabled-f unction # ’( lambda ( menu )
11 ( declare ( ignore menu )) * classify-on *))
12 ( " C r o ss-validati on " : s e l ec t io n - ca l lb a c k ’ g u i - c r o s s - v a l i d a t i o n
13 : accelerator #\ c
14 : e nabled-function # ’( lambda ( menu )
15 ( declare ( ignore menu )) * c r o s s - v a l i d a t i o n -
16 ( help-menu
17 " Help "
18 (( " About " : s el e ct i o n- c a l l b ac k ’ gui-about ))))
19 (: menu-bar file-menu view-menu id3-menu help-menu )

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 98 / 133


Arboles de Decisión: CL-ID3 GUI

Ventana principal: Layouts

1 (: layouts
2 ( main-layout column-layout ’( panes state-pane ))
3 ( panes row-layout ’( info-pane tree-pane ))
4 ( titles column-layout ’())
5 ( matrix-pane row-layout ’( titles confusion )
6 : title " Confusion Matrix " : x-gap ’10 : y-gap ’30
7 : title-position : frame : vi sib le -mi n- wid th ’200)
8 ( confusion grid-layout ’())
9 ( info-pane column-layout ’( setting-pane id3-pane matrix-pane ))
10 ( setting-pane grid-layout
11 ’( " Source File " source-id-pane
12 " No . Attributes " n u m - a t t r i b u t e s - p a n e
13 " No . Examples " num -e xam pl es- pa ne
14 " Class " class-pane )
15 : y-adjust : center
16 : title " Trainning Set "
17 : title-pos ition : frame : columns ’2)
18 ( id3-pane grid-layout ’( " K value " k-value-pane
19 " Efficiency " efficiency-pane )
20 : y-adjust : center
21 : title " Cross Validation "
22 : title-positio n : frame : columns ’2))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 99 / 133


Arboles de Decisión: CL-ID3 GUI

Ventana principal: datos iniciales

1 (: d ef a u l t - i n i t a r g s
2 : title " CL-ID3 "
3 : v i s i b l e - m i n - w i d t h 840
4 : v i s i b l e - m i n - h e i g h t 600))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 100 / 133
Arboles de Decisión: CL-ID3 GUI

Llamadas: gui-load-file

1 ( defun gui-load-file ( data interface )


2 ( declare ( ignore data ))
3 ( let (( file ( prompt-for-f ile
4 nil
5 : filter " *. arff "
6 : filters ’( " WEKA files " " *. arff "
7 " Comme Separated Values " " *. csv " ))))
8 ( when file
9 ( let * (( path ( princ-to-string file ))
10 ( setting ( car ( last ( split-sequence #\/ path )))))
11 ( load-file path )
12 ( setf ( t e x t - i n p u t - p a n e - t e x t ( source-id-pane interface ))
13 setting )
14 ( setf ( t e x t - i n p u t - p a n e - t e x t ( n u m - a t t r i b u t e s - p a n e interface ))
15 ( princ-to-str ing ( length * attributes *)))
16 ( setf ( t e x t - i n p u t - p a n e - t e x t ( n um- ex amp le s-p an e interface ))
17 ( princ-to-str ing ( length * examples *)))
18 ( setf ( t e x t - i n p u t - p a n e - t e x t ( class-pane interface ))
19 ( princ-to-string * target *))
20 ( setf ( title-pane-text ( state-pane interface ))
21 ( format nil " The setting ~ s has been loaded "
22 path ))
23 ( setf * examples-on * t * attributes-on * t * induce-on * t )))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 101 / 133
Arboles de Decisión: CL-ID3 GUI

Llamadas: gui-quit

1 ( defun gui-quit ( data interface )


2 ( declare ( ignore data ))
3 ( qui t-interf ace interface ))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 102 / 133
Arboles de Decisión: CL-ID3 GUI

Llamadas: gui-view-attributes 1

1 ( defun g u i - v i e w - a t t r i b u t e s ( data interface )


2 ( declare ( ignore data interface ))
3 ( let * (( ma x-l en gth -a ttr ib ( apply # ’ max
4 ( mapcar # ’ length
5 ( mapcar # ’ princ-to-string
6 * attributes *))))
7 ( pane-total-width ( list ’ character
8 (* ma x-l en gth -a ttr ib
9 (+ 1 ( length * attributes *))))))...

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 103 / 133
Arboles de Decisión: CL-ID3 GUI

Llamadas: gui-view-attributes 2

1 ( d e f i n e-in terface gui-domains () ()


2 (: panes
3 ( a ttributes-pane m u l t i - c o l u m n - l i s t - p a n e l
4 : columns ’((: title " Attrib / Class "
5 : adjust : left
6 : v is ibl e- min -w idt h ( character 10))
7 (: title " Attributes " : adjust : left
8 : v is ibl e- min -w idt h ( character 20))
9 (: title " Domains " : adjust : left
10 : v is ibl e- min -w idt h ( character 20)))
11 : items ( loop for a in * attributes * collect
12 ( list ( if ( eql * target * a ) ’c ’a )
13 a
14 ( get-domain a )))
15 : v is ibl e- min -w idt h pane-total-widt h
16 : vi s i bl e -m i n -h e ig h t : text-height
17 : ve rtical-scroll t )
18 ( button-pane push-button
19 : text " Close "
20 : callback ’ gui-quit ))
21 (: d e fa ult-initargs
22 : title " CL-ID3 : attributes " ))
23 ( display ( make-instance ’ gui-domains ))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 104 / 133
Arboles de Decisión: CL-ID3 GUI

Dibujando el árbol: listas → nodos

1 ( defstruct node
2 ( inf nil )
3 ( sub-trees nil )
4 ( from-label nil ))
5
6 ( defun make-tree ( tree-as-lst )
7 " It makes a tree of nodes with TREE-AS-LST "
8 ( make-node : inf ( root tree-as-lst )
9 : sub-trees ( ma ke-sub-trees ( children tree-as-lst ))))
10
11 ( defun ma ke-sub-trees ( children-lst )
12 " It makes de subtrees list of a tree with CHILDREN "
13 ( loop for child in children-lst collect
14 ( let (( sub-tree ( second child ))
15 ( label ( first child )))
16 ( if ( leaf-p sub-tree )
17 ( make-node : inf sub-tree
18 : sub-trees nil
19 : from-label label )
20 ( make-node : inf ( root sub-tree )
21 : sub-trees ( make-sub-trees ( children sub-tree ))
22 : from-label label )))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 105 / 133
Arboles de Decisión: CL-ID3 GUI

Dibujando el árbol

1 ( defmethod print-object (( n node ) stream )


2 ( format stream " ~ s " ( node-inf n )))
3
4 ( defun display-tree ( root interface )
5 " It displays the tree with ROOT in its pane in INTERFACE "
6 ( with-slots ( tree-pane ) interface
7 ( setf ( graph-pan e-roots tree-pane )
8 ( list root ))
9 ( m a p - p a ne- ch ild re n tree-pane ; ;; redraw panes c o r r e c t i n g x / y - a d j u s t m e n t s
10 ( lambda ( item )
11 ( u p d a t e - p i n b o a r d - o b j e c t item )))))
12
13 ( defun node-children ( node )
14 " It gets the children of NODE to be displayed "
15 ( let (( children ( node-sub-trees node )))
16 ( when children
17 ( if ( leaf-p children ) ( list children )
18 children ))))
19
20 ; ;; induce
21
22 ( defun gui-induce ( data interface )
23 " It induces the decisicion tree and displays it in the INTERFACE "
24 ( declare ( ignore data ))
25 ( setf * current-tree * ( induce ))
26 ( display-tree ( make-tree * current-tree *)
27 interface ))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 106 / 133
Arboles de Decisión: CL-ID3 GUI

Función principal

1 ( defun gui ()
2 ( reset )
3 ( display ( make-instance ’ cl-id3-gui )))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 107 / 133
Filtrado colaborativo Introducción

Amazon, Reddit & Co.

I La idea es usar las preferencias de los usuarios, para dar


recomendaciones a otros usuarios.
I Ejemplo: Amazon, Netflix, iTunes Store, Reddit, etc.

I Seguiremos la presentación de Seagaran [6].

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 108 / 133
Filtrado colaborativo Introducción

Filtrado Colaborativo

I Se trata de encontrar usuarios con gustos afines y usar sus


preferencias para emitir recomendaciones.
I El término fue acuñado en Xerox PARC, ¿Donde más?, en 1992
por Goldberg y col. [1].

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 109 / 133
Filtrado colaborativo Representación

Preferencias

I Asumamos 7 críticos para 5 películas.


I La escala de calificación va de 0 a 5.
Película Rose Seymour Phillips Puig LaSalle Mathews Toby
Lady in Water 2.5 3.0 2.5 - 3.0 3.0 -
Snakes on Plane 3.5 3.5 3.0 3.5 4.0 4.0 4.5
Just my Luck 3.0 1.5 - 3.0 2.0 - -
Superman returns 3.5 5.0 3.5 4.0 3.0 5.0 4.0
The Night Listener 3.0 3.0 4.0 4.5 3.0 3.0 -
You, Me and Dupree 2.5 3.5 - 2.5 2.0 3.5 3.5

I Observen que no todos los críticos revisan todas la películas.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 110 / 133
Filtrado colaborativo Representación

Representando preferencias

I Usaremos listas de propiedades:


1 ( defvar * critics *
2 ’((: critic " Lisa Rose "
3 : critics (( " Lady in the Water " 2.5)
4 ( " Snakes on a Plane " 3.5)
5 ( " Just My Luck " 3.0)
6 ( " Superman Returns " 3.5)
7 ( " You , Me and Dupree " 2.5)
8 ( " The Night Listener " 3.0)))
9 (: critic " Gene Seymour "
10 : critics (( " Lady in the Water " 3.0)
11 ( " Snakes on a Plane " 3.5)
12 ( " Just My Luck " 1.5)
13 ( " Superman Returns " 5.0)
14 ( " The Night Listener " 3.0)
15 ( " You , Me and Dupree " 3.5)))
16 ...)

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 111 / 133
Filtrado colaborativo Representación

Funciones de acceso

1 ( defun get-critic ( critic )


2 ( find critic * critics *
3 : test # ’( lambda ( name reg )
4 ( string = name ( getf reg : critic )))))
5
6 ( defun g et -f i lm -r at i ng ( critic film )
7 ( cadr ( find film ( getf ( get-critic critic ) : critics )
8 : test # ’( lambda ( film reg )
9 ( string = film ( car reg ))))))
10
11 ( defun g e t - f i l m s - r a t e d - b y ( person )
12 ( mapcar # ’ car ( fourth ( get-critic person ))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 112 / 133
Filtrado colaborativo Representación

Ejemplos de uso

1 CL-USER > ( get-critic " Toby " )


2 (: CRITIC " Toby " : CRITICS (( " Snakes on a Plane " 4.5) ( " Superman Returns " 4.0)
3 ( " You , Me and Dupree " 1.0)))
4 CL-USER > ( get-film-rating " Toby " " Superman Returns " )
5 4.0
6 CL-USER > ( g e t -f i lm s - ra t ed - b y " Toby " )
7 ( " Snakes on a Plane " " Superman Returns " " You , Me and Dupree " )

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 113 / 133
Filtrado colaborativo Representación

Productos en común

1 ( defun shared-items ( critic1 critic2 )


2 ( intersection ( g e t - f i l m s - r a t e d - b y critic1 )
3 ( g e t - f i l m s - r a t e d - b y critic2 )
4 : test # ’ string = ))

1 CL - USER > ( shared - items " Toby " " Lisa Rose ")
2 (" Snakes on a Plane " " Superman Returns " " You , Me and Dupree ")

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 114 / 133
Filtrado colaborativo Usuarios similares

Distancia Euclidiana y Espacio de Preferencias

q
I dist((x1 , y1 )(x2 , y2 )) = (x1 − x2 )2 + (y1 − y2 )2

I Normalizaremos la distancia en [0, . . . , 1].

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 115 / 133
Filtrado colaborativo Usuarios similares

Computando

1 ( defun sim-euclidean ( person1 person2 )


2 " 1 means identical preferences , 0 the opposite "
3 ( let (( shared ( shared-items person1 person2 )))
4 ( if ( null shared )
5 0
6 (/ 1
7 (+ 1
8 ( sqrt ( loop for film in shared sum
9 ( sqr (- ( get-film-rating person1 film )
10 ( get-film-rating person2 film ))))))))))
11
12 ( defun sqr ( x ) (* x x ))

1 CL - USER > ( sim - euclidean " Lisa Rose " " Gene Seymour ")
2 0.29429805
3 CL - USER > ( sim - euclidean " Lisa Rose " " Claudia Puig ")
4 0.38742587

Puig tiene preferencias más cercanas a las de Rose que Seymour.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 116 / 133
2
Filtrado colaborativo Usuarios similares Just My Luck

Correlación de Pearson 1 2 3 4 5
Mick LaSalle

Figure 2-2. Comparing two movie critics on a scatter plot

You can also see a straight line on the chart. This is called the best-fit line because
comes as close to all the items on the chart as possible. If the two critics had ident
cal ratings for every movie, this line would be diagonal and would touch every item
yi in the chart, giving a perfect correlation score of 1. In the case illustrated, the critic
P P P
n xi yi − xi
I rxy = √ P P 2√ P disagree on a few movies, so the correlation score is about 0.4. Figure 2-3 shows a
P
exampleyof)a2 much higher correlation, one of about 0.75.
n xi2 −( xi ) n y 2 −(
i i

Gene Seymour Lisa Rose

5 Superman 5

4 4
Dupree Snakes Snakes Superman

3 Lady 3 Night Listener


Night Listener
Dupree Lady

2 2
Just My Luck

1 1

Mick LaSalle Jack Matthews


1 2 3 4 5 1 2 3 4 5

Figure 2-2. Comparing two movie critics on a scatter plot Figure 2-3. Two critics with a high correlation score
I Resuelve corrimientos en la escala.
You can also see a straight line on the chart. This is called the best-fit line because it
comes as close to all the items on the chart as possible. If the two critics had identi-
cal ratings for every movie, this line would be diagonal and would touch every item
in the chart, giving a perfect correlation score of 1. In the case illustrated, the critics
12 | Chapter 2: Making Recommendations
disagree on a few movies, so the correlation score is about 0.4. Figure 2-3 shows an
example of a much higher correlation, one of about 0.75.

Dr. Alejandro Lisa Rose


Guerra-Hernández (UV) Programación para la IA MIA 2020 117 / 133
Filtrado colaborativo Usuarios similares

Computando

1 ( defun sim-pearson ( person1 person2 )


2 " 1 means identical preferences , -1 the opposite "
3 ( let (( si ( shared-items person1 person2 )))
4 ( if ( null si )
5 0
6 ( let * (( n ( length si ))
7 ( prefs1 ( loop for film in si collect
8 ( get-film-rating person1 film )))
9 ( prefs2 ( loop for film in si collect
10 ( get-film-rating person2 film )))
11 ( sum1 ( sum prefs1 ))
12 ( sum2 ( sum prefs2 ))
13 ( sum1sq ( sum ( mapcar # ’ sqr prefs1 )))
14 ( sum2sq ( sum ( mapcar # ’ sqr prefs2 )))
15 ( psum ( sum ( mapcar # ’( lambda ( x y ) (* x y )) prefs1 prefs2 )))
16 ( num (- psum (/ (* sum1 sum2 ) n )))
17 ( den ( sqrt (* (- sum1sq (/ ( sqr sum1 ) n ))
18 (- sum2sq (/ ( sqr sum2 ) n ))))))
19 ( if ( zerop den )
20 1
21 (/ num den ))))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 118 / 133
Filtrado colaborativo Usuarios similares

Ejemplos

1 CL - USER > ( sim - pearson " Lisa Rose " " Gene Seymour ")
2 0.39605904
3 CL - USER > ( sim - pearson " Mick LaSalle " " Gene Seymour ")
4 0.4117648
5 CL - USER > ( sim - pearson " Lisa Rose " " Jack Matthews ")
6 0.74701745

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 119 / 133
Filtrado colaborativo Usuarios similares

Y el top de los críticos es...

1 ( defun top-matches ( person & optional ( n 5) ( sim # ’ sim-pearson ))


2 ( subseq ( sort ( mapcar # ’( lambda ( c )
3 ( list c ( funcall sim person c )))
4 ( g e t - o t h e r - c r i t i c s person ))
5 # ’( lambda ( x y ) ( > ( cadr x ) ( cadr y ))))
6 0 n ))
7
8 ( defun g e t - o t h e r - c r i t i c s ( critic )
9 ( remove critic
10 ( mapcar # ’( lambda ( x ) ( getf x : critic ))
11 * critics *)
12 : test # ’ string =))

1 CL - USER > ( top - matches " Toby " 3)


2 ((" Lisa Rose " 0.9912409) (" Mick LaSalle " 0.92447347)
3 (" Claudia Puig " 0.8934049))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 120 / 133
Filtrado colaborativo Recomendaciones

Emitiendo recomendaciones

1 ( defun g e t - r e c o m m e n d a t i o n s ( person & optional ( similarity # ’ sim-pearson ))


2 ( let * (( other-critics ( g et -ot he r-c ri tic s person ))
3 ( films-not-seen ( set-difference
4 ( reduce # ’( lambda ( x y )
5 ( union x y : test # ’ string =))
6 ( mapcar # ’ ge t -f i l ms - ra t e d- b y
7 other-critics ))
8 ( ge t - fi l ms - r at e d- b y person )
9 : test # ’ string =)))
10 ( sort
11 ( loop for film in films-not-seen collect
12 ( let * (( sim-sums 0)
13 ( total ( apply # ’+
14 ( mapcar # ’( lambda ( critic )
15 ( let (( rating
16 ( get-film-rating critic film ))
17 ( sim
18 ( funcall similarity person critic )))
19 ( if rating
20 ( progn
21 ( setf sim-sums (+ sim-sums sim ))
22 (* rating sim ))
23 0)))
24 other-critics ))))
25 ( list (/ total sim-sums ) film )))
26 # ’( lambda ( x y ) ( > ( car x ) ( car y ))))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 121 / 133
Filtrado colaborativo Recomendaciones

Ejemplos

1 CL - USER > ( get - recommendations " Toby ")


2 ((3.1192015 " The Night Listener ") (3.0022347 " Lady in the Water ")
3 (2.5309806 " Just My Luck "))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 122 / 133
Filtrado colaborativo Productos similares

Invirtiendo la lista de preferencias

I Se trata de indexar ahora por película:


1 ( defun transform-prefs ()
2 " Inverts the dictionary * critics * , indexing it by film "
3 ( let * (( critics ( loop for critic in * critics * collect
4 ( getf critic : critic )))
5 ( films ( reduce # ’( lambda ( x y ) ( union x y : test # ’ string =))
6 ( loop for critic in critics collect
7 ( g e t- f i lm s -r a t ed - by critic )))))
8 ( loop for film in films collect
9 ( list : critic film
10 : critics ( remove-if # ’( lambda ( x ) ( null ( cadr x )))
11 ( mapcar # ’( lambda ( c )
12 ( list c ( get-film-rating c film )))
13 critics ))))))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 123 / 133
Filtrado colaborativo Productos similares

Transformación

I El diccionario luce ahora así:


1 CL - USER > ( transform - prefs )
2 ((: CRITIC " Lady in the Water " : CRITICS ((" Lisa Rose " 2.5) (" Gene
3 Seymour " 3.0) (" Michael Phillips " 2.5) (" Mick LaSalle " 3.0) (" Jack
4 Matthews " 3.0))) (: CRITIC " Snakes on a Plane " : CRITICS ((" Lisa Rose "
5 3.5) (" Gene Seymour " 3.5) (" Michael Phillips " 3.0) (" Claudia Puig "
6 3.5) (" Mick LaSalle " 4.0) (" Jack Matthews " 4.0) (" Toby " 4.5)))
7 (: CRITIC " Just My Luck " : CRITICS ((" Lisa Rose " 3.0) (" Gene Seymour "
8 1.5) (" Claudia Puig " 3.0) (" Mick LaSalle " 2.0))) (: CRITIC " Superman
9 Returns " : CRITICS ((" Lisa Rose " 3.5) (" Gene Seymour " 5.0) (" Michael
10 Phillips " 3.5) (" Claudia Puig " 4.0) (" Mick LaSalle " 3.0) (" Jack
11 Matthews " 5.0) (" Toby " 4.0))) (: CRITIC " You , Me and Dupree " : CRITICS
12 ((" Lisa Rose " 2.5) (" Gene Seymour " 3.5) (" Claudia Puig " 2.5) (" Mick
13 LaSalle " 2.0) (" Jack Matthews " 3.5) (" Toby " 1.0))) (: CRITIC " The Night
14 Listener " : CRITICS ((" Lisa Rose " 3.0) (" Gene Seymour " 3.0) (" Michael
15 Phillips " 4.0) (" Claudia Puig " 4.5) (" Mick LaSalle " 3.0) (" Jack
16 Matthews " 3.0))))

I Así podemos usar las funciones ya programadas.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 124 / 133
Filtrado colaborativo Productos similares

Corrida

I ¿Qué películas se parecen a Superman Returns?


1 CL - USER > ( setf * critics * ( transform - prefs ))
2 ((: CRITIC " Lady in the Water " : CRITICS ((" Lisa Rose " 2.5) (" Gene
3 Seymour " 3.0) (" Michael Phillips " 2.5) (" Mick LaSalle " 3.0) (" Jack
4 Matthews " 3.0))) (: CRITIC " Snakes on a Plane " : CRITICS ((" Lisa Rose "
5 3.5) (" Gene Seymour " 3.5) (" Michael Phillips " 3.0) (" Claudia Puig "
6 3.5) (" Mick LaSalle " 4.0) (" Jack Matthews " 4.0) (" Toby " 4.5)))
7 (: CRITIC " Just My Luck " : CRITICS ((" Lisa Rose " 3.0) (" Gene Seymour "
8 1.5) (" Claudia Puig " 3.0) (" Mick LaSalle " 2.0))) (: CRITIC " Superman
9 Returns " : CRITICS ((" Lisa Rose " 3.5) (" Gene Seymour " 5.0) (" Michael
10 Phillips " 3.5) (" Claudia Puig " 4.0) (" Mick LaSalle " 3.0) (" Jack
11 Matthews " 5.0) (" Toby " 4.0))) (: CRITIC " You , Me and Dupree " : CRITICS
12 ((" Lisa Rose " 2.5) (" Gene Seymour " 3.5) (" Claudia Puig " 2.5) (" Mick
13 LaSalle " 2.0) (" Jack Matthews " 3.5) (" Toby " 1.0))) (: CRITIC " The Night
14 Listener " : CRITICS ((" Lisa Rose " 3.0) (" Gene Seymour " 3.0) (" Michael
15 Phillips " 4.0) (" Claudia Puig " 4.5) (" Mick LaSalle " 3.0) (" Jack
16 Matthews " 3.0))))
17 CL - USER > ( top - matches " Superman Returns " 3)
18 ((" You , Me and Dupree " 0.6579514) (" Lady in the Water " 0.48795068)
19 (" Snakes on a Plane " 0.111803316))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 125 / 133
Filtrado colaborativo Productos similares

Otra corrida

I ¿Quién recomienda Just My Luck?


1 CL - USER > ( get - recommendations " Just My Luck ")
2 ((3.8716946 " Jack Matthews ") (2.9610002 " Toby ")
3 (2.2872024 " Michael Phillips "))

I ¿Y The Night Listener?


1 CL - USER > ( get - recommendations " The Night Listener ")
2 ((3.5313943 " Toby "))

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 126 / 133
Filtrado colaborativo Obteniendo datos(

Delicious?

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 127 / 133
Filtrado colaborativo Obteniendo datos(

Delicious API: Update

I Más información: http://delicious.com/developers


I https://api.del.icio.us/v1/posts/update - Verifica cuando un
usuario llevo a cabo su última actualización

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 128 / 133
Filtrado colaborativo Obteniendo datos(

Delicious API: Posts

I https://api.del.icio.us/v1/posts/add? - Agrega un bookmark.


I https://api.del.icio.us/v1/posts/delete? - Borra un bookmark.
I https://api.del.icio.us/v1/posts/get? - Obtiene bookmark de una fecha, o un
objeto específico.
I https://api.del.icio.us/v1/posts/recent? - Obtiene bookmarks recientes.
I https://api.del.icio.us/v1/posts/dates?- Lista las fechas de los bookmarks.
I https://api.del.icio.us/v1/posts/all? - Los bookmarks ordenados por fecha o
rango.
I https://api.del.icio.us/v1/posts/all?hashes - Obtiene cambios.
I https://api.del.icio.us/v1/posts/suggest - Recomendaciones para una URL dada.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 129 / 133
Filtrado colaborativo Obteniendo datos(

Delicious API: Tags y Tag bundles

I https://api.del.icio.us/v1/tags/get - Obtiene todos las etiquetas.


I https://api.del.icio.us/v1/tags/delete? - Borra una etiqueta de todas las entradas.
I https://api.del.icio.us/v1/tags/rename? - Renombra una etiqueta en todas las
entradas.
I https://api.del.icio.us/v1/tags/bundles/all? - Obtiene un paquete de etiquetas.
I https://api.del.icio.us/v1/tags/bundles/set? - Asigna un conjunto de etiquetas a
un paquete.
I https://api.del.icio.us/v1/tags/bundles/delete? - Borra un paquete de etiquetas.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 130 / 133
Filtrado colaborativo Obteniendo datos(

Otro paquete quicklisp: Drakma


1 CL - USER > ( drakma : http - request " https :// api . del . icio . us / v1 / tags / get "
2 : basic - authorization ’(" aguerrahdz " "***"))
3 " <? xml version =\"1.0\" encoding =\" UTF -8\"? > < result code =\" no tags \"/ >"
4 200
5 ((: CONTENT - TYPE . " text / xml ; charset = UTF -8") (: DATE . " Fri , 24 Feb
6 2012 00:57:20 GMT ") (: SERVER . " nginx /1.0.11") (: SET - COOKIE
7 . " deluser =\" U 9 f t o I H 2 x S G g Z d L b y 4 7 b I v Y x H w U X a Z Y k 0 + f m4 G x P6 A 8f b h gP Q D lk /0 S1S +9 VWA / S9TCmsndu8Y2e
8 Domain =. delicious . com ; Max - Age =2592000; Path =/; expires = Sun ,
9 25 - Mar -2012 00:57:20
10 GMT , _user = aguerrahdz %203.2 %20 U 9 f t o I H 2 x S G g Z d L b y 4 7 b I v Y x H w U X a Z Y k 0 + fm 4 Gx P 6 A8 f b hg P QD l k /0 S1S +9 V
11 Domain =. delicious . com ; Max - Age =2592000; Path =/; expires = Sun ,
12 25 - Mar -2012 00:57:20 GMT ") (: CONTENT - LENGTH . "62") (: CONNECTION
13 . " Close "))
14 # < PURI : URI https :// api . del . icio . us / v1 / tags / get >
15 # < FLEXI - STREAMS : FLEXI - IO - STREAM 200 B977F >
16 T
17 " OK "
18
19 CL - USER > ( drakma : http - request
20 " https :// api . del . icio . us / v1 / posts / suggest ? url = http :// yahoo . com "
21 : basic - authorization ’(" aguerrahdz " "***"))
22 " <? xml version =\"1.0\" encoding =\" UTF -8\"? > < suggest > < popular
23 tag =\" email \"/ > < popular tag =\" yahoo \"/ > < popular
24 tag =\" search \"/ > < recommended tag =\" news \"/ > < recommended
25 tag =\" searchengine \"/ > < recommended tag =\" mail \"/ > < recommended
26 tag =\" games \"/ > < recommended tag =\" e - mail \"/ > < recommended
27 tag =\" entertainment \"/ > < recommended tag =\" engine \"/ > </ suggest >"
28 200
29 ...

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 131 / 133
Filtrado colaborativo Obteniendo datos(

En lugar de del.ici.ous

I https://www.themoviedb.org
I http://www.omdbapi.com

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 132 / 133
Filtrado colaborativo Obteniendo datos(

Referencias I
[1] D Goldberg y col. “Using collaborative filtering to weave an information tapestry”. En:
Communications of the ACM 35.12 (1992), págs. 61-71.
[2] A Guerra-Hernández, CR de-la Mora-Basáñez y MA Jiménez-Montaño. “The significance
of nucleotides within DNA codons: a quantitative approach.”. En: Avances en la Ciencia
de la Computación: VI Encuentro Internacional de Computación ENC’05. Ed. por
L Villaseñor-Pineda y A Martínez-García. Sociedad Mexicana de Ciencias de la
Computación (SMCC). Puebla, Pue., México: Benemérita Universidad Autónoma de
Puebla, 2005, págs. 167-169.
[3] DA Mac Dónaill y M Manktelow. “Molecular informatics: quantifying information patterns
in the genetic code”. En: Molecular Simulation 30.5 (2004), págs. 267-272.
[4] T Mitchell. Machine Learning. Computer Science Series. Singapore: McGraw-Hill
International Editions, 1997.
[5] JR Quinlan. “Induction of Decision Trees”. En: Machine Learning 1 (1986), págs. 81-106.
[6] T Seagaran. Programming Collective Intelligence. Sebastopol, CA, USA 95472: O’Reilly
Media, 2008.
[7] P Seibel. Practical Common Lisp. USA: Apress, 2005.

Dr. Alejandro Guerra-Hernández (UV) Programación para la IA MIA 2020 133 / 133

También podría gustarte