Reglas de Asociación

Apriori, Eclat, métricas de interés e interpretación

Author

Dante Conti, Sergi Ramirez, (c) IDEAI

Published

April 27, 2026

Modified

April 27, 2026

1 Introducción

Las reglas de asociación son una familia de técnicas de machine learning no supervisado orientadas a descubrir patrones de coocurrencia en conjuntos de transacciones. Su formulación clásica aparece en el análisis de la cesta de la compra (market basket analysis), aunque su utilidad va mucho más allá del supermercado.

Una regla de asociación tiene la forma:

\[ X \Rightarrow Y \]

donde:

  • \(X\) es el antecedente de la regla, también llamado left-hand side o LHS;
  • \(Y\) es el consecuente de la regla, también llamado right-hand side o RHS;
  • \(X\) e \(Y\) son conjuntos de items;
  • normalmente se exige que \(X \cap Y = \emptyset\).

La lectura informal es:

Si una transacción contiene los items de \(X\), entonces tiende a contener también los items de \(Y\).

Por ejemplo:

\[ \{\text{pan}, \text{mantequilla}\} \Rightarrow \{\text{mermelada}\} \]

se interpreta como:

Las cestas que contienen pan y mantequilla suelen contener también mermelada.

Es importante remarcar desde el principio que una regla de asociación no implica causalidad. Una regla puede ser útil para detectar relaciones, perfiles o recomendaciones, pero no permite afirmar que comprar pan y mantequilla cause la compra de mermelada.

2 Objetivos de aprendizaje

Al finalizar este tema, deberías de ser capaz de:

  • entender qué es una transacción, un item, un itemset y una regla de asociación;
  • diferenciar entre análisis supervisado y no supervisado en el contexto de reglas;
  • calcular e interpretar soporte, confianza, lift, leverage, conviction y coverage;
  • comprender el principio Apriori y su papel en la reducción del espacio de búsqueda;
  • aplicar el algoritmo Apriori en R mediante el paquete arules;
  • aplicar el algoritmo Eclat para extraer itemsets frecuentes;
  • visualizar reglas mediante arulesViz;
  • filtrar, ordenar y podar reglas redundantes;
  • interpretar reglas desde una perspectiva estadística y de negocio;
  • preparar datos transaccionales desde formatos habituales;
  • discretizar variables numéricas para poder usarlas en reglas de asociación;
  • detectar problemas frecuentes: demasiadas reglas, reglas triviales, reglas espurias y sesgo hacia items muy frecuentes.

3 Perspectiva de Data Mining

Las reglas de asociación pertenecen al ámbito del aprendizaje no supervisado porque no parten de una variable respuesta que se quiera predecir. El objetivo no es construir un modelo predictivo \(f(X)\), sino descubrir relaciones internas en los datos.

En Data Mining se usan para:

  • recomendación de productos: clientes que compran A también suelen comprar B;
  • diseño de tienda: colocar juntos productos que tienden a aparecer en la misma cesta;
  • venta cruzada (cross-selling): sugerir complementos relevantes;
  • detección de patrones de comportamiento: navegación web, uso de servicios, rutas de clientes;
  • segmentación descriptiva: identificar combinaciones de características habituales;
  • auditoría o fraude: detectar combinaciones poco habituales o sospechosas;
  • bioinformática: estudiar coocurrencia de atributos, genes o síntomas;
  • educación: analizar patrones de respuestas, errores frecuentes o rutas de aprendizaje.

A diferencia de otros métodos no supervisados como el clustering, las reglas de asociación no agrupan individuos. En lugar de eso, producen una lista de patrones interpretables.

4 Conceptos básicos

4.1 Transacción

Una transacción es un conjunto de eventos o items que aparecen juntos bajo una misma unidad de análisis.

Ejemplos:

  • una cesta de compra;
  • una sesión de navegación web;
  • un conjunto de síntomas de un paciente;
  • las asignaturas matriculadas por un estudiante;
  • las características presentes en un inmueble;
  • las acciones realizadas por un usuario en una aplicación.

Formalmente, si tenemos \(n\) transacciones, podemos escribir:

\[ T = \{t_1, t_2, \dots, t_n\} \]

Cada transacción \(t_i\) es un subconjunto del conjunto total de items \(I\):

\[ t_i \subseteq I \]

4.2 Item

Un item es un elemento individual que puede aparecer o no aparecer en una transacción.

Por ejemplo, en una base de datos de supermercado:

\[ I = \{\text{leche}, \text{pan}, \text{huevos}, \text{cerveza}, \text{pañales}, \dots\} \]

4.3 Itemset

Un itemset es un conjunto de uno o más items.

Ejemplo:

\[ \{\text{leche}, \text{pan}\} \]

Si un itemset tiene \(k\) items, se denomina k-itemset.

  • \(\{\text{leche}\}\) es un 1-itemset.
  • \(\{\text{leche}, \text{pan}\}\) es un 2-itemset.
  • \(\{\text{leche}, \text{pan}, \text{huevos}\}\) es un 3-itemset.

4.4 Regla de asociación

Una regla de asociación divide un itemset en dos partes:

\[ X \Rightarrow Y \]

Ejemplo:

\[ \{\text{pasta}, \text{tomate}\} \Rightarrow \{\text{queso}\} \]

Aquí:

  • \(X = \{\text{pasta}, \text{tomate}\}\) es el antecedente;
  • \(Y = \{\text{queso}\}\) es el consecuente.

La regla no dice que siempre que alguien compre pasta y tomate vaya a comprar queso. Dice que, en los datos observados, la presencia de pasta y tomate se asocia con una mayor frecuencia de queso.

5 Representación de datos transaccionales

Las reglas de asociación trabajan con datos binarios de presencia/ausencia.

Cada transacción se puede representar como una fila y cada item como una columna:

Transacción pan leche huevos queso
T1 1 1 0 0
T2 1 0 1 1
T3 0 1 1 0
T4 1 1 1 1

El valor 1 indica que el item aparece en la transacción. El valor 0 indica que no aparece.

En R, el paquete arules almacena esta información como una matriz dispersa (sparse matrix), mucho más eficiente que una matriz densa cuando hay muchos items y cada transacción contiene solo unos pocos.

6 Métricas de evaluación de reglas

Una vez generadas las reglas, necesitamos criterios para decidir cuáles son relevantes. Las métricas más importantes son:

  • soporte;
  • confianza;
  • lift;
  • leverage;
  • conviction;
  • coverage;
  • count.

6.1 Soporte

El soporte de un itemset \(X\) es la proporción de transacciones que contienen \(X\).

\[ \text{support}(X) = \frac{\#\{t_i: X \subseteq t_i\}}{n} \]

Para una regla \(X \Rightarrow Y\), el soporte se calcula sobre el itemset conjunto \(X \cup Y\):

\[ \text{support}(X \Rightarrow Y) = \text{support}(X \cup Y) \]

6.1.1 Interpretación

Si una regla tiene soporte 0.08, significa que el 8% de todas las transacciones contienen simultáneamente el antecedente y el consecuente.

El soporte responde a la pregunta:

¿En cuántas transacciones aparece este patrón completo?

6.1.2 Advertencia

Un soporte muy alto suele producir reglas demasiado generales. Un soporte muy bajo puede producir reglas interesantes pero poco robustas.

Por ejemplo, una regla con soporte 0.001 puede parecer espectacular, pero si la base de datos tiene 1.000 transacciones, solo aparece en una transacción.

6.2 Confianza

La confianza de una regla \(X \Rightarrow Y\) mide la proporción de transacciones que contienen \(Y\) entre aquellas que contienen \(X\).

\[ \text{confidence}(X \Rightarrow Y) = \frac{\text{support}(X \cup Y)}{\text{support}(X)} \]

También puede interpretarse como una probabilidad condicional empírica:

\[ \text{confidence}(X \Rightarrow Y) = P(Y \mid X) \]

6.2.1 Interpretación

Si una regla tiene confianza 0.75, significa que el 75% de las transacciones que contienen \(X\) también contienen \(Y\).

La confianza responde a la pregunta:

Cuando aparece el antecedente, ¿con qué frecuencia aparece también el consecuente?

6.2.2 Advertencia

La confianza puede ser engañosa cuando el consecuente es muy frecuente.

Por ejemplo, si el 80% de los clientes compran pan, muchas reglas de la forma:

\[ X \Rightarrow \{\text{pan}\} \]

pueden tener confianza alta simplemente porque el pan aparece en casi todas las cestas.

6.3 Lift

El lift compara la confianza observada con la frecuencia esperada del consecuente si antecedente y consecuente fueran independientes.

\[ \text{lift}(X \Rightarrow Y) = \frac{\text{confidence}(X \Rightarrow Y)}{\text{support}(Y)} \]

Equivalente:

\[ \text{lift}(X \Rightarrow Y) = \frac{\text{support}(X \cup Y)}{\text{support}(X)\text{support}(Y)} \]

6.3.1 Interpretación

  • \(\text{lift} = 1\): no hay asociación aparente entre \(X\) e \(Y\).
  • \(\text{lift} > 1\): \(X\) e \(Y\) aparecen juntos más de lo esperado bajo independencia.
  • \(\text{lift} < 1\): \(X\) e \(Y\) aparecen juntos menos de lo esperado bajo independencia.

Si una regla tiene lift 2.4, significa que el consecuente aparece 2.4 veces más a menudo cuando aparece el antecedente que lo que cabría esperar si no hubiera relación.

6.3.2 Interpretación práctica

El lift suele ser más útil que la confianza para detectar reglas realmente interesantes, porque corrige parcialmente el efecto de consecuentes muy frecuentes.

6.4 Leverage

El leverage mide la diferencia absoluta entre el soporte observado de \(X \cup Y\) y el soporte esperado bajo independencia.

\[ \text{leverage}(X \Rightarrow Y) = \text{support}(X \cup Y) - \text{support}(X)\text{support}(Y) \]

6.4.1 Interpretación

  • leverage = 0: independencia aproximada;
  • leverage > 0: coocurrencia mayor de la esperada;
  • leverage < 0: coocurrencia menor de la esperada.

A diferencia del lift, el leverage mide una diferencia absoluta. Esto ayuda a distinguir reglas con lift muy alto pero soporte ínfimo de reglas con impacto real en muchas transacciones.

6.5 Conviction

La conviction mide hasta qué punto el antecedente implica el consecuente en comparación con lo que se esperaría por azar.

\[ \text{conviction}(X \Rightarrow Y) = \frac{1 - \text{support}(Y)}{1 - \text{confidence}(X \Rightarrow Y)} \]

6.5.1 Interpretación

  • conviction cercana a 1: poca evidencia de implicación;
  • conviction alta: la regla falla menos de lo esperado bajo independencia;
  • conviction infinita: confianza igual a 1.

Es una métrica asimétrica: la conviction de \(X \Rightarrow Y\) no tiene por qué coincidir con la de \(Y \Rightarrow X\).

6.6 Coverage

La coverage de una regla es el soporte del antecedente:

\[ \text{coverage}(X \Rightarrow Y) = \text{support}(X) \]

6.6.1 Interpretación

Indica a qué proporción de transacciones se puede aplicar la regla.

Una regla con mucha confianza pero coverage muy bajo puede ser precisa, pero aplicable a muy pocos casos.

6.7 Count

El count es el número absoluto de transacciones que contienen \(X \cup Y\).

\[ \text{count}(X \Rightarrow Y) = n \cdot \text{support}(X \cup Y) \]

Es especialmente útil para evitar sobreinterpretar reglas basadas en muy pocos casos.

7 Ejemplo manual con pocas transacciones

Antes de usar R, conviene entender las métricas a mano.

Supongamos las siguientes transacciones:

Transacción Items
T1 pan, leche, huevos
T2 pan, leche
T3 pan, queso
T4 leche, huevos
T5 pan, leche, queso
T6 pan, huevos
T7 leche, queso
T8 pan, leche, huevos

Analicemos la regla:

\[ \{\text{pan}\} \Rightarrow \{\text{leche}\} \]

Tenemos:

  • número total de transacciones: 8;
  • transacciones con pan: T1, T2, T3, T5, T6, T8 = 6;
  • transacciones con leche: T1, T2, T4, T5, T7, T8 = 6;
  • transacciones con pan y leche: T1, T2, T5, T8 = 4.

Por tanto:

\[ \text{support}(pan \Rightarrow leche) = \frac{4}{8} = 0.5 \]

\[ \text{confidence}(pan \Rightarrow leche) = \frac{4/8}{6/8} = \frac{4}{6} = 0.667 \]

\[ \text{lift}(pan \Rightarrow leche) = \frac{0.667}{6/8} = 0.889 \]

7.0.1 Interpretación

Aunque la confianza es relativamente alta, el lift es menor que 1. Esto indica que la presencia de pan no aumenta la probabilidad de leche; de hecho, la reduce ligeramente respecto a la frecuencia global de leche.

Este ejemplo muestra por qué no conviene ordenar reglas solo por confianza.

8 Algoritmo Apriori

El algoritmo Apriori es uno de los métodos clásicos para descubrir itemsets frecuentes y generar reglas de asociación.

Su idea central es el principio de monotonía descendente o downward closure:

Si un itemset no es frecuente, entonces ninguno de sus superconjuntos puede ser frecuente.

Por ejemplo, si:

\[ \{A, B\} \]

no alcanza el soporte mínimo, entonces ningún itemset que lo contenga podrá alcanzar el soporte mínimo:

\[ \{A, B, C\}, \{A, B, D\}, \{A, B, C, D\}, \dots \]

Esto permite podar una gran parte del espacio de búsqueda.

8.1 Etapas del algoritmo

El procedimiento general es:

  1. Identificar los 1-itemsets frecuentes.
  2. Generar candidatos de tamaño 2.
  3. Eliminar candidatos con subconjuntos infrecuentes.
  4. Calcular soporte y conservar solo los frecuentes.
  5. Repetir el proceso para tamaños mayores.
  6. A partir de los itemsets frecuentes, generar reglas.
  7. Filtrar las reglas por confianza mínima u otras métricas.

8.2 Ventajas

  • Es conceptualmente sencillo.
  • Produce reglas interpretables.
  • Está ampliamente implementado.
  • Permite restricciones por soporte, confianza, longitud y apariencia.

8.3 Limitaciones

  • Puede generar muchísimos candidatos.
  • Requiere varios escaneos de la base de datos.
  • Puede ser costoso con muchos items.
  • Puede producir reglas redundantes o triviales.
  • Es sensible a la elección de soporte y confianza mínimos.

9 Algoritmo Eclat

El algoritmo Eclat también busca itemsets frecuentes, pero utiliza una representación vertical de las transacciones.

En lugar de guardar cada transacción con sus items, guarda cada item junto con las transacciones donde aparece.

Ejemplo:

Item Transacciones
pan T1, T2, T3
leche T1, T2, T4
queso T3, T4

Para calcular el soporte de un itemset, Eclat intersecta conjuntos de identificadores de transacción.

Por ejemplo:

\[ \{pan, leche\} = T(pan) \cap T(leche) \]

9.1 Diferencia práctica con Apriori

  • Apriori trabaja de forma más explícita con generación de candidatos.
  • Eclat suele ser eficiente para itemsets frecuentes usando intersecciones de identificadores.
  • Eclat genera itemsets frecuentes, no reglas directamente. Después se pueden derivar reglas a partir de esos itemsets.

10 Preparación del entorno en R

Mostrar código
# Cargamos las librerías necesarias.
# Se incluyen paquetes para:
# - manipulación de datos
# - extracción de reglas de asociación
# - visualización de reglas
# - tablas y gráficos

list.of.packages <- c("arules", "arulesViz", "dplyr", "tidyr", "stringr", "ggplot2",
  "tibble", "purrr", "knitr", "kableExtra", "scales", "forcats", "RColorBrewer")

new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[, "Package"])]
if (length(new.packages) > 0) {
  install.packages(new.packages)
}

