Using \(g(\mu)=\log(\frac{\mu}{1-\mu})\) and \(f(y)=p^y(1-p)^{1-y}\), find the maximum likelihood estimates for the simulated data from the previous slide using the optim function.
1llb <- \(x, y, beta){2 eta <- beta[1] + beta[2] * x3 p <-inv_logit(eta)4 ll <- y *log(p) + (1- y) *log(1- p)5return(-sum(ll))}6optim(c(0,0), llb, x = x, y = y)
1
Creating a function called llb for log-likelihood
2
Constructing linear model
3
Obtaining inverse logit value for linear model
4
Obtaining individual log-likelihood values
5
Returning log-likelihood value based of the sum for all observation, returning a negative value for optim
6
Using optim to find the values for \(\hat {\boldsymbol \beta}\)
$par
[1] 2.697667 -7.624155
$value
[1] 137.0459
$counts
function gradient
67 NA
$convergence
[1] 0
$message
NULL
Source Code
---title: "Lecture 18 Code"editor: visualformat: html: code-tools: true---## Binary SimulationLet $Y_i\overset{iid}{\sim}Bernoulli(p_i)$ with $p_i=g^{-1}(\boldsymbol X_i^\mathrm T\boldsymbol \beta)$```{r}logit <- \(x){log(x/(1-x))} # <1>inv_logit <- \(x){exp(x)/(1+exp(x))} # <2>x <-rnorm(1000, 1) # <3>eta <-3-8* x # <4>y <-sapply(eta, \(x) rbinom(1, 1, inv_logit(x))) # <5>```1. Creating logit function2. Creating inverse logit function3. Simulating predictors from $N(2,1)$4. Constructing linear model5. Simulating outcome## Binary ModelUsing $g(\mu)=\log(\frac{\mu}{1-\mu})$ and $f(y)=p^y(1-p)^{1-y}$, find the maximum likelihood estimates for the simulated data from the previous slide using the `optim` function.$$\ell(\boldsymbol\beta) = \sum^n_{i=1} y_i \log(p_i) + (1-y_i)\log(1-p_i)$$- $p_i = g^{-1}(\boldsymbol X^\mathrm T\boldsymbol \beta)$## Code```{r}llb <- \(x, y, beta){ # <1> eta <- beta[1] + beta[2] * x # <2> p <-inv_logit(eta) # <3> ll <- y *log(p) + (1- y) *log(1- p) # <4>return(-sum(ll)) # <5>}optim(c(0,0), llb, x = x, y = y) # <6>```1. Creating a function called `llb` for log-likelihood2. Constructing linear model3. Obtaining inverse logit value for linear model4. Obtaining individual log-likelihood values5. Returning log-likelihood value based of the sum for all observation, returning a negative value for `optim`6. Using `optim` to find the values for $\hat {\boldsymbol \beta}$