```{r, message=FALSE, warning=FALSE, echo=FALSE}
require(knitr)
opts_chunk$set(eval=TRUE, cache=TRUE)
```

```{r, message=FALSE}
library(tidyverse)
library(Stat2Data)
library(skimr)
library(mosaicData)
# install.packages("lmtest")
```


Often, we want to model a **response** variable that is **binary**, meaning that it can take on only two possible outcomes. These outcomes could be labeled "Yes" or "No", or "True" of "False", but for all intents and purposes, they can be coded as either 0 or 1. We have seen these types of variables before (as indicator variables), but we always used them as **explanatory** variables. Creating a model for such a variable as the response requires a more sophisticated technique than ordinary least squares regression. It requires the use of a **logistic** model. 

#### Fitting a Logistic model

For a binary response, instead of modeling $\pi$ (the response variable) like this,
$$
  \pi = \beta_0 + \beta_1 X
$$

suppose we modeled it like this,
$$
  \log \left( \frac{\pi}{1-\pi} \right) = logit(\pi) = \beta_0 + \beta_1 X
$$

This transformation is called the **logit** function. What are the properties of this function? Note that this implies that
$$
  \pi = \frac{e^{\beta_0 + \beta_1 X}}{1 + e^{\beta_0 + \beta_1 X}} \in (0,1)
$$

The logit function constrains the fitted values to line within $(0,1)$, which helps to give a natural interpretation as the probability of the response actually being 1. 

Fitting a logistic curve is mathematically more complicated than fitting a least squares regression, but the syntax in R is similar, as is the output. The procedure for fitting is called *maximum likelihood estimation*, and the usual machinery for the sum of squares breaks down. Consequently, there is no notion of $R^2$, etc. We use the function `glm()` (for Generalized Linear Model) to fit a logistic regression. 


The data in the `Whickham` data set (built into `mosaicData`) contains observations about women, and whether they were alive 20 years after their initial observation. Our goal is to determine how being a `smoker` affects the probability of being alive, after controlling for `age`. 


```{r}
data(Whickham)
Whickham <-  Whickham %>%
  mutate(isAlive = 2 - as.numeric(outcome))
```

1. What is this piece of code doing? Why $2$? 

```{r}
logm <- glm(isAlive ~ age, data=Whickham, family=binomial)
summary(logm)
```


```{r, fig.width=10}
ggplot(Whickham, aes(y=isAlive, x=age)) +  geom_point() +
  geom_smooth(method = "glm",  method.args = list(family = "binomial"), se = FALSE) 
```

2. How can we interpret the coefficients of this model in the context of the problem? 

```{r}
logm2 <- glm(isAlive ~ age + smoker, data=Whickham, family=binomial)
summary(logm)
```


3. How does the `smoker` term affect the model?

##### Binning

Another way to make sense of a binary response variable is to **bin** the explanatory variable and then compute the average proportion of the response within each bin. 

```{r}
Whickham <- Whickham %>%
  mutate(ageGroup = cut(age, breaks=10))
Whickham %>% 
  group_by(ageGroup) %>%
  skim(isAlive)
```

Although this is not the preferred method for performing logistic regression, it can be illustrative to see how the logistic curve fits through this series of points. 

```{r, fig.width=10}
binned <- Whickham %>%
  group_by(ageGroup) %>%
  dplyr::summarize(meanAlive = mean(isAlive), meanAge = mean(age))

ggplot() + geom_point(data=binned, aes(x=meanAge, y=meanAlive)) + geom_smooth(data=Whickham, aes(x=age, y=isAlive), method='glm', method.args = list(family = "binomial"), se = FALSE)
```

##### The Link Values

Consider now the difference between the fitted values and the link values. Although the fitted values do not follow a linear pattern with respect to the explanatory variable, the link values do. To see this, let's plot them explicitly against the logit of the binned values. 

```{r, fig.width=10}
ggplot(binned, aes(x=meanAge, y = logit(meanAlive))) + geom_point()

Whickham <- Whickham %>%
  mutate(logmlink = predict(logm, type="link"))

ggplot() + geom_point(data=binned, aes(x=meanAge, y = logit(meanAlive))) + geom_smooth(data=Whickham, aes(x=age, y=logmlink), method="lm", se=FALSE)
```

Note how it is considerably easier for us to assess the quality of the fit visually using the link values, as opposed to the binned probabilities. 

5. Why can't we take the logit of the actual responses?

#### Odds Ratios and Interpretation of Coefficients

The interpretation of the coefficients in a linear regression model are clear based on an understanding of the geometry of the regression model. We use the terms *intercept* and *slope* because a simple linear regression model is a line. In a simple logistic model, the line is transformed by the logit function. How do the coefficients affect the shape of the curve in a logistic model?