invisible(lapply(list.of.packages, require, character.only = TRUE))
rm(list.of.packages, new.packages)

11 Conjunto de datos: Groceries

Trabajaremos con el conjunto de datos Groceries, incluido en el paquete arules.

Este dataset contiene transacciones de supermercado. Cada fila es una cesta de compra y cada item es un producto presente en esa cesta.

Mostrar código
data("Groceries")
Groceries
transactions in sparse format with
 9835 transactions (rows) and
 169 items (columns)

11.0.1 Interpretación

El objeto Groceries es de clase transactions. Esto significa que no es un data.frame clásico, sino una estructura optimizada para almacenar información de presencia/ausencia de items.

Mostrar código
class(Groceries)
[1] "transactions"
attr(,"package")
[1] "arules"
Mostrar código
summary(Groceries)
transactions as itemMatrix in sparse format with
 9835 rows (elements/itemsets/transactions) and
 169 columns (items) and a density of 0.02609146 

most frequent items:
      whole milk other vegetables       rolls/buns             soda 
            2513             1903             1809             1715 
          yogurt          (Other) 
            1372            34055 

element (itemset/transaction) length distribution:
sizes
   1    2    3    4    5    6    7    8    9   10   11   12   13   14   15   16 
2159 1643 1299 1005  855  645  545  438  350  246  182  117   78   77   55   46 
  17   18   19   20   21   22   23   24   26   27   28   29   32 
  29   14   14    9   11    4    6    1    1    1    1    3    1 

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  1.000   2.000   3.000   4.409   6.000  32.000 

includes extended item information - examples:
       labels  level2           level1
1 frankfurter sausage meat and sausage
2     sausage sausage meat and sausage
3  liver loaf sausage meat and sausage
Mostrar código
itemInfo(Groceries)

11.0.2 Interpretación

La salida de summary() permite ver:

  • número de transacciones;
  • número de items distintos;
  • densidad de la matriz;
  • distribución del tamaño de las cestas;
  • items más frecuentes.

La densidad indica qué proporción de la matriz transacción-item contiene unos. En datos de supermercado suele ser baja, porque cada cliente compra solo unos pocos productos del catálogo total.

12 Exploración inicial de las transacciones

12.1 Número de transacciones e items

Mostrar código
n_transacciones <- length(Groceries)
n_items <- length(itemLabels(Groceries))

n_transacciones
[1] 9835
Mostrar código
n_items
[1] 169

12.1.1 Interpretación

Tenemos 9835 transacciones y 169 items distintos. Esto ya anticipa un problema combinatorio: el número potencial de itemsets crece muy rápidamente con el número de items.

12.2 Primeras transacciones

Mostrar código
inspect(Groceries[1:5])
    items                     
[1] {citrus fruit,            
     semi-finished bread,     
     margarine,               
     ready soups}             
[2] {tropical fruit,          
     yogurt,                  
     coffee}                  
[3] {whole milk}              
[4] {pip fruit,               
     yogurt,                  
     cream cheese ,           
     meat spreads}            
[5] {other vegetables,        
     whole milk,              
     condensed milk,          
     long life bakery product}

12.2.1 Interpretación

Cada línea representa una cesta de compra. Los elementos entre llaves son los productos comprados conjuntamente.

12.3 Tamaño de las cestas

Mostrar código
tamanyos_cesta <- size(Groceries)

summary(tamanyos_cesta)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  1.000   2.000   3.000   4.409   6.000  32.000 
Mostrar código
ggplot(data.frame(tamanyo = tamanyos_cesta), aes(x = tamanyo)) +
  geom_histogram(binwidth = 1, boundary = 0, color = "white") +
  labs(
    title = "Distribución del tamaño de las cestas",
    subtitle = "Número de items por transacción",
    x = "Número de items en la cesta",
    y = "Número de transacciones"
  ) +
  theme_minimal()

12.3.1 Interpretación

Este gráfico permite identificar si las compras suelen ser pequeñas o grandes. Si la mayoría de cestas tienen pocos productos, será más difícil encontrar reglas largas con soporte suficiente.

13 Frecuencia de items

13.1 Items más frecuentes

Mostrar código
itemFrequencyPlot(
  Groceries,
  topN = 20,
  type = "relative",
  main = "Top 20 items más frecuentes",
  ylab = "Soporte relativo"
)

13.1.1 Interpretación

Los items más frecuentes suelen aparecer en muchas reglas. Esto puede ser útil, pero también peligroso: productos muy habituales pueden generar reglas de alta confianza pero poco informativas.

13.2 Tabla de frecuencia de items

Mostrar código
freq_items <- itemFrequency(Groceries, type = "relative") |>
  sort(decreasing = TRUE) |>
  head(20)

freq_items_tbl <- tibble(
  item = names(freq_items),
  soporte = as.numeric(freq_items)
)

freq_items_tbl |>
  mutate(soporte = percent(soporte, accuracy = 0.01)) |>
  kable(caption = "Top 20 items por soporte relativo") |>
  kable_styling(full_width = FALSE)
Top 20 items por soporte relativo
item soporte
whole milk 25.55%
other vegetables 19.35%
rolls/buns 18.39%
soda 17.44%
yogurt 13.95%
bottled water 11.05%
root vegetables 10.90%
tropical fruit 10.49%
shopping bags 9.85%
sausage 9.40%
pastry 8.90%
citrus fruit 8.28%
bottled beer 8.05%
newspapers 7.98%
canned beer 7.77%
pip fruit 7.56%
fruit/vegetable juice 7.23%
whipped/sour cream 7.17%
brown bread 6.49%
domestic eggs 6.34%

13.2.1 Interpretación

El soporte de un item individual indica la proporción de cestas donde aparece. Por ejemplo, si whole milk tiene soporte aproximado 0.26, significa que aparece en torno al 26% de las transacciones.

14 Extracción de reglas con Apriori

14.1 Primera ejecución

Aplicamos Apriori con parámetros relativamente conservadores.

Mostrar código
reglas_1 <- apriori(
  Groceries,
  parameter = list(
    supp = 0.01,
    conf = 0.5,
    minlen = 2
  )
)
Apriori

Parameter specification:
 confidence minval smax arem  aval originalSupport maxtime support minlen
        0.5    0.1    1 none FALSE            TRUE       5    0.01      2
 maxlen target  ext
     10  rules TRUE

Algorithmic control:
 filter tree heap memopt load sort verbose
    0.1 TRUE TRUE  FALSE TRUE    2    TRUE

Absolute minimum support count: 98 

set item appearances ...[0 item(s)] done [0.00s].
set transactions ...[169 item(s), 9835 transaction(s)] done [0.00s].
sorting and recoding items ... [88 item(s)] done [0.00s].
creating transaction tree ... done [0.00s].
checking subsets of size 1 2 3 4 done [0.00s].
writing ... [15 rule(s)] done [0.00s].
creating S4 object  ... done [0.00s].
Mostrar código
reglas_1
set of 15 rules 

14.1.1 Interpretación

Los parámetros significan:

  • supp = 0.01: la regla debe aparecer en al menos el 1% de las transacciones;
  • conf = 0.5: al menos el 50% de las transacciones con el antecedente deben contener el consecuente;
  • minlen = 2: la regla debe tener al menos dos items en total.
Mostrar código
summary(reglas_1)
set of 15 rules

rule length distribution (lhs + rhs):sizes
 3 
15 

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
      3       3       3       3       3       3 

summary of quality measures:
    support          confidence        coverage            lift      
 Min.   :0.01007   Min.   :0.5000   Min.   :0.01729   Min.   :1.984  
 1st Qu.:0.01174   1st Qu.:0.5151   1st Qu.:0.02089   1st Qu.:2.036  
 Median :0.01230   Median :0.5245   Median :0.02430   Median :2.203  
 Mean   :0.01316   Mean   :0.5411   Mean   :0.02454   Mean   :2.299  
 3rd Qu.:0.01403   3rd Qu.:0.5718   3rd Qu.:0.02598   3rd Qu.:2.432  
 Max.   :0.02227   Max.   :0.5862   Max.   :0.04342   Max.   :3.030  
     count      
 Min.   : 99.0  
 1st Qu.:115.5  
 Median :121.0  
 Mean   :129.4  
 3rd Qu.:138.0  
 Max.   :219.0  

mining info:
      data ntransactions support confidence
 Groceries          9835    0.01        0.5
                                                                             call
 apriori(data = Groceries, parameter = list(supp = 0.01, conf = 0.5, minlen = 2))

14.1.2 Interpretación

La salida resume:

  • distribución del número de items por regla;
  • resumen de soporte, confianza, coverage, lift y count;
  • reglas generadas.

Un número muy bajo de reglas puede indicar parámetros demasiado exigentes. Un número muy alto puede indicar parámetros demasiado permisivos.

15 Inspección de reglas

15.1 Reglas ordenadas por lift

Mostrar código
reglas_lift <- sort(reglas_1, by = "lift", decreasing = TRUE)
inspect(head(reglas_lift, 10))
     lhs                                  rhs                support   
[1]  {citrus fruit, root vegetables}   => {other vegetables} 0.01037112
[2]  {tropical fruit, root vegetables} => {other vegetables} 0.01230300
[3]  {root vegetables, rolls/buns}     => {other vegetables} 0.01220132
[4]  {root vegetables, yogurt}         => {other vegetables} 0.01291307
[5]  {curd, yogurt}                    => {whole milk}       0.01006609
[6]  {other vegetables, butter}        => {whole milk}       0.01148958
[7]  {tropical fruit, root vegetables} => {whole milk}       0.01199797
[8]  {root vegetables, yogurt}         => {whole milk}       0.01453991
[9]  {other vegetables, domestic eggs} => {whole milk}       0.01230300
[10] {yogurt, whipped/sour cream}      => {whole milk}       0.01087951
     confidence coverage   lift     count
