-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.qmd
595 lines (441 loc) · 22.1 KB
/
index.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
---
title: "Choice of Brand for Crackers"
author: "Mario Camacho"
date: "08-10-2024"
date-modified: last-modified
date-format: "DD MMMM YYYY"
lang: es
abstract: |
Nos adentramos en los modelos de respuesta múltiple nominal con medidas repetidas. Se demuestra que incluir efectos aleatorios es necesario para tener un buen ajuste ya que esta correlación entre observaciones es importante recogerla dentro del modelo.
keywords: ["respuesta múltiple", "convergenia modelos", "respuesta nominal", "efectos aleatorios", "medidas repetidas"]
format:
html:
toc: TRUE
toc-title: "Índice"
toc-location: left
toc-expand: TRUE
theme: css/style.css
editor: visual
page-layout: full
knitr:
opts_chunk:
R.options:
width: 110
code-fold: true
warning: false
---
```{r}
#| output: false
#| code-fold: false
library(tidyverse)
library(RColorBrewer)
library(ggridges)
library(ggstance)
library(Ecdat)
library(rpivotTable)
library(VGAM)
library(mclogit)
library(car)
```
# Database
## Descripción
En este caso de uso utilizamos la base de datos Cracker del paquete Ecdat sobre la elección de un individuo de una marca de galletas saladas entre cuatro opciones posibles. (Sunshine, Kleebler, Nabisco y Private)
La base de datos contiene 3.292 registros y dentro de cada fila tenemos:
- **id**: individuals identifiers\
- **choice**: one of sunshine, kleebler, nabisco, private\
- **disp.z**: is there a display for brand z ?\
- **feat.z**: is there a newspaper feature advertisement for brand z ?\
- **price.z**: price of brand z
```{r}
summary(Cracker)
```
## Datos por individuo
Se han recogido datos de 136 individuos. Cada individuo tiene de media 21 registros.
```{r}
Cracker |> select(id) |> table() |> as.data.frame() |> select(Freq) |> summary()
```
Tomamos de ejemplo algunos de los registros del id 1.
```{r}
Cracker |> filter(id==1) |> head(5)
```
## Distribución de las preferencias
Para cada usuario contamos el número de veces que ha elegido cada una de las marcas.
```{r}
data_0 <-
Cracker |> select(id, choice) |> group_by_all() |> count(,.drop = FALSE) |> ungroup() |> mutate(p = n/sum(n), .by=id) |>
#mutate(scale = scale(p, scale = FALSE), .by=id) |>
arrange(id,-n) |> mutate(preference = row_number(), .by=id)
```
El individuo 1 ha elegido la marca Nabisco en el 87.5 % de las veces.
```{r}
#| echo: false
data_0 |> head(8)
```
La distribución de la preferencia de cada marca:
```{r}
#| layout-ncol: 3
data_0 |> select(choice, preference) |> table() |> addmargins()
round(
data_0 |> select(choice, preference) |> table() |> prop.table(1)*100, 2
) |> addmargins()
```
## Escala
Creamos una escala teniendo en cuenta las preferencias del individuo e incluyendo el porcentaje de veces que elige cada una de las marcas sobre el total de sus elecciones.
```{r}
data_1 <-
data_0 |> mutate(scale = scale(p, scale = FALSE), .by=id)
```
Esta escala tiene una relación directa con la proporción de cada una de las elecciones. Se mueve entre los valores -0.25 y 0.75.
- El valor -0.25 si esa marca nunca ha sido elegida por el individuo (p=0).
- El valor 0.75 si es la única marca elegida por el usuario (p=1).
```{r}
data_1 |> select(choice, p, scale) |> summary()
```
Si las elecciones fueran fruto del azar, cada marca sería elegida un 25 % por cada individuo. Con la escala creado cuantificamos cuánto se desvía la proporción de cada elección sobre este porcentaje esperado.
```{r}
data_1 |> filter(id==1)
```
Los individuos 7 y 123 han hecho un total de 17 elecciones siendo su marca preferida Nabisco.
```{r}
data_1 |> filter(id %in% c(7,123))
```
# Análisis exploratorio
```{r}
paleta_choice <- c("lightsalmon", "darkolivegreen3", "lightblue", "mediumorchid")
```
## Eliminación datos confusos
Existen tres registros donde el precio de la marca Nabisco es cero. Puede deberse a alguna oferta que no tengamos recogida o error en los datos. Eliminamos estos registros
```{r}
#| echo: fenced
Cracker |> filter(price.nabisco==0) |> select(c(contains('nabisco'),'choice'))
Cracker_clean <- Cracker |> filter(price.nabisco>0)
```
## Distribución del precio
```{r}
summary(Cracker_clean |> select(contains('price')))
```
Definimos el precio de la marca elegida por el usuario y lo enfrentamos al precio medio de las elecciones que tenía el individuo.
```{r}
data_2 <- Cracker_clean |> mutate(precio_medio = (price.sunshine + price.kleebler + price.nabisco + price.private) / 4,
precio_preferencia = case_when(choice == "sunshine" ~ price.sunshine,
choice == "kleebler" ~ price.kleebler,
choice == "nabisco" ~ price.nabisco,
choice == "private" ~ price.private),
id=factor(id))
# |>
#select(precio_preferencia, precio_medio, id, choice)
```
La marca Private casi siempre tiene un precio superior al precio medio de las cuatro marcas cuando es la marca que el individuo prefiere. Aquellos casos donde la marca elegida es la marca Nabisco, el precio de esta elección casi siempre es inferior al precio medio de las cuatro marcas.
```{r}
#| out-width: 80%
data_2 |> ggplot() + geom_point(aes(x=precio_preferencia, y=precio_medio, colour = factor(choice))) +
geom_abline(intercept = 0) + xlim(30, 150) + ylim(30, 150) +
xlab("Precio de la marca escogida (choice)") +
ylab("Precio medio de las cuatro marcas")+
scale_color_manual(values = paleta_choice) +
labs(colour="choice")
```
Tenemos la distribución del precio para cada una de las marcas y marcamos la media del precio de cada una de ellas. Las marcas Sunshine y Klebbe son bimodales.
```{r}
#| out-width: 80%
Cracker_clean |> select(contains("price")) |> head() |> pivot_longer(cols = c(price.sunshine,price.kleebler ,price.nabisco ,price.private), names_to = "Marca", values_to = "Precio") |> ggplot(aes(x = Precio, y = Marca, fill=Marca)) +
geom_density_ridges(quantile_lines=TRUE, quantile_fun=function(Precio,...)mean(Precio),
jittered_points = TRUE, position = "raincloud", scale = 0.9,
aes(point_color = Marca, point_fill = Marca, point_shape = Marca)) +
stat_summaryh(fun.x=median,
geom="text",
aes(label=sprintf("%1.1f", ..x..)),
position=position_nudge(y=-0.1),
colour="black",
size=3.5) +
scale_fill_manual(values = paleta_choice) +
labs(fill="",color="",
title = "Density Ridges del precio",
subtitle = "se incluyen las medianas")
```
# Modelo predictivo
## Objetivo
Queremos predecir la preferencia de un individuo entre cuatro posibles marcas de galletas saladas en función de las características de venta de cada una de las marcas.
## Enfoque del modelo
La variable respuesta es la variable *choice*. Una variable nominal con cuatro categorías que identifica la marca preferida de cada individuo.
Tenemos dos variables dicotómicas para cada marca. La variable *display* indica si la marca tenía un display o no. Y la variable *feat* indica si había un anuncio en el periódico o no.
También la variable continua *price* sobre el precio de la marca.
## Train y test
Separamos mediante un muestreo estratificado (estrato: usuario) el 10 % de los datos para testear el modelo.
```{r}
set.seed(1234)
Cracker_clean <- Cracker_clean |> mutate(r=row_number())
test_0 <- Cracker_clean |>
slice_sample(prop = 0.10, by = c(id))
train_0 <- anti_join(Cracker_clean, test_0, by='r') |> select(-r)
```
## Modelo respuesta múltiple nominal
Usamos la librería VGAM para un modelo repuesta múltiple nominal.
Previamente debemos elegir una categoría de referencia. El resultado del modelo indicará cómo de probable es la elección de cada una de las tres marcas en relación a la categoría de referencia para cada individuo en función.
*Se elige como referencia el nivel "Private".*
[**Modelo 1**]{.underline}
Modelo saturado.
```{r}
#| collapse: true
modelo1 <- vglm((choice) ~ disp.sunshine + disp.kleebler + disp.nabisco + disp.private + feat.sunshine +
feat.kleebler + feat.nabisco + feat.private + price.sunshine + price.kleebler + price.nabisco + price.private,
family=multinomial(refLevel='private'),
data = train_0)
summary(modelo1)
```
[**Modelo 2**]{.underline}
Sin las variables disp.sunshine y feat.sunshine, ya que son las únicas variables no significativas para las tres marcas. ("los tres modelos")
```{r}
#| collapse: true
modelo2 <- vglm((choice) ~ disp.kleebler + disp.nabisco + disp.private +
feat.kleebler + feat.nabisco + feat.private + price.sunshine + price.kleebler + price.nabisco + price.private,
family=multinomial(refLevel='private'),
data = train_0)
summary(modelo2)
```
[**Coeficientes modelo 2**]{.underline}
No existen más variables que no sean significativas a la hora de comparar la probabilidad de preferencias de cada una de las tres marcas contra la marca de referencia.
```{r}
coef(modelo2, matrix = TRUE)
```
```{r}
#| out-width: 100%
mycol <- c("red","darkgreen","blue")
par(mfrow=c(1,3))
plotvgam(modelo2, se=TRUE, scale=12,
lcol=mycol[1], scol=mycol[1], which.term=1, ylim = c(-1, 1))
plotvgam(modelo2, se=TRUE, scale=12,
lcol=mycol[2], scol=mycol[2], which.term=2, ylim = c(-1, 1))
plotvgam(modelo2, se=TRUE, scale=12,
lcol=mycol[3], scol=mycol[3], which.term=3, ylim = c(-1, 1))
```
### Test modelo 2 {.underline}
La predicción del modelo nos devuelte el valor *response* o el valor *link*.
El valor *link* compara la probabilidad de elección de cada marca en comparación con la marca de referencia. Es decir, para cada nivel de la variable respuesta la predicción nos indica si es menos probable que la marca de referencia (valor menor a 0), igual de probable (valor igual a 0) o más probable (valor mayor a 0).
El valor *response* nos devuelve la probabilidad de elección de cada marca.
```{r}
#| layout-ncol: 2
predictvglm(modelo2, newdata = test_0, type = "link") |> head()
predictvglm(modelo2, newdata = test_0, type = "response") |> head()
```
En el primer caso, como log(mu\[,1\]/mu\[,4\]) es menor a 0, sabemos que la probabilidad de que el usuario escoja la marca sunshine es menor que la probabilidad de escoger la marca private. $\exp(-2.9901208)$ = `r exp(-2.9901208)`\
$\frac{0.01433895}{0.2851743}$ = `r 0.01433895 / 0.2851743`
```{r}
pred <-
predictvglm(modelo2, newdata = train_0,
type = "response",
se.fit = FALSE, deriv = 0, dispersion = NULL,
untransform = FALSE)
pred <-
cbind(
pred |> as.data.frame() |> mutate(id=row_number()) |> pivot_longer(names_to = "category", cols = c(sunshine,kleebler,nabisco,private)) |> slice_max(value, n=1, by = (id)),
choice = train_0$choice) |> mutate(category=as.factor(category))
```
La tasa de acierto es muy baja.
```{r}
caret::confusionMatrix(data=pred$category, reference = pred$choice)
```
## Modelo respuesta múltiple nominal medidas repetidas
Hasta el momento no hemos tenido en cuenta en el modelo predictivo que estamos usando información con medidas repetidas, ya que para cada usuario tenemos más de un evento donde ha elegido entre las cuatro marcas.
El modelo saturado inicial cuenta con una parte aleatoria. \* Intersección aleatorioa. Cada usuario tiene su valor base en la relación entre la variable respuesta y las variables independientes. \* Pendiente aleatoria. La relación entre cada una de las variables dependientes y la variable independiente será diferente para cada usuario. La relación entre cada variable dependiente y la dependiente puede ser diferente para cada usuario.
[**Modelo 3**]{.underline}
Modelo saturado.
```{r}
#| collapse: true
modelo3 <- mblogit(relevel(choice, ref = "private") ~ disp.sunshine + disp.kleebler + disp.nabisco + disp.private + feat.sunshine +
feat.kleebler + feat.nabisco + feat.private + price.sunshine + price.kleebler + price.nabisco + price.private,
random = ~ 1 | id,
data = train_0,
control = mmclogit.control(epsilon = 1e-10,
maxit = 50, trace=TRUE, # Intento aumentar número de iteraciones para que converga
trace.inner=FALSE,
avoid.increase = FALSE,
break.on.increase = FALSE,
break.on.infinite = FALSE,
break.on.negative = FALSE))
#summary(modelo3)
```
```{r}
pred <-
predict(modelo3, test_0, type="response")
pred <-
cbind(
pred |> as.data.frame() |> mutate(id=row_number()) |> pivot_longer(names_to = "category", cols = c(sunshine,kleebler,nabisco,private)) |> slice_max(value, n=1, by = (id)),
choice = test_0$choice) |> mutate(category=as.factor(category))
```
El modelo mblogit usa un proceso iterativo para ajustar los parámetros del modelo. El algoritmo busca minimizar o maximizar una función objetivo (verosimilitud del modelo).
La convergencia se alcanza en el punto donde los cambios en los parámetros de una iteración a la siguiente son lo suficientemente pequeños como para considerar que el proceso ha encontrado una solución óptima.
Podemos tener casos donde el algortimo nos advierte de que no ha encontrado esta convergencia. Posibles causas:
- **Multicolinealidad.** Una alta correlación entre las variables independientes puede hacer que el modelo tenga dificultades para encontrar una solución estable.
- **Datos desbalanceados.** Si los datos están muy desbalanceados puede provocar que el modelo tenga problemas para converger.
- **Valores atípicos.** El ruido en los datos pueden interferir con el proceso de convergencia.
- **Modelo demasiado complejo.** Un modelo demasiado complejo o mal especificado puede dificultar la convergencia.
- **Escalado de variables.** Variables en escalas muy diferentes pueden causar problemas de convergencia.
En este punto tenemos tres posibles formas de resolver el problema:
- Verificar la multicolinealidad. Usar el VIF para verificar si las variables independientes están correlacionadas.
- Escalar las variables. Tenemos variables dicotómicas y variables contínuas de precio.
- Aumenta el número de iteraciones o ajusta la tolerancia. (En realidad hemos bajado el número de iteraciones en el modelo3 para encontrarnos con este problema)
### VIF
El VIF está basado en la suposición de un modelo lineal.
Cuando la variable respuesta es categórica, no podemos calcular directamente el VIF. Sin embargo, podemos evaluar la multicolinealidad entre las variables independientes antes de ajustar el modelo usando un modelo lineal auxiliar donde se trata una de las variables independientes como la variable respuesta.
1. Ignoramos la variable categórica respuesta. La multicolinealidad es un problema que afecta a las relaciones entre las variables independientes. La variable respuesta categórica no influye en la multicolinealidad entre las predictoras.
2. Ajustamos un modelo de regresión lineal donde cada una de las variables independientes es la variable dependiente del modelo lineal.
3. Calcular el VIF para cada variable independiente.
```{r}
#| include: false
vif_values1 <- vif(lm(price.sunshine ~ ., data = train_0 |> select(-c(id,choice))))
vif_values2 <- vif(lm(price.nabisco ~ ., data = train_0 |> select(-c(id,choice))))
vif_values3 <- vif(lm(price.private ~ ., data = train_0 |> select(-c(id,choice))))
vif_values4 <- vif(lm(price.kleebler ~ ., data = train_0 |> select(-c(id,choice))))
# Una manera más estructurada de ver los VIF
#vif_dataframe <- data.frame(Variable = names(vif_values), VIF = vif_values) |> arrange(-VIF)
vif_dataframe <- rbind(
data.frame(target = "price.sunshine", Variable = names(vif_values1), VIF = vif_values1),
data.frame(target = "price.nabisco", Variable = names(vif_values2), VIF = vif_values2),
data.frame(target = "price.private", Variable = names(vif_values3), VIF = vif_values3),
data.frame(target = "price.kleebler", Variable = names(vif_values4), VIF = vif_values4)) |> arrange(-VIF)
rownames(vif_dataframe) = NULL
vif_dataframe |> head(10)
```
### Escalado de variables
[**Escalado:**]{.underline}
```{r}
# Escalado del conjunto de entrenamiento
train_1 <- train_0 |> mutate(price.sunshine = scale(price.sunshine),
price.kleebler = scale(price.kleebler),
price.nabisco = scale(price.nabisco),
price.private = scale(price.private))
summary(train_1)
```
[**Normalización:**]{.underline}
```{r}
# Normalizado del conjunto de entrenamiento
normalizar <- function(x) {
min_values <- min(x)
max_values <- max(x)
(x - min_values) / (max_values - min_values)
}
train_2 <- train_0 |> mutate(price.sunshine = normalizar(price.sunshine),
price.kleebler = normalizar(price.kleebler),
price.nabisco = normalizar(price.nabisco),
price.private = normalizar(price.private))
summary(train_2)
```
```{r}
#| collapse: true
modelo3_escalado <- mblogit(relevel(choice, ref = "private") ~ disp.sunshine + disp.kleebler + disp.nabisco + disp.private + feat.sunshine +
feat.kleebler + feat.nabisco + feat.private + price.sunshine + price.kleebler + price.nabisco + price.private,
random = ~ 1 | id,
data = train_2,
control = mmclogit.control(epsilon = 1e-10,
maxit = 50, trace=TRUE, # Intento aumentar número de iteraciones para que converga
trace.inner=FALSE,
avoid.increase = FALSE,
break.on.increase = FALSE,
break.on.infinite = FALSE,
break.on.negative = FALSE))
#summary(modelo3)
```
### Test modelo3 {.underline}
En este caso los resultados del modelo3 y el modelo3_escalado son los mismos y solo cambia el valor de los parámetros.
```{r}
test_2 <- test_0 |> mutate(price.sunshine = normalizar(price.sunshine),
price.kleebler = normalizar(price.kleebler),
price.nabisco = normalizar(price.nabisco),
price.private = normalizar(price.private))
```
```{r}
pred <-
predict(modelo3, train_0, type="response")
pred <-
cbind(
pred |> as.data.frame() |> mutate(id=row_number()) |> pivot_longer(names_to = "category", cols = c(sunshine,kleebler,nabisco,private)) |> slice_max(value, n=1, by = (id)),
choice = train_0$choice) |> mutate(category=as.factor(category))
pred_escalado <-
predict(modelo3_escalado, train_2, type="response")
pred_escalado <-
cbind(
pred_escalado |> as.data.frame() |> mutate(id=row_number()) |> pivot_longer(names_to = "category", cols = c(sunshine,kleebler,nabisco,private)) |> slice_max(value, n=1, by = (id)),
choice = train_0$choice) |> mutate(category=as.factor(category))
```
```{r}
data.frame(Coefficientes = names(modelo3$coefficients), modelo3 = modelo3$coefficients, modelo3_escalado = modelo3_escalado$coefficients, row.names = NULL) |> head()
```
```{r}
caret::confusionMatrix(data=pred$category, reference = pred$choice)
```
```{r}
caret::confusionMatrix(data=pred_escalado$category, reference = pred_escalado$choice)
```
### Modelo final
[**Modelo 4**]{.underline}
Eliminamos los siguientes parámetros en orden. El criterio de eliminación es no incluir parámetros no significativos para ninguno de los tres modelos. Tras eliminar un parámetro se vuelve a evaluar el modelo.\
- intercepto\
- disp.nabisco\
- disp.private\
- disp.kleebler\
- feat.nabisco
```{r}
#| collapse: true
modelo4 <- mblogit(relevel(choice, ref = "private") ~ disp.sunshine + feat.sunshine +
feat.kleebler + feat.private + price.sunshine + price.kleebler + price.nabisco + price.private -1,
random = ~ 1 | id,
data = train_0,
control = mmclogit.control(epsilon = 1e-08,
maxit = 100, trace=FALSE, # Intento aumentar número de iteraciones para que converga
trace.inner=FALSE,
avoid.increase = FALSE,
break.on.increase = FALSE,
break.on.infinite = FALSE,
break.on.negative = FALSE))
summary(modelo4)
```
[**Test**]{.underline}
```{r}
pred <-
predict(modelo4, train_0, type="response")
pred <-
cbind(
pred |> as.data.frame() |> mutate(id=row_number()) |> pivot_longer(names_to = "category", cols = c(sunshine,kleebler,nabisco,private)) |> slice_max(value, n=1, by = (id)),
choice = train_0$choice) |> mutate(category=as.factor(category))
```
```{r}
caret::confusionMatrix(data=pred$category, reference = pred$choice)
```
```{r}
#| layout-ncol: 2
predict(modelo4, newdata = test_0, type = "link") |> head()
predict(modelo4, newdata = test_0, type = "response") |> head()
```
$\exp(0.2067485)$ = `r exp(0.2067485)`\
$\frac{0.009972645}{0.008109995}$ = `r 0.009972645 / 0.008109995`
## Efectos aleatorios
```{r}
random_effects <- matrix(unlist(modelo4$random.effects[1]), ncol=3)
random_effects |> head()
```
### Comparación individuos
Seleccionamos dos individuos que se hayan encontrado en el mismo escenario y el resultado de su elección haya sido la misma.
Los individuos 103 y 27 son un ejemplo de dos individuos con un escenario idéntico donde eligen la misma marca.
```{r}
#| out-width: 50%
user_103 <- Cracker_clean |> filter(id==103) |> filter(price.sunshine<60) |> filter(price.kleebler<100) |> select(-c(r))
user_27 <- Cracker_clean |> filter(id==27) |> filter(price.sunshine<60) |> filter(price.kleebler<100) |> select(-c(r))
cbind(t(user_103),t(user_27)) |> as.data.frame() |> unname()
```
Si obtenemos las predicciones para estos dos individuos donde todas sus variables son idénticas, las predicciones son distintas.
```{r}
setNames(
data.frame(
t(data.frame(c(103,predict(modelo4, user_103)),
c(27,predict(modelo4, user_27))))
,row.names = NULL),
c("id","sunshine","kleebler","nabisco"))
```
Esto se debe a los efectos aleatorios asociados a cada individuo, los cuales hacen que cada individuo tenga un comportamiento específico de él mismo.
```{r}
random_effects[c(103, 27),]
```
# Bibliografía
<https://www.jstor.org/stable/1392088>
<https://www.jstatsoft.org/article/view/v032i10>