See this shiny app [https://ameliamn.shinyapps.io/log_app/](https://ameliamn.shinyapps.io/log_app/) to experiment with changes to the intercept and slope coefficients in a simple logistic model.

8. How do changes in the intercept term affect the shape of the logistic curve?
9. How do changes in the slope term affect the shape of the logistic curve?

We saw earlier that the link values are linear with respect to the explanatory variable. The link values are the $\log$ of the **odds**. Note that if an event occurs with proability $\pi$, then 
$$
  odds = \frac{\pi}{1-\pi}, \qquad \pi = \frac{odds}{1+odds}.
$$
Note that while $\pi \in [0,1]$, $odds \in (0,\infty)$. Thus, we can interpret $\hat{\beta_1}$ as the typical change in $\log{(odds)}$ for each one unit increase in the explanatory variable. More naturally, the odds of success are multiplied by $e^{\hat{\beta_1}}$ for each one unit increase in the explanatory variable, since this is the **odds ratio**. 
$$
  \begin{aligned}
      odds_X &= \frac{\hat{\pi}_X}{1 - \hat{\pi}_X} = e^{\hat{\beta}_0 + \hat{\beta}_1 X} \\
			odds_{X+1} &= \frac{\hat{\pi}_{X+1}}{1 - \hat{\pi}_{X+1}} = e^{\hat{\beta}_0 + \hat{\beta}_1 (X + 1)} \\
			\frac{odds_{X+1}}{odds_X} &= \frac{e^{\hat{\beta}_0 + \hat{\beta}_1 (X + 1)}}{e^{\hat{\beta}_0 + \hat{\beta}_1 X}} = e^{\hat{\beta}_1}
  \end{aligned}
$$
Furthermore, since the *logits* are linear with respect to the explanatory variable, these changes are constant. 

Finding confidence intervals for the odds ratio is easy. We could look at the point estimate and standard error from the `summary()` and use the `qnorm()` function to find a critical z value, or we could just use the convenience function `confint()`. 

```{r}
exp(confint(logm))
```


#### Assessing a Logistic Fit

Three of the conditions we require for linear regression have analogs for logistic models:

* Linearity of the *logit* (or $\log{(odds)}$)
* Independence
* Random

However, the requirements for Constant Variance and Normality are no longer applicable. In the first case, the variability in the response now inherently depends on the value, so we know we won't have constant variance. In the second case, there is no reason to think that the residuals will be normally distributed, since the "residuals" are can only be computed in relation to 0 or 1. So in both cases the properties of a binary response variable break down the assumptions we made previously. 

Moreover, since we don't have any sums of squares, we can't use $R^2$, ANOVA, or $F$-tests. Instead, since we fit the model using *maximum likelihood estimation*, we compute the likelihood of our model. 
		$$
			L(y_i) = \begin{cases}
        \hat{\pi} & \text{if } y_i=1 \\
        1-\hat{\pi} & \text{if } y_i=0
        \end{cases},\qquad L(model) = \prod_{i=1}^n L(y_i)
		$$
Because these numbers are usually very small (why?), it is more convenient to speak of the log-likelihood $\log(L)$, which is always negative. A larger $\log(L)$ is closer to zero and therefore a better fit.

The log-likelihood is easy to retrieve
```{r}
logLik(logm)
```


The closest thing to an analog of the $F$-test is the **Likelihood Ratio Test** (LRT). Here, our goal is to compare the log-likelihoods of two models: the one we build vs. the constant model. This is similar to the way we compared the sum of the squares explained by a linear regression model to the model that consists solely of the grand mean. 

The null hypothesis in the LRT is that $\beta_1 = \beta_2 = \cdots = \beta_k = 0$. The alternative hypothesis is that at least one of these coefficients is non-zero. The test statistic is:
$$
  G = -2\log(\text{constant model}) - (-2 \log(\text{model})).
$$
These two quantities are known as **deviances**. It can be shown that $G$ follows a $\chi^2$ distribution with $k$ degrees of freedom. This allows us to compute a $p$-value for the model. 

```{r}
library(lmtest)
lrtest(logm)
```

In this sense the LRT has obvious similarities to the ANOVA table and $F$-test. In the same way that we previously performed a nested $F$-test to assess the usefulness of a group of predictors, we can perform a nested LRT. 

Adding interaction or quadratic terms works in much the same way as it did with linear regression. 

```{r}
linteract <- glm(isAlive ~ age + smoker + age*smoker, data=Whickham, family=binomial)
summary(linteract)
```

10. Interpret the coefficients of this model, and find confidence intervals for them.

Suppose now that we suspect that there are diminishing returns to the extent to which being alive is associated with a person's age. We can easily add quadratic terms. 

```{r}
lquad <- glm(isAlive ~ age + smoker + age*smoker + I(age^2) + I(age^2):smoker, data=Whickham, family=binomial)
summary(lquad)
```

11. Interpret the coefficients of this model, and find confidence intervals for them.

How can we assess whether these terms are warranted? Just like the nested $F$-test, the nested LRT gives us information about the incremental contribution of a set of terms to our model.

```{r}
lrtest(logm, linteract, lquad)
```

13. Experiment with different models until you find one that you think fits the data best. Justify your answer. 



#### Two-Way Tables and Chi-Squared Tests

Consider the logistic model for $isAlive$ based only on $smoker$. This is a simple logistic regression model in which **both** the response and explanatory variable are binary. 

```{r}
logm <- glm(isAlive ~ smoker, data=Whickham, family=binomial)
summary(logm)
```

Since both variables in this case are binary, an essentially equivalent model is to simply compute a 2-way table. 

```{r}

  
two.way = table(Whickham$isAlive, Whickham$smoker)
two.way
```

Note that the logistic model only has two possible imputs (and therefore two possible outputs), and that they match the entries in the 2-way table.

Furthermore, the odds ratio from the 2-way table is the same as the odds ratio from the logistic model. 

```{r}
oddsRatio(two.way)
# Since the coefficient is negative, we add a negative here to match the 2-way table
exp(-coef(logm))
```

When we built the logistic regression model, we obtained a $p$-value for the coefficient of $smoker$. This was helpful, because it gave us some information about the extent of the statistical significance of the relationship between $smoker$ and $isAlive$. Can we obtain something similar from the 2-way table? Indeed, the $\chi^2$-test gives essentially the same information. 

```{r}
chisq.test(two.way[1:2,1:2], correct=FALSE)
```

#### Classification

We already learned how to compare models using the deviance, but how do we know how well our model works? One techinque for assessing the goodness-of-fit in a logistic regression model is to examine the percentage of the time that our model was "right."

Return to the logistic model that we built for $isAlive$ as a function of $age$ and $smoker$. 

```{r}
logm <- glm(isAlive ~ age + smoker, data=Whickham, family=binomial)
summary(logm)
```

When we visualize the model, it's hard to assess how often our model is correct. (This isn't *exactly* our model, but it's close) 

```{r, fig.width=10}
ggplot(Whickham, aes(y=isAlive, x=age, col=smoker)) +  geom_point() +
  geom_smooth(data=filter(Whickham, smoker=="Yes"), method = "glm", formula='y~x', method.args = list(family = "binomial"), se = FALSE) +
  geom_smooth(data=filter(Whickham, smoker=="No"), method = "glm", formula='y~x', method.args = list(family = "binomial"), se = FALSE) 
```

Moreover, what does it even mean to be correct? The response variable is binary, but the predictions generated by the model are quantities on $[0,1]$. A simple way to **classify** the fitted values of our model is to simply round them off. Once we do this, we can tabulate how often the rounded-off probability from the model agrees with the actual response variable. 

```{r}
Whickham <- Whickham %>%
  mutate(fitted = fitted.values(logm)) %>%
  mutate(fitalive = ifelse(fitted >= 0.5, 1, 0))
tbl <- table(Whickham$isAlive, Whickham$fitalive)
tbl
sum(diag(tbl)) / nrow(Whickham)
```

Thus, our model was correct nearly 84% of the time. Is that good? It depends on the application...

We might want to compare this with what would happen if we used the null model, just predicting every value by the mean

```{r}
Whickham %>% 
  skim(isAlive)
```

or if we had just flipped a coin instead of using a model at all.
```{r}
Whickham <- Whickham %>%
   mutate(fitalive = sample(c(0,1), size=1314, replace=TRUE))
table(Whickham$isAlive, Whickham$fitalive)
```

1. Which of these "models" is best?

#### Concordance
A more sophisticated technique for assessing the quality of fit is to examine the $C$-statistic, where $C$ stands for **concordance**. The idea here is to pair up each actual success with each actual failure, and then compute whether the fitted probability for the success was greater than the fitted probability for the failure. The percentage of pairs statisfying this condition makes up the $C$-statistic. 

Note that even if our model had no predictive power, it would still be right about half of the time. Thus, the $C$-statistic for two randomly generated vectors is about 0.5. 

```{r}
X <- data.frame(a = runif(10000), b = runif(10000))
# install.packages("Hmisc")
library(Hmisc)
rcorrcens(a~b, data=X)
```

In this case our model is much more effective.

```{r}
rcorrcens(isAlive ~ fitted.values(logm), data=Whickham)
# warning! Hmisc may mess with dplyr. After you're done with it, it's good to
detach(package:Hmisc)
```