[1]  0.5862069  0.01769192 3.029608 102  
[2]  0.5845411  0.02104728 3.020999 121  
[3]  0.5020921  0.02430097 2.594890 120  
[4]  0.5000000  0.02582613 2.584078 127  
[5]  0.5823529  0.01728521 2.279125  99  
[6]  0.5736041  0.02003050 2.244885 113  
[7]  0.5700483  0.02104728 2.230969 118  
[8]  0.5629921  0.02582613 2.203354 143  
[9]  0.5525114  0.02226741 2.162336 121  
[10] 0.5245098  0.02074225 2.052747 107  

15.1.1 Interpretación

Ordenar por lift ayuda a encontrar asociaciones más fuertes que las esperadas por independencia. Sin embargo, una regla con lift alto pero soporte bajo puede ser poco robusta.

15.2 Reglas ordenadas por confianza

Mostrar código
reglas_confianza <- sort(reglas_1, by = "confidence", decreasing = TRUE)
inspect(head(reglas_confianza, 10))
     lhs                                  rhs                support   
[1]  {citrus fruit, root vegetables}   => {other vegetables} 0.01037112
[2]  {tropical fruit, root vegetables} => {other vegetables} 0.01230300
[3]  {curd, yogurt}                    => {whole milk}       0.01006609
[4]  {other vegetables, butter}        => {whole milk}       0.01148958
[5]  {tropical fruit, root vegetables} => {whole milk}       0.01199797
[6]  {root vegetables, yogurt}         => {whole milk}       0.01453991
[7]  {other vegetables, domestic eggs} => {whole milk}       0.01230300
[8]  {yogurt, whipped/sour cream}      => {whole milk}       0.01087951
[9]  {root vegetables, rolls/buns}     => {whole milk}       0.01270971
[10] {pip fruit, other vegetables}     => {whole milk}       0.01352313
     confidence coverage   lift     count
[1]  0.5862069  0.01769192 3.029608 102  
[2]  0.5845411  0.02104728 3.020999 121  
[3]  0.5823529  0.01728521 2.279125  99  
[4]  0.5736041  0.02003050 2.244885 113  
[5]  0.5700483  0.02104728 2.230969 118  
[6]  0.5629921  0.02582613 2.203354 143  
[7]  0.5525114  0.02226741 2.162336 121  
[8]  0.5245098  0.02074225 2.052747 107  
[9]  0.5230126  0.02430097 2.046888 125  
[10] 0.5175097  0.02613116 2.025351 133  

15.2.1 Interpretación

Ordenar por confianza responde a la pregunta:

Dado el antecedente, ¿cuáles son los consecuentes más probables?

Pero hay que verificar si el consecuente no es simplemente un item muy frecuente.

15.3 Reglas ordenadas por soporte

Mostrar código
reglas_soporte <- sort(reglas_1, by = "support", decreasing = TRUE)
inspect(head(reglas_soporte, 10))
     lhs                                       rhs                support   
[1]  {other vegetables, yogurt}             => {whole milk}       0.02226741
[2]  {tropical fruit, yogurt}               => {whole milk}       0.01514997
[3]  {other vegetables, whipped/sour cream} => {whole milk}       0.01464159
[4]  {root vegetables, yogurt}              => {whole milk}       0.01453991
[5]  {pip fruit, other vegetables}          => {whole milk}       0.01352313
[6]  {root vegetables, yogurt}              => {other vegetables} 0.01291307
[7]  {root vegetables, rolls/buns}          => {whole milk}       0.01270971
[8]  {other vegetables, domestic eggs}      => {whole milk}       0.01230300
[9]  {tropical fruit, root vegetables}      => {other vegetables} 0.01230300
[10] {root vegetables, rolls/buns}          => {other vegetables} 0.01220132
     confidence coverage   lift     count
[1]  0.5128806  0.04341637 2.007235 219  
[2]  0.5173611  0.02928317 2.024770 149  
[3]  0.5070423  0.02887646 1.984385 144  
[4]  0.5629921  0.02582613 2.203354 143  
[5]  0.5175097  0.02613116 2.025351 133  
[6]  0.5000000  0.02582613 2.584078 127  
[7]  0.5230126  0.02430097 2.046888 125  
[8]  0.5525114  0.02226741 2.162336 121  
[9]  0.5845411  0.02104728 3.020999 121  
[10] 0.5020921  0.02430097 2.594890 120  

15.3.1 Interpretación

Ordenar por soporte prioriza patrones que afectan a muchas transacciones. Son reglas con mayor cobertura, aunque no necesariamente las más sorprendentes.

16 Conversión de reglas a tabla

Para analizar reglas de manera más cómoda, se pueden convertir a data.frame.

Mostrar código
reglas_df <- as(reglas_1, "data.frame") |>
  as_tibble()

head(reglas_df)
Mostrar código
reglas_df |>
  arrange(desc(lift)) |>
  slice(1:15) |>
  mutate(
    support = round(support, 4),
    confidence = round(confidence, 4),
    coverage = round(coverage, 4),
    lift = round(lift, 4),
    count = round(count, 0)
  ) |>
  kable(caption = "Top 15 reglas ordenadas por lift") |>
  kable_styling(full_width = FALSE)
Top 15 reglas ordenadas por lift
rules support confidence coverage lift count
{citrus fruit,root vegetables} => {other vegetables} 0.0104 0.5862 0.0177 3.0296 102
{tropical fruit,root vegetables} => {other vegetables} 0.0123 0.5845 0.0210 3.0210 121
{root vegetables,rolls/buns} => {other vegetables} 0.0122 0.5021 0.0243 2.5949 120
{root vegetables,yogurt} => {other vegetables} 0.0129 0.5000 0.0258 2.5841 127
{curd,yogurt} => {whole milk} 0.0101 0.5824 0.0173 2.2791 99
{other vegetables,butter} => {whole milk} 0.0115 0.5736 0.0200 2.2449 113
{tropical fruit,root vegetables} => {whole milk} 0.0120 0.5700 0.0210 2.2310 118
{root vegetables,yogurt} => {whole milk} 0.0145 0.5630 0.0258 2.2034 143
{other vegetables,domestic eggs} => {whole milk} 0.0123 0.5525 0.0223 2.1623 121
{yogurt,whipped/sour cream} => {whole milk} 0.0109 0.5245 0.0207 2.0527 107
{root vegetables,rolls/buns} => {whole milk} 0.0127 0.5230 0.0243 2.0469 125
{pip fruit,other vegetables} => {whole milk} 0.0135 0.5175 0.0261 2.0254 133
{tropical fruit,yogurt} => {whole milk} 0.0151 0.5174 0.0293 2.0248 149
{other vegetables,yogurt} => {whole milk} 0.0223 0.5129 0.0434 2.0072 219
{other vegetables,whipped/sour cream} => {whole milk} 0.0146 0.5070 0.0289 1.9844 144

17 Visualización de reglas

17.1 Gráfico soporte-confianza coloreado por lift

Mostrar código
plot(
  reglas_1,
  method = "scatterplot",
  measure = c("support", "confidence"),
  shading = "lift"
)

17.1.1 Interpretación

Cada punto representa una regla.

  • Eje X: soporte.
  • Eje Y: confianza.
  • Color: lift.

Las reglas más interesantes suelen combinar:

  • soporte no demasiado bajo;
  • confianza alta;
  • lift mayor que 1.

No obstante, no existe un único criterio universal. La elección depende del problema.

17.2 Gráfico de dos medidas con jitter

Mostrar código
plot(
  reglas_1,
  method = "two-key plot"
)

17.2.1 Interpretación

Este gráfico resume varias métricas simultáneamente. Es útil cuando hay muchas reglas y queremos identificar regiones de interés.

17.3 Grafo de reglas

Mostrar código
reglas_top_lift <- head(sort(reglas_1, by = "lift", decreasing = TRUE), 20)

plot(
  reglas_top_lift,
  method = "graph",
  engine = "htmlwidget"
)

17.3.1 Interpretación

El grafo permite ver qué items aparecen conectados por reglas. Es especialmente útil para presentaciones o exploración inicial, pero puede volverse ilegible si se muestran demasiadas reglas.

17.4 Gráfico agrupado

Mostrar código
plot(reglas_top_lift, method = "grouped")

17.4.1 Interpretación

El gráfico permite ver relaciones existentes agrupadas por el consecuente.

18 Filtrado de reglas

18.1 Reglas con un consecuente concreto

Supongamos que nos interesa estudiar qué productos conducen a la compra de whole milk.

Mostrar código
reglas_whole_milk <- apriori(
  Groceries,
  parameter = list(
    supp = 0.005,
    conf = 0.3,
    minlen = 2
  ),
  appearance = list(
    rhs = "whole milk",
    default = "lhs"
  )
)
Apriori

Parameter specification:
 confidence minval smax arem  aval originalSupport maxtime support minlen
        0.3    0.1    1 none FALSE            TRUE       5   0.005      2
 maxlen target  ext
     10  rules TRUE

Algorithmic control:
 filter tree heap memopt load sort verbose
    0.1 TRUE TRUE  FALSE TRUE    2    TRUE

Absolute minimum support count: 49 

set item appearances ...[1 item(s)] done [0.00s].
set transactions ...[169 item(s), 9835 transaction(s)] done [0.00s].
sorting and recoding items ... [120 item(s)] done [0.00s].
creating transaction tree ... done [0.00s].
checking subsets of size 1 2 3 4 done [0.00s].
writing ... [212 rule(s)] done [0.00s].
creating S4 object  ... done [0.00s].
Mostrar código
reglas_whole_milk <- sort(reglas_whole_milk, by = "lift", decreasing = TRUE)
inspect(head(reglas_whole_milk, 15))
     lhs                        rhs              support confidence    coverage     lift count
[1]  {tropical fruit,                                                                         
      root vegetables,                                                                        
      yogurt}                => {whole milk} 0.005693950  0.7000000 0.008134215 2.739554    56
[2]  {pip fruit,                                                                              
      root vegetables,                                                                        
      other vegetables}      => {whole milk} 0.005490595  0.6750000 0.008134215 2.641713    54
[3]  {butter,                                                                                 
      whipped/sour cream}    => {whole milk} 0.006710727  0.6600000 0.010167768 2.583008    66
[4]  {pip fruit,                                                                              
      whipped/sour cream}    => {whole milk} 0.005998983  0.6483516 0.009252669 2.537421    59
[5]  {butter,                                                                                 
      yogurt}                => {whole milk} 0.009354347  0.6388889 0.014641586 2.500387    92
[6]  {root vegetables,                                                                        
      butter}                => {whole milk} 0.008235892  0.6377953 0.012913066 2.496107    81
[7]  {tropical fruit,                                                                         
      curd}                  => {whole milk} 0.006507372  0.6336634 0.010269446 2.479936    64
[8]  {pip fruit,                                                                              
      other vegetables,                                                                       
      yogurt}                => {whole milk} 0.005083884  0.6250000 0.008134215 2.446031    50
[9]  {pip fruit,                                                                              
      domestic eggs}         => {whole milk} 0.005388917  0.6235294 0.008642603 2.440275    53
[10] {tropical fruit,                                                                         
      butter}                => {whole milk} 0.006202339  0.6224490 0.009964413 2.436047    61
[11] {domestic eggs,                                                                          
      margarine}             => {whole milk} 0.005185562  0.6219512 0.008337570 2.434099    51
[12] {butter,                                                                                 
      domestic eggs}         => {whole milk} 0.005998983  0.6210526 0.009659380 2.430582    59
[13] {tropical fruit,                                                                         
      other vegetables,                                                                       
      yogurt}                => {whole milk} 0.007625826  0.6198347 0.012302999 2.425816    75
[14] {other vegetables,                                                                       
      yogurt,                                                                                 
      fruit/vegetable juice} => {whole milk} 0.005083884  0.6172840 0.008235892 2.415833    50
[15] {tropical fruit,                                                                         
      domestic eggs}         => {whole milk} 0.006914082  0.6071429 0.011387900 2.376144    68

18.1.1 Interpretación

Aquí forzamos que whole milk aparezca en el consecuente. Esto transforma el análisis en una pregunta más dirigida:

¿Qué combinaciones de productos se asocian con la presencia de leche?

Esto es útil cuando el negocio tiene un item objetivo: un producto, servicio, conversión o comportamiento.

18.2 Reglas donde aparece un item en cualquier lado

