-
Notifications
You must be signed in to change notification settings - Fork 0
/
104_mnlogit.Rmd
62 lines (40 loc) · 1.12 KB
/
104_mnlogit.Rmd
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
# Multinomial Logit
<!-- Discussion of the model goes here -->
```{r}
mnlogit <- function(data, formula) {
mf <- model.frame(formula, data, na.action=na.exclude)
y <- model.response(mf)
X <- model.matrix(formula, mf)
N <- nrow(X)
K <- ncol(X)
levels <- unique(y) |> sort()
M <- length(levels)
Y <- matrix(N*M, nrow=N, ncol=M)
for (m in 1:M) {
Y[,m] <- ifelse(y==levels[m], 1, 0)
}
b <- numeric(K*(M-1))
mnlogitLL <- function(param) {
b <- matrix(param, nrow=K, ncol=M-1)
Xb <- cbind(rep(0, N), X %*% b)
lli <- numeric(N)
for (m in 1:M) {
lli <- lli + Y[,m]*Xb[,m] - Y[,m]*log(rowSums(exp(Xb)))
}
return(-sum(lli))
}
out <- optim(b, mnlogitLL, method="BFGS")
est <- matrix(out$par, nrow=K, ncol=M-1)
rownames(est) <- colnames(X)
colnames(est) <- paste0(levels[1], "/", levels[2:M])
return(est)
}
```
Testing the function:
```{r}
library(mclogit)
housing <- MASS::housing #has an ordinal outcome but we'll ignore that for our purposes
f <- Sat ~ Infl + Freq + Type
t(mblogit(f, data = housing)$coefmat)
mnlogit(housing, f)
```