Mostrar código
reglas_yogurt <- subset(reglas_1, items %in% "yogurt")
reglas_yogurt <- sort(reglas_yogurt, by = "lift", decreasing = TRUE)
inspect(head(reglas_yogurt, 10))
    lhs                             rhs                support    confidence
[1] {root vegetables, yogurt}    => {other vegetables} 0.01291307 0.5000000 
[2] {curd, yogurt}               => {whole milk}       0.01006609 0.5823529 
[3] {root vegetables, yogurt}    => {whole milk}       0.01453991 0.5629921 
[4] {yogurt, whipped/sour cream} => {whole milk}       0.01087951 0.5245098 
[5] {tropical fruit, yogurt}     => {whole milk}       0.01514997 0.5173611 
[6] {other vegetables, yogurt}   => {whole milk}       0.02226741 0.5128806 
    coverage   lift     count
[1] 0.02582613 2.584078 127  
[2] 0.01728521 2.279125  99  
[3] 0.02582613 2.203354 143  
[4] 0.02074225 2.052747 107  
[5] 0.02928317 2.024770 149  
[6] 0.04341637 2.007235 219  

18.2.1 Interpretación

Este filtro permite estudiar el ecosistema de un item, independientemente de si aparece como antecedente o consecuente.

18.3 Reglas con lift alto y soporte mínimo razonable

Mostrar código
reglas_interesantes <- subset(
  reglas_1,
  subset = lift > 2 & support > 0.01 & confidence > 0.5
)

length(reglas_interesantes)
[1] 13
Mostrar código
inspect(sort(reglas_interesantes, by = "lift", decreasing = TRUE))
     lhs                                  rhs                support   
[1]  {citrus fruit, root vegetables}   => {other vegetables} 0.01037112
[2]  {tropical fruit, root vegetables} => {other vegetables} 0.01230300
[3]  {root vegetables, rolls/buns}     => {other vegetables} 0.01220132
[4]  {curd, yogurt}                    => {whole milk}       0.01006609
[5]  {other vegetables, butter}        => {whole milk}       0.01148958
[6]  {tropical fruit, root vegetables} => {whole milk}       0.01199797
[7]  {root vegetables, yogurt}         => {whole milk}       0.01453991
[8]  {other vegetables, domestic eggs} => {whole milk}       0.01230300
[9]  {yogurt, whipped/sour cream}      => {whole milk}       0.01087951
[10] {root vegetables, rolls/buns}     => {whole milk}       0.01270971
[11] {pip fruit, other vegetables}     => {whole milk}       0.01352313
[12] {tropical fruit, yogurt}          => {whole milk}       0.01514997
[13] {other vegetables, yogurt}        => {whole milk}       0.02226741
     confidence coverage   lift     count
[1]  0.5862069  0.01769192 3.029608 102  
[2]  0.5845411  0.02104728 3.020999 121  
[3]  0.5020921  0.02430097 2.594890 120  
[4]  0.5823529  0.01728521 2.279125  99  
[5]  0.5736041  0.02003050 2.244885 113  
[6]  0.5700483  0.02104728 2.230969 118  
[7]  0.5629921  0.02582613 2.203354 143  
[8]  0.5525114  0.02226741 2.162336 121  
[9]  0.5245098  0.02074225 2.052747 107  
[10] 0.5230126  0.02430097 2.046888 125  
[11] 0.5175097  0.02613116 2.025351 133  
[12] 0.5173611  0.02928317 2.024770 149  
[13] 0.5128806  0.04341637 2.007235 219  

18.3.1 Interpretación

Este tipo de filtrado combina varias dimensiones:

  • soporte para asegurar presencia mínima;
  • confianza para asegurar fiabilidad condicional;
  • lift para asegurar asociación no trivial.

19 Reglas redundantes

Una regla es redundante si no aporta información adicional respecto a otra regla más general.

Por ejemplo:

\[ \{A\} \Rightarrow \{C\} \]

puede hacer redundante a:

\[ \{A, B\} \Rightarrow \{C\} \]

si ambas tienen métricas muy similares y la segunda solo añade complejidad.

Mostrar código
reglas_redundantes <- is.redundant(reglas_1)
table(reglas_redundantes)
reglas_redundantes
FALSE 
   15 
Mostrar código
reglas_no_redundantes <- reglas_1[!reglas_redundantes]

length(reglas_1)
[1] 15
Mostrar código
length(reglas_no_redundantes)
[1] 15
Mostrar código
inspect(head(sort(reglas_no_redundantes, by = "lift", decreasing = TRUE), 15))
     lhs                                       rhs                support   
[1]  {citrus fruit, root vegetables}        => {other vegetables} 0.01037112
[2]  {tropical fruit, root vegetables}      => {other vegetables} 0.01230300
[3]  {root vegetables, rolls/buns}          => {other vegetables} 0.01220132
[4]  {root vegetables, yogurt}              => {other vegetables} 0.01291307
[5]  {curd, yogurt}                         => {whole milk}       0.01006609
[6]  {other vegetables, butter}             => {whole milk}       0.01148958
[7]  {tropical fruit, root vegetables}      => {whole milk}       0.01199797
[8]  {root vegetables, yogurt}              => {whole milk}       0.01453991
[9]  {other vegetables, domestic eggs}      => {whole milk}       0.01230300
[10] {yogurt, whipped/sour cream}           => {whole milk}       0.01087951
[11] {root vegetables, rolls/buns}          => {whole milk}       0.01270971
[12] {pip fruit, other vegetables}          => {whole milk}       0.01352313
[13] {tropical fruit, yogurt}               => {whole milk}       0.01514997
[14] {other vegetables, yogurt}             => {whole milk}       0.02226741
[15] {other vegetables, whipped/sour cream} => {whole milk}       0.01464159
     confidence coverage   lift     count
[1]  0.5862069  0.01769192 3.029608 102  
[2]  0.5845411  0.02104728 3.020999 121  
[3]  0.5020921  0.02430097 2.594890 120  
[4]  0.5000000  0.02582613 2.584078 127  
[5]  0.5823529  0.01728521 2.279125  99  
[6]  0.5736041  0.02003050 2.244885 113  
[7]  0.5700483  0.02104728 2.230969 118  
[8]  0.5629921  0.02582613 2.203354 143  
[9]  0.5525114  0.02226741 2.162336 121  
[10] 0.5245098  0.02074225 2.052747 107  
[11] 0.5230126  0.02430097 2.046888 125  
[12] 0.5175097  0.02613116 2.025351 133  
[13] 0.5173611  0.02928317 2.024770 149  
[14] 0.5128806  0.04341637 2.007235 219  
[15] 0.5070423  0.02887646 1.984385 144  

19.0.1 Interpretación

Eliminar reglas redundantes ayuda a producir un conjunto más manejable y más interpretable. En un informe ejecutivo, es preferible presentar pocas reglas robustas y accionables que cientos de reglas similares.

20 Comparación de umbrales

La elección de soporte y confianza afecta mucho al número de reglas generadas.

Mostrar código
param_grid <- expand.grid(
  soporte = c(0.001, 0.005, 0.01, 0.02),
  confianza = c(0.2, 0.4, 0.6, 0.8)
)

conteo_reglas <- param_grid |>
  mutate(
    n_reglas = map2_int(soporte, confianza, function(s, c) {
      reglas_tmp <- apriori(
        Groceries,
        parameter = list(supp = s, conf = c, minlen = 2),
        control = list(verbose = FALSE)
      )
      length(reglas_tmp)
    })
  )

conteo_reglas
Mostrar código
ggplot(conteo_reglas, aes(x = soporte, y = n_reglas, color = factor(confianza))) +
  geom_line() +
  geom_point(size = 2) +
  scale_x_continuous(labels = percent_format(accuracy = 0.1)) +
  labs(
    title = "Efecto del soporte y la confianza en el número de reglas",
    x = "Soporte mínimo",
    y = "Número de reglas",
    color = "Confianza mínima"
  ) +
  theme_minimal()

20.0.1 Interpretación

Al aumentar el soporte mínimo, normalmente disminuye el número de reglas. Al aumentar la confianza mínima, también disminuye el número de reglas. La elección de estos umbrales es una decisión analítica que debe equilibrar:

  • interpretabilidad;
  • robustez;
  • número de reglas;
  • objetivo de negocio;
  • tamaño de la base de datos.

21 Extracción de itemsets frecuentes

Antes de generar reglas, muchas veces interesa estudiar solo los itemsets frecuentes.

Mostrar código
itemsets_frecuentes <- apriori(
  Groceries,
  parameter = list(
    target = "frequent itemsets",
    supp = 0.02,
    minlen = 1
  )
)
Apriori

Parameter specification:
 confidence minval smax arem  aval originalSupport maxtime support minlen
         NA    0.1    1 none FALSE            TRUE       5    0.02      1
 maxlen            target  ext
     10 frequent itemsets TRUE

Algorithmic control:
 filter tree heap memopt load sort verbose
    0.1 TRUE TRUE  FALSE TRUE    2    TRUE

Absolute minimum support count: 196 

set item appearances ...[0 item(s)] done [0.00s].
set transactions ...[169 item(s), 9835 transaction(s)] done [0.00s].
sorting and recoding items ... [59 item(s)] done [0.00s].
creating transaction tree ... done [0.00s].
checking subsets of size 1 2 3 done [0.00s].
sorting transactions ... done [0.00s].
writing ... [122 set(s)] done [0.00s].
creating S4 object  ... done [0.00s].
Mostrar código
itemsets_frecuentes
set of 122 itemsets 
Mostrar código
inspect(head(sort(itemsets_frecuentes, by = "support", decreasing = TRUE), 20))
     items                          support    count
[1]  {whole milk}                   0.25551601 2513 
[2]  {other vegetables}             0.19349263 1903 
[3]  {rolls/buns}                   0.18393493 1809 
[4]  {soda}                         0.17437722 1715 
[5]  {yogurt}                       0.13950178 1372 
[6]  {bottled water}                0.11052364 1087 
[7]  {root vegetables}              0.10899847 1072 
[8]  {tropical fruit}               0.10493137 1032 
[9]  {shopping bags}                0.09852567  969 
[10] {sausage}                      0.09395018  924 
[11] {pastry}                       0.08896797  875 
[12] {citrus fruit}                 0.08276563  814 
[13] {bottled beer}                 0.08052872  792 
[14] {newspapers}                   0.07981698  785 
[15] {canned beer}                  0.07768175  764 
[16] {pip fruit}                    0.07564820  744 
[17] {other vegetables, whole milk} 0.07483477  736 
[18] {fruit/vegetable juice}        0.07229283  711 
[19] {whipped/sour cream}           0.07168277  705 
[20] {brown bread}                  0.06487036  638 

21.0.1 Interpretación

Los itemsets frecuentes muestran grupos de productos que aparecen conjuntamente de forma habitual. No tienen dirección causal ni antecedente-consecuente: simplemente indican coocurrencia.

22 Eclat en R

Mostrar código
itemsets_eclat <- eclat(
  Groceries,
  parameter = list(
    supp = 0.02,
    minlen = 2
  )
)
Eclat

parameter specification:
 tidLists support minlen maxlen            target  ext
    FALSE    0.02      2     10 frequent itemsets TRUE

algorithmic control:
 sparse sort verbose
      7   -2    TRUE

Absolute minimum support count: 196 

create itemset ... 
set transactions ...[169 item(s), 9835 transaction(s)] done [0.00s].
sorting and recoding items ... [59 item(s)] done [0.00s].
creating sparse bit matrix ... [59 row(s), 9835 column(s)] done [0.00s].
writing  ... [63 set(s)] done [0.00s].
Creating S4 object  ... done [0.00s].
Mostrar código
itemsets_eclat
set of 63 itemsets 
Mostrar código
inspect(head(sort(itemsets_eclat, by = "support", decreasing = TRUE), 15))
     items                               support    count
[1]  {other vegetables, whole milk}      0.07483477 736  
[2]  {whole milk, rolls/buns}            0.05663447 557  
[3]  {whole milk, yogurt}                0.05602440 551  
[4]  {root vegetables, whole milk}       0.04890696 481  
[5]  {root vegetables, other vegetables} 0.04738180 466  
[6]  {other vegetables, yogurt}          0.04341637 427  
[7]  {other vegetables, rolls/buns}      0.04260295 419  
[8]  {tropical fruit, whole milk}        0.04229792 416  
[9]  {whole milk, soda}                  0.04006101 394  
[10] {rolls/buns, soda}                  0.03833249 377  
[11] {tropical fruit, other vegetables}  0.03589222 353  
[12] {whole milk, bottled water}         0.03436706 338  
[13] {yogurt, rolls/buns}                0.03436706 338  
[14] {whole milk, pastry}                0.03324860 327  
[15] {other vegetables, soda}            0.03274021 322  

22.0.1 Interpretación

Eclat devuelve itemsets frecuentes. Si el objetivo es encontrar combinaciones frecuentes sin generar reglas direccionales, Eclat puede ser una alternativa adecuada.

22.1 Conversión en diferentes tipos de objetos

Mostrar código
top5 <- sort(itemsets_eclat)[1:5]
inspect(top5)
    items                               support    count
[1] {other vegetables, whole milk}      0.07483477 736  
[2] {whole milk, rolls/buns}            0.05663447 557  
[3] {whole milk, yogurt}                0.05602440 551  
[4] {root vegetables, whole milk}       0.04890696 481  
[5] {root vegetables, other vegetables} 0.04738180 466  

22.1.1 Obtención del itemset en lista

Mostrar código
as(items(top5), "list")
[[1]]
[1] "other vegetables" "whole milk"      

[[2]]
[1] "whole milk" "rolls/buns"

[[3]]
[1] "whole milk" "yogurt"    

[[4]]
[1] "root vegetables" "whole milk"     

[[5]]
[1] "root vegetables"  "other vegetables"

22.1.2 Obtención del itemset en formato matriz binaria

Mostrar código
as(items(top5), "matrix")
     frankfurter sausage liver loaf   ham  meat finished products
[1,]       FALSE   FALSE      FALSE FALSE FALSE             FALSE
[2,]       FALSE   FALSE      FALSE FALSE FALSE             FALSE
[3,]       FALSE   FALSE      FALSE FALSE FALSE             FALSE
[4,]       FALSE   FALSE      FALSE FALSE FALSE             FALSE
[5,]       FALSE   FALSE      FALSE FALSE FALSE             FALSE
     organic sausage chicken turkey  pork  beef hamburger meat  fish
[1,]           FALSE   FALSE  FALSE FALSE FALSE          FALSE FALSE
[2,]           FALSE   FALSE  FALSE FALSE FALSE          FALSE FALSE
[3,]           FALSE   FALSE  FALSE FALSE FALSE          FALSE FALSE
[4,]           FALSE   FALSE  FALSE FALSE FALSE          FALSE FALSE
[5,]           FALSE   FALSE  FALSE FALSE FALSE          FALSE FALSE
     citrus fruit tropical fruit pip fruit grapes berries nuts/prunes
[1,]        FALSE          FALSE     FALSE  FALSE   FALSE       FALSE
[2,]        FALSE          FALSE     FALSE  FALSE   FALSE       FALSE
[3,]        FALSE          FALSE     FALSE  FALSE   FALSE       FALSE
[4,]        FALSE          FALSE     FALSE  FALSE   FALSE       FALSE
[5,]        FALSE          FALSE     FALSE  FALSE   FALSE       FALSE
     root vegetables onions herbs other vegetables packaged fruit/vegetables
[1,]           FALSE  FALSE FALSE             TRUE                     FALSE
[2,]           FALSE  FALSE FALSE            FALSE                     FALSE
[3,]           FALSE  FALSE FALSE            FALSE                     FALSE
[4,]            TRUE  FALSE FALSE            FALSE                     FALSE
[5,]            TRUE  FALSE FALSE             TRUE                     FALSE
     whole milk butter  curd dessert butter milk yogurt whipped/sour cream
[1,]       TRUE  FALSE FALSE   FALSE       FALSE  FALSE              FALSE
[2,]       TRUE  FALSE FALSE   FALSE       FALSE  FALSE              FALSE
[3,]       TRUE  FALSE FALSE   FALSE       FALSE   TRUE              FALSE
[4,]       TRUE  FALSE FALSE   FALSE       FALSE  FALSE              FALSE
[5,]      FALSE  FALSE FALSE   FALSE       FALSE  FALSE              FALSE
     beverages UHT-milk condensed milk cream soft cheese sliced cheese
[1,]     FALSE    FALSE          FALSE FALSE       FALSE         FALSE
[2,]     FALSE    FALSE          FALSE FALSE       FALSE         FALSE
[3,]     FALSE    FALSE          FALSE FALSE       FALSE         FALSE
[4,]     FALSE    FALSE          FALSE FALSE       FALSE         FALSE
[5,]     FALSE    FALSE          FALSE FALSE       FALSE         FALSE
     hard cheese cream cheese  processed cheese spread cheese curd cheese
[1,]       FALSE         FALSE            FALSE         FALSE       FALSE
[2,]       FALSE         FALSE            FALSE         FALSE       FALSE
[3,]       FALSE         FALSE            FALSE         FALSE       FALSE
[4,]       FALSE         FALSE            FALSE         FALSE       FALSE
[5,]       FALSE         FALSE            FALSE         FALSE       FALSE
     specialty cheese mayonnaise salad dressing tidbits frozen vegetables
[1,]            FALSE      FALSE          FALSE   FALSE             FALSE
[2,]            FALSE      FALSE          FALSE   FALSE             FALSE
[3,]            FALSE      FALSE          FALSE   FALSE             FALSE
[4,]            FALSE      FALSE          FALSE   FALSE             FALSE
[5,]            FALSE      FALSE          FALSE   FALSE             FALSE
     frozen fruits frozen meals frozen fish frozen chicken ice cream
[1,]         FALSE        FALSE       FALSE          FALSE     FALSE
[2,]         FALSE        FALSE       FALSE          FALSE     FALSE
[3,]         FALSE        FALSE       FALSE          FALSE     FALSE
[4,]         FALSE        FALSE       FALSE          FALSE     FALSE
[5,]         FALSE        FALSE       FALSE          FALSE     FALSE
     frozen dessert frozen potato products domestic eggs rolls/buns white bread
[1,]          FALSE                  FALSE         FALSE      FALSE       FALSE
[2,]          FALSE                  FALSE         FALSE       TRUE       FALSE
[3,]          FALSE                  FALSE         FALSE      FALSE       FALSE
[4,]          FALSE                  FALSE         FALSE      FALSE       FALSE
[5,]          FALSE                  FALSE         FALSE      FALSE       FALSE
     brown bread pastry roll products  semi-finished bread zwieback
[1,]       FALSE  FALSE          FALSE               FALSE    FALSE
[2,]       FALSE  FALSE          FALSE               FALSE    FALSE
[3,]       FALSE  FALSE          FALSE               FALSE    FALSE
[4,]       FALSE  FALSE          FALSE               FALSE    FALSE
[5,]       FALSE  FALSE          FALSE               FALSE    FALSE
     potato products flour  salt  rice pasta vinegar   oil margarine
[1,]           FALSE FALSE FALSE FALSE FALSE   FALSE FALSE     FALSE
[2,]           FALSE FALSE FALSE FALSE FALSE   FALSE FALSE     FALSE
[3,]           FALSE FALSE FALSE FALSE FALSE   FALSE FALSE     FALSE
[4,]           FALSE FALSE FALSE FALSE FALSE   FALSE FALSE     FALSE
[5,]           FALSE FALSE FALSE FALSE FALSE   FALSE FALSE     FALSE
     specialty fat sugar artif. sweetener honey mustard ketchup spices soups
[1,]         FALSE FALSE            FALSE FALSE   FALSE   FALSE  FALSE FALSE
[2,]         FALSE FALSE            FALSE FALSE   FALSE   FALSE  FALSE FALSE
[3,]         FALSE FALSE            FALSE FALSE   FALSE   FALSE  FALSE FALSE
[4,]         FALSE FALSE            FALSE FALSE   FALSE   FALSE  FALSE FALSE
[5,]         FALSE FALSE            FALSE FALSE   FALSE   FALSE  FALSE FALSE
     ready soups Instant food products sauces cereals organic products
[1,]       FALSE                 FALSE  FALSE   FALSE            FALSE
[2,]       FALSE                 FALSE  FALSE   FALSE            FALSE
[3,]       FALSE                 FALSE  FALSE   FALSE            FALSE
[4,]       FALSE                 FALSE  FALSE   FALSE            FALSE
[5,]       FALSE                 FALSE  FALSE   FALSE            FALSE
     baking powder preservation products pudding powder canned vegetables
[1,]         FALSE                 FALSE          FALSE             FALSE
[2,]         FALSE                 FALSE          FALSE             FALSE
[3,]         FALSE                 FALSE          FALSE             FALSE
[4,]         FALSE                 FALSE          FALSE             FALSE
[5,]         FALSE                 FALSE          FALSE             FALSE
     canned fruit pickled vegetables specialty vegetables   jam sweet spreads
[1,]        FALSE              FALSE                FALSE FALSE         FALSE
[2,]        FALSE              FALSE                FALSE FALSE         FALSE
[3,]        FALSE              FALSE                FALSE FALSE         FALSE
[4,]        FALSE              FALSE                FALSE FALSE         FALSE
[5,]        FALSE              FALSE                FALSE FALSE         FALSE
     meat spreads canned fish dog food cat food pet care baby food coffee
[1,]        FALSE       FALSE    FALSE    FALSE    FALSE     FALSE  FALSE
[2,]        FALSE       FALSE    FALSE    FALSE    FALSE     FALSE  FALSE
[3,]        FALSE       FALSE    FALSE    FALSE    FALSE     FALSE  FALSE
[4,]        FALSE       FALSE    FALSE    FALSE    FALSE     FALSE  FALSE
[5,]        FALSE       FALSE    FALSE    FALSE    FALSE     FALSE  FALSE
     instant coffee   tea cocoa drinks bottled water  soda misc. beverages
[1,]          FALSE FALSE        FALSE         FALSE FALSE           FALSE
[2,]          FALSE FALSE        FALSE         FALSE FALSE           FALSE
[3,]          FALSE FALSE        FALSE         FALSE FALSE           FALSE
[4,]          FALSE FALSE        FALSE         FALSE FALSE           FALSE
[5,]          FALSE FALSE        FALSE         FALSE FALSE           FALSE
     fruit/vegetable juice syrup bottled beer canned beer brandy whisky liquor
[1,]                 FALSE FALSE        FALSE       FALSE  FALSE  FALSE  FALSE
[2,]                 FALSE FALSE        FALSE       FALSE  FALSE  FALSE  FALSE
[3,]                 FALSE FALSE        FALSE       FALSE  FALSE  FALSE  FALSE
[4,]                 FALSE FALSE        FALSE       FALSE  FALSE  FALSE  FALSE
[5,]                 FALSE FALSE        FALSE       FALSE  FALSE  FALSE  FALSE
       rum liqueur liquor (appetizer) white wine red/blush wine prosecco
[1,] FALSE   FALSE              FALSE      FALSE          FALSE    FALSE
[2,] FALSE   FALSE              FALSE      FALSE          FALSE    FALSE
[3,] FALSE   FALSE              FALSE      FALSE          FALSE    FALSE
[4,] FALSE   FALSE              FALSE      FALSE          FALSE    FALSE
[5,] FALSE   FALSE              FALSE      FALSE          FALSE    FALSE
     sparkling wine salty snack popcorn nut snack snack products
[1,]          FALSE       FALSE   FALSE     FALSE          FALSE
[2,]          FALSE       FALSE   FALSE     FALSE          FALSE
[3,]          FALSE       FALSE   FALSE     FALSE          FALSE
[4,]          FALSE       FALSE   FALSE     FALSE          FALSE
[5,]          FALSE       FALSE   FALSE     FALSE          FALSE
     long life bakery product waffles cake bar chewing gum chocolate
[1,]                    FALSE   FALSE    FALSE       FALSE     FALSE
[2,]                    FALSE   FALSE    FALSE       FALSE     FALSE
[3,]                    FALSE   FALSE    FALSE       FALSE     FALSE
[4,]                    FALSE   FALSE    FALSE       FALSE     FALSE
[5,]                    FALSE   FALSE    FALSE       FALSE     FALSE
     cooking chocolate specialty chocolate specialty bar chocolate marshmallow
[1,]             FALSE               FALSE         FALSE                 FALSE
[2,]             FALSE               FALSE         FALSE                 FALSE
[3,]             FALSE               FALSE         FALSE                 FALSE
[4,]             FALSE               FALSE         FALSE                 FALSE
[5,]             FALSE               FALSE         FALSE                 FALSE
     candy seasonal products detergent softener decalcifier dish cleaner
[1,] FALSE             FALSE     FALSE    FALSE       FALSE        FALSE
[2,] FALSE             FALSE     FALSE    FALSE       FALSE        FALSE
[3,] FALSE             FALSE     FALSE    FALSE       FALSE        FALSE
[4,] FALSE             FALSE     FALSE    FALSE       FALSE        FALSE
[5,] FALSE             FALSE     FALSE    FALSE       FALSE        FALSE
     abrasive cleaner cleaner toilet cleaner bathroom cleaner hair spray
[1,]            FALSE   FALSE          FALSE            FALSE      FALSE
[2,]            FALSE   FALSE          FALSE            FALSE      FALSE
[3,]            FALSE   FALSE          FALSE            FALSE      FALSE
[4,]            FALSE   FALSE          FALSE            FALSE      FALSE
[5,]            FALSE   FALSE          FALSE            FALSE      FALSE
     dental care male cosmetics make up remover skin care
[1,]       FALSE          FALSE           FALSE     FALSE
[2,]       FALSE          FALSE           FALSE     FALSE
[3,]       FALSE          FALSE           FALSE     FALSE
[4,]       FALSE          FALSE           FALSE     FALSE
[5,]       FALSE          FALSE           FALSE     FALSE
     female sanitary products baby cosmetics  soap rubbing alcohol
[1,]                    FALSE          FALSE FALSE           FALSE
[2,]                    FALSE          FALSE FALSE           FALSE
[3,]                    FALSE          FALSE FALSE           FALSE
[4,]                    FALSE          FALSE FALSE           FALSE
[5,]                    FALSE          FALSE FALSE           FALSE
     hygiene articles napkins dishes cookware kitchen utensil cling film/bags
[1,]            FALSE   FALSE  FALSE    FALSE           FALSE           FALSE
[2,]            FALSE   FALSE  FALSE    FALSE           FALSE           FALSE
[3,]            FALSE   FALSE  FALSE    FALSE           FALSE           FALSE
[4,]            FALSE   FALSE  FALSE    FALSE           FALSE           FALSE
[5,]            FALSE   FALSE  FALSE    FALSE           FALSE           FALSE
     kitchen towels house keeping products candles light bulbs
[1,]          FALSE                  FALSE   FALSE       FALSE
[2,]          FALSE                  FALSE   FALSE       FALSE
[3,]          FALSE                  FALSE   FALSE       FALSE
[4,]          FALSE                  FALSE   FALSE       FALSE
[5,]          FALSE                  FALSE   FALSE       FALSE
     sound storage medium newspapers photo/film pot plants
[1,]                FALSE      FALSE      FALSE      FALSE
[2,]                FALSE      FALSE      FALSE      FALSE
[3,]                FALSE      FALSE      FALSE      FALSE
[4,]                FALSE      FALSE      FALSE      FALSE
[5,]                FALSE      FALSE      FALSE      FALSE
     flower soil/fertilizer flower (seeds) shopping bags  bags
[1,]                  FALSE          FALSE         FALSE FALSE
[2,]                  FALSE          FALSE         FALSE FALSE
[3,]                  FALSE          FALSE         FALSE FALSE
[4,]                  FALSE          FALSE         FALSE FALSE
[5,]                  FALSE          FALSE         FALSE FALSE

22.1.3 Conjuntos de elementos como una matriz dispersa

Por razones de eficiencia, la matriz ngCMatrix que se obtiene está transpuesta.

Mostrar código
as(items(top5), "ngCMatrix")
169 x 5 sparse Matrix of class "ngCMatrix"
                                   
frankfurter               . . . . .
sausage                   . . . . .
liver loaf                . . . . .
ham                       . . . . .
meat                      . . . . .
finished products         . . . . .
organic sausage           . . . . .
chicken                   . . . . .
turkey                    . . . . .
pork                      . . . . .
beef                      . . . . .
hamburger meat            . . . . .
fish                      . . . . .
citrus fruit              . . . . .
tropical fruit            . . . . .
pip fruit                 . . . . .
grapes                    . . . . .
berries                   . . . . .
nuts/prunes               . . . . .
root vegetables           . . . | |
onions                    . . . . .
herbs                     . . . . .
other vegetables          | . . . |
packaged fruit/vegetables . . . . .
whole milk                | | | | .
butter                    . . . . .
curd                      . . . . .
dessert                   . . . . .
butter milk               . . . . .
yogurt                    . . | . .
whipped/sour cream        . . . . .
beverages                 . . . . .
UHT-milk                  . . . . .
condensed milk            . . . . .
cream                     . . . . .
soft cheese               . . . . .
sliced cheese             . . . . .
hard cheese               . . . . .
cream cheese              . . . . .
processed cheese          . . . . .
spread cheese             . . . . .
curd cheese               . . . . .
specialty cheese          . . . . .
mayonnaise                . . . . .
salad dressing            . . . . .
tidbits                   . . . . .
frozen vegetables         . . . . .
frozen fruits             . . . . .
frozen meals              . . . . .
frozen fish               . . . . .
frozen chicken            . . . . .
ice cream                 . . . . .
frozen dessert            . . . . .
frozen potato products    . . . . .
domestic eggs             . . . . .
rolls/buns                . | . . .
white bread               . . . . .
brown bread               . . . . .
pastry                    . . . . .
roll products             . . . . .
semi-finished bread       . . . . .
zwieback                  . . . . .
potato products           . . . . .
flour                     . . . . .
salt                      . . . . .
rice                      . . . . .
pasta                     . . . . .
vinegar                   . . . . .
oil                       . . . . .
margarine                 . . . . .
specialty fat             . . . . .
sugar                     . . . . .
artif. sweetener          . . . . .
honey                     . . . . .
mustard                   . . . . .
ketchup                   . . . . .
spices                    . . . . .
soups                     . . . . .
ready soups               . . . . .
Instant food products     . . . . .
sauces                    . . . . .
cereals                   . . . . .
organic products          . . . . .
baking powder             . . . . .
preservation products     . . . . .
pudding powder            . . . . .
canned vegetables         . . . . .
canned fruit              . . . . .
pickled vegetables        . . . . .
specialty vegetables      . . . . .
jam                       . . . . .
sweet spreads             . . . . .
meat spreads              . . . . .
canned fish               . . . . .
dog food                  . . . . .
cat food                  . . . . .
pet care                  . . . . .
baby food                 . . . . .
coffee                    . . . . .
instant coffee            . . . . .
tea                       . . . . .
cocoa drinks              . . . . .
bottled water             . . . . .
soda                      . . . . .
misc. beverages           . . . . .
fruit/vegetable juice     . . . . .
syrup                     . . . . .
bottled beer              . . . . .
canned beer               . . . . .
brandy                    . . . . .
whisky                    . . . . .
liquor                    . . . . .
rum                       . . . . .
liqueur                   . . . . .
liquor (appetizer)        . . . . .
white wine                . . . . .
red/blush wine            . . . . .
prosecco                  . . . . .
sparkling wine            . . . . .
salty snack               . . . . .
popcorn                   . . . . .
nut snack                 . . . . .
snack products            . . . . .
long life bakery product  . . . . .
waffles                   . . . . .
cake bar                  . . . . .
chewing gum               . . . . .
chocolate                 . . . . .
cooking chocolate         . . . . .
specialty chocolate       . . . . .
specialty bar             . . . . .
chocolate marshmallow     . . . . .
candy                     . . . . .
seasonal products         . . . . .
detergent                 . . . . .
softener                  . . . . .
decalcifier               . . . . .
dish cleaner              . . . . .
abrasive cleaner          . . . . .
cleaner                   . . . . .
toilet cleaner            . . . . .
bathroom cleaner          . . . . .
hair spray                . . . . .
dental care               . . . . .
male cosmetics            . . . . .
make up remover           . . . . .
skin care                 . . . . .
female sanitary products  . . . . .
baby cosmetics            . . . . .
soap                      . . . . .
rubbing alcohol           . . . . .
hygiene articles          . . . . .
napkins                   . . . . .
dishes                    . . . . .
cookware                  . . . . .
kitchen utensil           . . . . .
cling film/bags           . . . . .
kitchen towels            . . . . .
house keeping products    . . . . .
candles                   . . . . .
light bulbs               . . . . .
sound storage medium      . . . . .
newspapers                . . . . .
photo/film                . . . . .
pot plants                . . . . .
flower soil/fertilizer    . . . . .
flower (seeds)            . . . . .
shopping bags             . . . . .
bags                      . . . . .

23 Creación de datos transaccionales desde cero

En la práctica, los datos no siempre vienen en formato transactions. Veamos dos formatos habituales.

23.1 Formato cesta o basket

Cada fila contiene una transacción completa.

Mostrar código
datos_basket <- data.frame(
  transaccion = c(1, 2, 3, 4, 5),
  item_1 = c("pan", "pan", "leche", "pan", "queso"),
  item_2 = c("leche", "queso", "huevos", "huevos", "pan"),
  item_3 = c("huevos", NA, NA, "queso", NA)
)

datos_basket
Mostrar código
lista_basket <- datos_basket |>
  select(-transaccion) |>
  apply(1, function(x) na.omit(as.character(x)))

trans_basket <- as(lista_basket, "transactions")
inspect(trans_basket)
    items               
[1] {huevos, leche, pan}
[2] {pan, queso}        
[3] {huevos, leche}     
[4] {huevos, pan, queso}
[5] {pan, queso}        

23.2 Formato largo o single

Cada fila representa un item dentro de una transacción.

Mostrar código
datos_single <- tibble(
  id_compra = c(1, 1, 1, 2, 2, 3, 3, 4, 4, 4),
  item = c("pan", "leche", "huevos", "pan", "queso", "leche", "huevos", "pan", "huevos", "queso")
)

datos_single
Mostrar código
lista_single <- split(datos_single$item, datos_single$id_compra)
trans_single <- as(lista_single, "transactions")
inspect(trans_single)
    items                transactionID
[1] {huevos, leche, pan} 1            
[2] {pan, queso}         2            
[3] {huevos, leche}      3            
[4] {huevos, pan, queso} 4            

23.2.1 Interpretación

El formato largo es muy común cuando los datos proceden de una base de datos relacional. Cada compra puede tener varias filas, una por producto.

24 Reglas sobre variables categóricas

Las reglas de asociación también pueden aplicarse a datos tabulares categóricos, no solo a cestas de compra.

Vamos a construir un ejemplo artificial con clientes.

Mostrar código
set.seed(123)

clientes <- tibble(
  edad = sample(c("joven", "adulto", "senior"), 500, replace = TRUE, prob = c(0.35, 0.45, 0.20)),
  canal = sample(c("web", "tienda", "app"), 500, replace = TRUE, prob = c(0.45, 0.35, 0.20)),
  segmento = sample(c("bajo", "medio", "alto"), 500, replace = TRUE, prob = c(0.40, 0.40, 0.20)),
  compra_premium = sample(c("no", "si"), 500, replace = TRUE, prob = c(0.75, 0.25)),
  usa_cupon = sample(c("no", "si"), 500, replace = TRUE, prob = c(0.65, 0.35))
)

# Introducimos una asociación artificial:
clientes <- clientes |>
  mutate(
    compra_premium = ifelse(edad == "adulto" & canal == "app" & segmento == "alto", "si", compra_premium)
  )

head(clientes)

Para convertir un data.frame categórico a transacciones, cada variable-nivel se convierte en un item.

Mostrar código
clientes_trans <- as(clientes, "transactions")
clientes_trans
transactions in sparse format with
 500 transactions (rows) and
 13 items (columns)
Mostrar código
inspect(clientes_trans[1:5])
    items                transactionID
[1] {edad=adulto,                     
     canal=web,                       
     segmento=medio,                  
     compra_premium=si,               
     usa_cupon=no}                   1
[2] {edad=joven,                      
     canal=web,                       
     segmento=bajo,                   
     compra_premium=si,               
     usa_cupon=no}                   2
[3] {edad=adulto,                     
     canal=web,                       
     segmento=medio,                  
     compra_premium=no,               
     usa_cupon=no}                   3
[4] {edad=senior,                     
     canal=web,                       
     segmento=alto,                   
     compra_premium=no,               
     usa_cupon=no}                   4
[5] {edad=senior,                     
     canal=web,                       
     segmento=alto,                   
     compra_premium=no,               
     usa_cupon=no}                   5
Mostrar código
reglas_clientes <- apriori(
  clientes_trans,
  parameter = list(
    supp = 0.03,
    conf = 0.5,
    minlen = 2
  ),
  appearance = list(
    rhs = "compra_premium=si",
    default = "lhs"
  )
)
Apriori

Parameter specification:
 confidence minval smax arem  aval originalSupport maxtime support minlen
        0.5    0.1    1 none FALSE            TRUE       5    0.03      2
 maxlen target  ext
     10  rules TRUE

Algorithmic control:
 filter tree heap memopt load sort verbose
    0.1 TRUE TRUE  FALSE TRUE    2    TRUE

Absolute minimum support count: 15 

set item appearances ...[1 item(s)] done [0.00s].
set transactions ...[13 item(s), 500 transaction(s)] done [0.00s].
sorting and recoding items ... [13 item(s)] done [0.00s].
creating transaction tree ... done [0.00s].
checking subsets of size 1 2 3 4 5 done [0.00s].
writing ... [0 rule(s)] done [0.00s].
creating S4 object  ... done [0.00s].
Mostrar código
reglas_clientes <- sort(reglas_clientes, by = "lift", decreasing = TRUE)
inspect(head(reglas_clientes, 15))

24.0.1 Interpretación

Este análisis responde a una pregunta de perfilado:

¿Qué combinaciones de atributos se asocian con la compra premium?

Este enfoque puede ser útil para segmentación descriptiva, pero no sustituye a un modelo supervisado si el objetivo principal es predecir.

25 Discretización de variables numéricas

Los algoritmos de reglas de asociación trabajan con items discretos. Si tenemos variables numéricas, debemos convertirlas en intervalos.

Mostrar código
set.seed(321)

datos_num <- tibble(
  edad = round(rnorm(400, mean = 42, sd = 12)),
  gasto = round(rlnorm(400, meanlog = 3.5, sdlog = 0.5), 1),
  visitas = rpois(400, lambda = 4),
  canal = sample(c("web", "tienda", "app"), 400, replace = TRUE)
)

datos_num <- datos_num |>
  mutate(
    gasto_alto = ifelse(gasto > quantile(gasto, 0.75), "si", "no")
  )

head(datos_num)
Mostrar código
datos_discretos <- datos_num |>
  mutate(
    edad_grupo = cut(
      edad,
      breaks = c(-Inf, 30, 50, Inf),
      labels = c("edad_joven", "edad_media", "edad_alta")
    ),
    gasto_grupo = cut(
      gasto,
      breaks = quantile(gasto, probs = c(0, 0.33, 0.66, 1)),
      include.lowest = TRUE,
      labels = c("gasto_bajo", "gasto_medio", "gasto_alto_intervalo")
    ),
    visitas_grupo = cut(
      visitas,
      breaks = c(-Inf, 2, 5, Inf),
      labels = c("visitas_bajas", "visitas_medias", "visitas_altas")
    )
  ) |>
  select(edad_grupo, gasto_grupo, visitas_grupo, canal, gasto_alto)

head(datos_discretos)
Mostrar código
trans_discretas <- as(datos_discretos, "transactions")

reglas_gasto <- apriori(
  trans_discretas,
  parameter = list(
    supp = 0.03,
    conf = 0.5,
    minlen = 2
  ),
  appearance = list(
    rhs = "gasto_alto=si",
    default = "lhs"
  )
)
Apriori

Parameter specification:
 confidence minval smax arem  aval originalSupport maxtime support minlen
        0.5    0.1    1 none FALSE            TRUE       5    0.03      2
 maxlen target  ext
     10  rules TRUE

Algorithmic control:
 filter tree heap memopt load sort verbose
    0.1 TRUE TRUE  FALSE TRUE    2    TRUE

Absolute minimum support count: 12 

set item appearances ...[1 item(s)] done [0.00s].
set transactions ...[14 item(s), 400 transaction(s)] done [0.00s].
sorting and recoding items ... [14 item(s)] done [0.00s].
creating transaction tree ... done [0.00s].
checking subsets of size 1 2 3 4 5 done [0.00s].
writing ... [21 rule(s)] done [0.00s].
creating S4 object  ... done [0.00s].
Mostrar código
reglas_gasto <- sort(reglas_gasto, by = "lift", decreasing = TRUE)
inspect(head(reglas_gasto, 10))
     lhs                                    rhs             support confidence coverage     lift count
[1]  {edad_grupo=edad_alta,                                                                           
      gasto_grupo=gasto_alto_intervalo,                                                               
      canal=web}                         => {gasto_alto=si}  0.0325  0.8666667   0.0375 3.501684    13
[2]  {gasto_grupo=gasto_alto_intervalo,                                                               
      visitas_grupo=visitas_medias,                                                                   
      canal=app}                         => {gasto_alto=si}  0.0525  0.8400000   0.0625 3.393939    21
[3]  {edad_grupo=edad_alta,                                                                           
      gasto_grupo=gasto_alto_intervalo,                                                               
      visitas_grupo=visitas_medias}      => {gasto_alto=si}  0.0425  0.8095238   0.0525 3.270803    17
[4]  {edad_grupo=edad_alta,                                                                           
      gasto_grupo=gasto_alto_intervalo}  => {gasto_alto=si}  0.0800  0.8000000   0.1000 3.232323    32
[5]  {gasto_grupo=gasto_alto_intervalo,                                                               
      canal=app}                         => {gasto_alto=si}  0.0975  0.7500000   0.1300 3.030303    39
[6]  {gasto_grupo=gasto_alto_intervalo,                                                               
      visitas_grupo=visitas_altas}       => {gasto_alto=si}  0.0650  0.7428571   0.0875 3.001443    26
[7]  {gasto_grupo=gasto_alto_intervalo,                                                               
      visitas_grupo=visitas_bajas}       => {gasto_alto=si}  0.0500  0.7407407   0.0675 2.992892    20
[8]  {gasto_grupo=gasto_alto_intervalo}  => {gasto_alto=si}  0.2475  0.7333333   0.3375 2.962963    99
[9]  {edad_grupo=edad_media,                                                                          
      gasto_grupo=gasto_alto_intervalo,                                                               
      canal=app}                         => {gasto_alto=si}  0.0475  0.7307692   0.0650 2.952603    19
[10] {edad_grupo=edad_joven,                                                                          
      gasto_grupo=gasto_alto_intervalo}  => {gasto_alto=si}  0.0400  0.7272727   0.0550 2.938476    16

25.0.1 Interpretación

La discretización transforma variables continuas en categorías interpretables. Sin embargo, la elección de cortes puede afectar mucho a las reglas obtenidas.

Buenas prácticas:

  • usar cortes con sentido de negocio cuando existan;
  • evitar crear demasiados intervalos;
  • comprobar que cada intervalo tenga suficientes observaciones;
  • comparar resultados con diferentes discretizaciones.

26 Diagnóstico de reglas

Una regla interesante debería cumplir varias condiciones:

  1. Soporte suficiente: aparece en un número razonable de casos.
  2. Confianza adecuada: el consecuente aparece a menudo dado el antecedente.
  3. Lift mayor que 1: hay asociación positiva frente a independencia.
  4. Interpretabilidad: la regla se puede explicar de forma clara.
  5. Accionabilidad: se puede tomar una decisión a partir de ella.
  6. No trivialidad: no refleja algo evidente o tautológico.
  7. Estabilidad: se mantiene en diferentes muestras o periodos.

27 Validación mediante partición train/test

Aunque las reglas de asociación son no supervisadas, podemos evaluar si las reglas descubiertas en una muestra siguen teniendo sentido en otra.

Mostrar código
set.seed(123)

idx_train <- sample(seq_along(Groceries), size = round(0.7 * length(Groceries)))
groceries_train <- Groceries[idx_train]
groceries_test <- Groceries[-idx_train]

reglas_train <- apriori(
  groceries_train,
  parameter = list(
    supp = 0.01,
    conf = 0.5,
    minlen = 2
  ),
  control = list(verbose = FALSE)
)

reglas_train <- sort(reglas_train, by = "lift", decreasing = TRUE)
reglas_train_top <- head(reglas_train, 20)

inspect(reglas_train_top)
     lhs                        rhs                   support confidence   coverage     lift count
[1]  {tropical fruit,                                                                             
      root vegetables}       => {other vegetables} 0.01162115  0.6060606 0.01917490 3.101949    80
[2]  {yogurt,                                                                                     
      whipped/sour cream}    => {other vegetables} 0.01089483  0.5102041 0.02135386 2.611334    75
[3]  {root vegetables,                                                                            
      yogurt}                => {other vegetables} 0.01321906  0.5083799 0.02600232 2.601998    91
[4]  {other vegetables,                                                                           
      curd}                  => {whole milk}       0.01133062  0.6000000 0.01888437 2.372430    78
[5]  {pip fruit,                                                                                  
      yogurt}                => {whole milk}       0.01089483  0.5905512 0.01844858 2.335069    75
[6]  {curd,                                                                                       
      yogurt}                => {whole milk}       0.01089483  0.5859375 0.01859384 2.316826    75
[7]  {root vegetables,                                                                            
      yogurt}                => {whole milk}       0.01496223  0.5754190 0.02600232 2.275235   103
[8]  {root vegetables,                                                                            
      whipped/sour cream}    => {whole milk}       0.01002324  0.5750000 0.01743173 2.273578    69
[9]  {tropical fruit,                                                                             
      root vegetables}       => {whole milk}       0.01089483  0.5681818 0.01917490 2.246619    75
[10] {other vegetables,                                                                           
      domestic eggs}         => {whole milk}       0.01176641  0.5436242 0.02164439 2.149517    81
[11] {pip fruit,                                                                                  
      other vegetables}      => {whole milk}       0.01467170  0.5401070 0.02716444 2.135610   101
[12] {other vegetables,                                                                           
      butter}                => {whole milk}       0.01074956  0.5362319 0.02004648 2.120287    74
[13] {tropical fruit,                                                                             
      yogurt}                => {whole milk}       0.01568855  0.5346535 0.02934340 2.114046   108
[14] {yogurt,                                                                                     
      whipped/sour cream}    => {whole milk}       0.01133062  0.5306122 0.02135386 2.098067    78
[15] {other vegetables,                                                                           
      whipped/sour cream}    => {whole milk}       0.01510750  0.5306122 0.02847182 2.098067   104
[16] {other vegetables,                                                                           
      yogurt}                => {whole milk}       0.02382336  0.5256410 0.04532249 2.078411   164
[17] {root vegetables,                                                                            
      rolls/buns}            => {whole milk}       0.01162115  0.5228758 0.02222545 2.067477    80
[18] {other vegetables,                                                                           
      fruit/vegetable juice} => {whole milk}       0.01089483  0.5033557 0.02164439 1.990293    75
Mostrar código
# Evaluación aproximada de calidad en test mediante interestMeasure
medidas_test <- interestMeasure(
  reglas_train_top,
  transactions = groceries_test,
  measure = c("support", "confidence", "lift", "count")
)

medidas_train <- quality(reglas_train_top)[, c("support", "confidence", "lift", "count")]

comparacion <- bind_cols(
  regla = labels(reglas_train_top),
  train_support = medidas_train$support,
  train_confidence = medidas_train$confidence,
  train_lift = medidas_train$lift,
  test_support = medidas_test$support,
  test_confidence = medidas_test$confidence,
  test_lift = medidas_test$lift
)

comparacion |>
  mutate(across(where(is.numeric), ~ round(.x, 4))) |>
  kable(caption = "Comparación de reglas entre train y test") |>
  kable_styling(full_width = FALSE)
Comparación de reglas entre train y test
regla train_support train_confidence train_lift test_support test_confidence test_lift
{tropical fruit,root vegetables} => {other vegetables} 0.0116 0.6061 3.1019 0.0116 0.6061 3.1019
{yogurt,whipped/sour cream} => {other vegetables} 0.0109 0.5102 2.6113 0.0109 0.5102 2.6113
{root vegetables,yogurt} => {other vegetables} 0.0132 0.5084 2.6020 0.0132 0.5084 2.6020
{other vegetables,curd} => {whole milk} 0.0113 0.6000 2.3724 0.0113 0.6000 2.3724
{pip fruit,yogurt} => {whole milk} 0.0109 0.5906 2.3351 0.0109 0.5906 2.3351
{curd,yogurt} => {whole milk} 0.0109 0.5859 2.3168 0.0109 0.5859 2.3168
{root vegetables,yogurt} => {whole milk} 0.0150 0.5754 2.2752 0.0150 0.5754 2.2752
{root vegetables,whipped/sour cream} => {whole milk} 0.0100 0.5750 2.2736 0.0100 0.5750 2.2736
{tropical fruit,root vegetables} => {whole milk} 0.0109 0.5682 2.2466 0.0109 0.5682 2.2466
{other vegetables,domestic eggs} => {whole milk} 0.0118 0.5436 2.1495 0.0118 0.5436 2.1495
{pip fruit,other vegetables} => {whole milk} 0.0147 0.5401 2.1356 0.0147 0.5401 2.1356
{other vegetables,butter} => {whole milk} 0.0107 0.5362 2.1203 0.0107 0.5362 2.1203
{tropical fruit,yogurt} => {whole milk} 0.0157 0.5347 2.1140 0.0157 0.5347 2.1140
{yogurt,whipped/sour cream} => {whole milk} 0.0113 0.5306 2.0981 0.0113 0.5306 2.0981
{other vegetables,whipped/sour cream} => {whole milk} 0.0151 0.5306 2.0981 0.0151 0.5306 2.0981
{other vegetables,yogurt} => {whole milk} 0.0238 0.5256 2.0784 0.0238 0.5256 2.0784
{root vegetables,rolls/buns} => {whole milk} 0.0116 0.5229 2.0675 0.0116 0.5229 2.0675
{other vegetables,fruit/vegetable juice} => {whole milk} 0.0109 0.5034 1.9903 0.0109 0.5034 1.9903

27.0.1 Interpretación

Si una regla tiene lift alto en train pero desaparece en test, puede tratarse de un patrón inestable. En aplicaciones reales, esta validación temporal o por particiones es muy recomendable.

28 Recomendaciones prácticas

28.1 Cómo elegir soporte mínimo

Depende del tamaño de la base de datos y del objetivo.

Si hay pocas transacciones, un soporte demasiado bajo genera reglas basadas en pocos casos. Si hay millones de transacciones, un soporte del 0.1% puede seguir representando miles de casos.

Una regla práctica es traducir soporte a número absoluto:

\[ \text{count mínimo} = n \cdot \text{support mínimo} \]

Por ejemplo, con 10.000 transacciones:

  • soporte 0.01 equivale a 100 transacciones;
  • soporte 0.005 equivale a 50 transacciones;
  • soporte 0.001 equivale a 10 transacciones.

28.2 Cómo elegir confianza mínima

La confianza debe compararse con el soporte del consecuente.

Una confianza del 60% puede parecer alta, pero si el consecuente aparece globalmente en el 80% de las transacciones, la regla no es interesante.

Por eso conviene revisar también lift y leverage.

28.3 Cómo presentar resultados

En una presentación o informe, no conviene mostrar 200 reglas. Es mejor seleccionar entre 5 y 15 reglas representativas y explicar:

  • regla;
  • soporte;
  • confianza;
  • lift;
  • número de casos;
  • interpretación;
  • posible acción.

29 Ejemplo de informe interpretativo

Supongamos que encontramos una regla:

\[ \{\text{yogurt}, \text{tropical fruit}\} \Rightarrow \{\text{whole milk}\} \]

con:

  • soporte = 0.015;
  • confianza = 0.52;
  • lift = 2.05;
  • count = 148.

La interpretación sería:

El 1.5% de todas las cestas contienen simultáneamente yogurt, fruta tropical y leche. Entre las cestas que contienen yogurt y fruta tropical, el 52% también contienen leche. Además, la compra de leche es aproximadamente 2.05 veces más frecuente en estas cestas que lo que cabría esperar si no hubiera asociación entre los productos.

Posible acción:

Se podría probar una recomendación automática de leche cuando el cliente añada yogurt y fruta tropical al carrito, o situar estos productos en zonas próximas si el objetivo es aumentar venta cruzada.

Precaución:

La regla no demuestra causalidad. Antes de tomar decisiones permanentes, convendría validar el patrón en otro periodo o mediante un experimento A/B.

30 Errores frecuentes

30.1 Confundir confianza con causalidad

Una regla con confianza alta no significa que el antecedente cause el consecuente.

30.2 Ignorar el soporte

Una regla con confianza 100% puede estar basada en muy pocas transacciones.

30.3 Ignorar la frecuencia del consecuente

Si el consecuente es muy frecuente, muchas reglas tendrán confianza alta aunque no sean interesantes.

30.4 Mostrar demasiadas reglas

El objetivo no es generar la mayor cantidad posible de reglas, sino encontrar patrones útiles.

30.5 No filtrar reglas redundantes

Muchas reglas pueden ser variaciones mínimas de otras reglas más simples.

30.6 No validar estabilidad

Los patrones pueden cambiar con el tiempo, por temporada, promociones o cambios de catálogo.

31 Ejercicio guiado 1

Con el dataset Groceries:

  1. Genera reglas con soporte mínimo 0.005 y confianza mínima 0.4.
  2. Ordena las reglas por lift.
  3. Filtra las reglas donde el consecuente sea whole milk.
  4. Elimina reglas redundantes.
  5. Selecciona las 10 mejores reglas.
  6. Interpreta soporte, confianza y lift de las 3 primeras.
Mostrar código
reglas_ejercicio <- apriori(
  Groceries,
  parameter = list(
    supp = 0.005,
    conf = 0.4,
    minlen = 2
  ),
  appearance = list(
    rhs = "whole milk",
    default = "lhs"
  )
)
Apriori

Parameter specification:
 confidence minval smax arem  aval originalSupport maxtime support minlen
        0.4    0.1    1 none FALSE            TRUE       5   0.005      2
 maxlen target  ext
     10  rules TRUE

Algorithmic control:
 filter tree heap memopt load sort verbose
    0.1 TRUE TRUE  FALSE TRUE    2    TRUE

Absolute minimum support count: 49 

set item appearances ...[1 item(s)] done [0.00s].
set transactions ...[169 item(s), 9835 transaction(s)] done [0.00s].
sorting and recoding items ... [120 item(s)] done [0.00s].
creating transaction tree ... done [0.00s].
checking subsets of size 1 2 3 4 done [0.00s].
writing ... [169 rule(s)] done [0.00s].
creating S4 object  ... done [0.00s].
Mostrar código
reglas_ejercicio <- reglas_ejercicio[!is.redundant(reglas_ejercicio)]
reglas_ejercicio <- sort(reglas_ejercicio, by = "lift", decreasing = TRUE)

inspect(head(reglas_ejercicio, 10))
     lhs                     rhs              support confidence    coverage     lift count
[1]  {tropical fruit,                                                                      
      root vegetables,                                                                     
      yogurt}             => {whole milk} 0.005693950  0.7000000 0.008134215 2.739554    56
[2]  {pip fruit,                                                                           
      root vegetables,                                                                     
      other vegetables}   => {whole milk} 0.005490595  0.6750000 0.008134215 2.641713    54
[3]  {butter,                                                                              
      whipped/sour cream} => {whole milk} 0.006710727  0.6600000 0.010167768 2.583008    66
[4]  {pip fruit,                                                                           
      whipped/sour cream} => {whole milk} 0.005998983  0.6483516 0.009252669 2.537421    59
[5]  {butter,                                                                              
      yogurt}             => {whole milk} 0.009354347  0.6388889 0.014641586 2.500387    92
[6]  {root vegetables,                                                                     
      butter}             => {whole milk} 0.008235892  0.6377953 0.012913066 2.496107    81
[7]  {tropical fruit,                                                                      
      curd}               => {whole milk} 0.006507372  0.6336634 0.010269446 2.479936    64
[8]  {pip fruit,                                                                           
      other vegetables,                                                                    
      yogurt}             => {whole milk} 0.005083884  0.6250000 0.008134215 2.446031    50
[9]  {pip fruit,                                                                           
      domestic eggs}      => {whole milk} 0.005388917  0.6235294 0.008642603 2.440275    53
[10] {tropical fruit,                                                                      
      butter}             => {whole milk} 0.006202339  0.6224490 0.009964413 2.436047    61

32 Ejercicio guiado 2

Estudia qué productos están relacionados con yogurt.

Mostrar código
reglas_yogurt_2 <- apriori(
  Groceries,
  parameter = list(
    supp = 0.005,
    conf = 0.3,
    minlen = 2
  )
)
Apriori

Parameter specification:
 confidence minval smax arem  aval originalSupport maxtime support minlen
        0.3    0.1    1 none FALSE            TRUE       5   0.005      2
 maxlen target  ext
     10  rules TRUE

Algorithmic control:
 filter tree heap memopt load sort verbose
    0.1 TRUE TRUE  FALSE TRUE    2    TRUE

Absolute minimum support count: 49 

set item appearances ...[0 item(s)] done [0.00s].
set transactions ...[169 item(s), 9835 transaction(s)] done [0.00s].
sorting and recoding items ... [120 item(s)] done [0.00s].
creating transaction tree ... done [0.00s].
checking subsets of size 1 2 3 4 done [0.00s].
writing ... [482 rule(s)] done [0.00s].
creating S4 object  ... done [0.00s].
Mostrar código
reglas_yogurt_2 <- subset(reglas_yogurt_2, items %in% "yogurt")
reglas_yogurt_2 <- reglas_yogurt_2[!is.redundant(reglas_yogurt_2)]
reglas_yogurt_2 <- sort(reglas_yogurt_2, by = "lift", decreasing = TRUE)

inspect(head(reglas_yogurt_2, 15))
     lhs                        rhs                   support confidence   coverage     lift count
[1]  {root vegetables,                                                                            
      whole milk,                                                                                 
      yogurt}                => {tropical fruit}  0.005693950  0.3916084 0.01453991 3.732043    56
[2]  {tropical fruit,                                                                             
      curd}                  => {yogurt}          0.005287239  0.5148515 0.01026945 3.690645    52
[3]  {other vegetables,                                                                           
      whole milk,                                                                                 
      fruit/vegetable juice} => {yogurt}          0.005083884  0.4854369 0.01047280 3.479790    50
[4]  {tropical fruit,                                                                             
      whole milk,                                                                                 
      yogurt}                => {root vegetables} 0.005693950  0.3758389 0.01514997 3.448112    56
[5]  {tropical fruit,                                                                             
      root vegetables,                                                                            
      whole milk}            => {yogurt}          0.005693950  0.4745763 0.01199797 3.401937    56
[6]  {pip fruit,                                                                                  
      yogurt}                => {tropical fruit}  0.006405694  0.3559322 0.01799695 3.392048    63
[7]  {other vegetables,                                                                           
      whole milk,                                                                                 
      yogurt}                => {tropical fruit}  0.007625826  0.3424658 0.02226741 3.263712    75
[8]  {other vegetables,                                                                           
      whole milk,                                                                                 
      yogurt}                => {root vegetables} 0.007829181  0.3515982 0.02226741 3.225716    77
[9]  {tropical fruit,                                                                             
      whipped/sour cream}    => {yogurt}          0.006202339  0.4485294 0.01382816 3.215224    61
[10] {tropical fruit,                                                                             
      other vegetables,                                                                           
      whole milk}            => {yogurt}          0.007625826  0.4464286 0.01708185 3.200164    75
[11] {root vegetables,                                                                            
      yogurt}                => {tropical fruit}  0.008134215  0.3149606 0.02582613 3.001587    80
[12] {yogurt,                                                                                     
      bottled water}         => {tropical fruit}  0.007117438  0.3097345 0.02297916 2.951782    70
[13] {curd,                                                                                       
      yogurt}                => {tropical fruit}  0.005287239  0.3058824 0.01728521 2.915071    52
[14] {whole milk,                                                                                 
      cream cheese }         => {yogurt}          0.006609049  0.4012346 0.01647178 2.876197    65
[15] {yogurt,                                                                                     
      whipped/sour cream}    => {root vegetables} 0.006405694  0.3088235 0.02074225 2.833283    63

32.0.1 Preguntas

  • ¿Aparece yogurt más a menudo en el antecedente o en el consecuente?
  • ¿Qué reglas tienen mayor lift?
  • ¿Alguna regla parece trivial?
  • ¿Qué acción comercial se podría derivar?

33 Resumen final

Las reglas de asociación son una herramienta potente para descubrir patrones de coocurrencia en datos transaccionales o categóricos. Su principal fortaleza es la interpretabilidad: producen reglas fáciles de comunicar.

Sin embargo, deben utilizarse con cuidado. El analista debe evitar interpretar automáticamente las reglas como relaciones causales y debe considerar simultáneamente varias métricas.

Las ideas clave son:

  • el soporte mide frecuencia global del patrón;
  • la confianza mide frecuencia condicional;
  • el lift compara la regla con lo esperado bajo independencia;
  • el leverage mide diferencia absoluta frente a independencia;
  • la coverage indica cuántos casos activa el antecedente;
  • Apriori usa poda para reducir el espacio de búsqueda;
  • Eclat usa representación vertical e intersecciones;
  • la visualización y el filtrado son esenciales para interpretar resultados;
  • la validación en otra muestra ayuda a detectar reglas inestables.

34 Bibliografía y recursos recomendados

  • Agrawal, R., Imieliński, T., & Swami, A. (1993). Mining association rules between sets of items in large databases. Proceedings of the ACM SIGMOD International Conference on Management of Data.
  • Hahsler, M., Grün, B., & Hornik, K. (2005). arules: A computational environment for mining association rules and frequent item sets. Journal of Statistical Software.
  • Hahsler, M. (2017). arulesViz: Interactive visualization of association rules with R. The R Journal.
  • Han, J., Pei, J., & Yin, Y. (2000). Mining frequent patterns without candidate generation. ACM SIGMOD.
  • Zaki, M. J. (2000). Scalable algorithms for association mining. IEEE Transactions on Knowledge and Data Engineering.
  • Amat Rodrigo, J. (2018). Reglas de asociación y algoritmo Apriori con R. Ciencia de Datos.

Aquesta web està creada por Dante Conti y Sergi Ramírez, (c) 2026