```{r setup, include = FALSE}
library(broom)
library(ggplot2)
library(dplyr)
library(lubridate)
library(tidyr)
library(nycflights13)
```

# Model visualisation

In this chapter we will explore model visualisation from two different sides:

1. Use a model to make it easier to see important patterns in our data.

1. Use visualisation to understand what a model is telling us about our data.

We're going to give you a basic strategy, and point you to places to learn more. The key is to think about data generated from your model as regular data - you're going to want to manipulate it and visualise it in many different ways.

Centered around looking at residuals and looking at predictions. You'll see those here applied to linear models (and some minor variations), but it's a flexible technique since every model can generate predictions and residuals.

Being good at modelling is a mixture of having some good general principles and having a big toolbox of techniques. Here we'll focus on general techniques to help you undertand what your model is telling you.

Focus on constructing models that help you better understand the data. This will generally lead to models that predict better. But you have to beware of overfitting the data - in the next section we'll discuss some formal methods. But a healthy dose of scepticism is also a powerful: do you believe that a pattern you see in your sample is going to generalise to a wider population? 

Transition from implicit knowledge in your head and in data to explicit knowledge in the model. In other words, you want to make explicit your knowledge of the data and capture it explicitly in a model. This makes it easier to apply to new domains, and easier for others to use. But you must always remember that your knowledge is incomplete.

For very large and complex datasets this is going to be a lot of work. There are certainly alternative approaches - a more machine learning approach is simply to focus on improving the predictive ability of the model, being careful to fairly assess it (i.e. not assessing the model on the data that was used to train it). These approaches tend to produce black boxes - i.e. the model does a really good job, but you don't know why. This is fine, but the main problem is that you can't apply your real world knowledge to the model to think about whether or not it's likely to work in the long-term, as fundamentals change. For most real models, I'd expect you to use some combination of this approach and a ML model building approach. If prediction is important, get to a good point, and then use visulisation to understand the most important parts of the model.

In the next chapter, you'll also learn about how to visualise the model-level summaries, and the model parameters.

To do this we're going to use some helper functions from the modelr package. This package provides some wrappers around the traditional base R modelling functions that make them easier to use in data manipulation pipelines. Currently at <https://github.com/hadley/modelr> but will need to be on CRAN before the book is published.

```{r}
library(modelr)
```


## Residuals

To motivate the use of models we're going to start with an interesting pattern from the NYC flights dataset: the number of flights per day.

```{r}
library(nycflights13)
library(lubridate)
library(dplyr)

daily <- flights %>% 
  mutate(date = make_datetime(year, month, day)) %>% 
  group_by(date) %>% 
  summarise(n = n())

ggplot(daily, aes(date, n)) + 
  geom_line()
```

Understanding this pattern is challenging because there's a very strong day-of-week effect that dominates the subtler patterns:

```{r}
daily <- daily %>% 
  mutate(wday = wday(date, label = TRUE))
ggplot(daily, aes(wday, n)) + 
  geom_boxplot()
```

There are fewer flights on weekends because a very large proportion of travel is for business. You might sometimes have to less on Sunday for an early flight, but it's very rare that you'd leave on Saturday: you'd much rather be home with your family.

One way to remove this strong pattern is to fit a model that "explains" (i.e. attempts to predict) the day of week effect, and then look at the residuals:

```{r}
mod <- lm(n ~ wday, data = daily)
daily <- daily %>% add_residuals(n_resid = mod)

daily %>% 
  ggplot(aes(date, n_resid)) + 
  geom_hline(yintercept = 0, size = 2, colour = "white") + 
  geom_line()
```

Note the change in the y-axis: now we are seeing the deviation from the expected number of flights, given the day of week. This plot is interesting because now that we've removed much of the large day-of-week effect, we can see some of the subtler patterns that remain:

1.  Our day of week adjustment seems to fail starting around June: you can
    still see a strong regular pattern that our model hasn't removed. Drawing
    a plot with one line for each day of the week makes the cause easier
    to see:

    ```{r}
    ggplot(daily, aes(date, n_resid, colour = wday)) + 
      geom_hline(yintercept = 0, size = 2, colour = "white") + 
      geom_line()
    ```

    The problem appears to be Saturdays: it seems like during summer there are 
    more flights on Saturdays than we expect, and during Fall there are fewer. 
    I suspect this is because of summer holidays: many people go on holiday 
    in the summer, and people don't mind travelling on Saturdays for vacation.
    (This doesn't, however, explain why there are more Satruday flights in 
    spring than fall).

1.  There are some day with much fewer flights than expected:


    ```{r}
    daily %>% filter(n_resid < -100)
    ```

    If you're familiar with American public holidays, you might spot New Year's 
    day, July 4th, Thanksgiving and Christmas. There are some others that don't 
    seem to correspond immediately to public holidays. You'll work on those 
    in the exercise below.
    
1.  There seems to be some smoother long term trend over the course of a year.
    We can highlight that trend with `geom_smooth()`:

    ```{r}
    daily %>% 
      ggplot(aes(date, n_resid)) + 
      geom_hline(yintercept = 0, size = 2, colour = "white") + 
      geom_line(colour = "grey50") + 
      geom_smooth(se = FALSE, span = 0.20)
    ```

    There are fewer flights in January (and December), and more in summer 
    (May-Sep). We can't do much more with this trend than brainstorm possible 
    explanations because we only have a single year's worth of data.
    
We'll tackle the day of week effect first. Let's zoom in on Saturdays, going back to raw numbers:

```{r}
daily %>% 
  filter(wday == "Sat") %>% 
  ggplot(aes(date, n)) + 
    geom_line() +
    geom_point(alpha = 1/3) + 
    scale_x_datetime(NULL, date_breaks = "1 month", date_labels = "%b")
```

So it looks like summer holidays are from early June to late August. That seems to line up fairly well with the [state's school terms](http://schools.nyc.gov/Calendar/2013-2014+School+Year+Calendars.htm): summer break is Jun 26 - Sep 9. So lets add a "term" variable to attemp to control for that. 

```{r}
daily <- daily %>%
  mutate(term = cut(date, 
    breaks = as.POSIXct(ymd(20130101, 20130601, 20130825, 20140101)),
    labels = c("spring", "summer", "fall") 
  )) 

daily %>% 
  filter(wday == "Sat") %>% 
  ggplot(aes(date, n, colour = term)) +
  geom_point(alpha = 1/3) + 
  geom_line() +
  scale_x_datetime(NULL, date_breaks = "1 month", date_labels = "%b")
```

(I manually tweaked the dates to get nice breaks in the plot.)

It's useful to see how this new variable affects the other days of the week:

```{r}
daily %>% 
  ggplot(aes(wday, n, colour = term)) +
    geom_boxplot()
```

It looks like there is significant variation across the terms, so fitting a separate day of week effect for each term is reasonable. This improves our model, but not as much as we might hope:

```{r}
mod2 <- lm(n ~ wday * term, data = daily)
daily$n_resid2 <- resid(mod2)

ggplot(daily, aes(date)) + 
  geom_line(aes(y = n_resid, colour = "mod1")) +
  geom_line(aes(y = n_resid2, colour = "mod2")) +
  scale_colour_manual(values = c(mod1 = "grey50", mod2 = "black"))
```

That's because this model is basically calculating an average for each combination of wday and school term. We have a lot of big outliers, so they tend to drag the mean far away from the typical value.

```{r}
middles <- daily %>% 
  group_by(wday, term) %>% 
  summarise(
    mean = mean(n),
    median = median(n)
  )

middles %>% 
  ggplot(aes(wday)) +
    geom_linerange(aes(ymin = mean, ymax = median), colour = "grey70") + 
    geom_point(aes(y = mean, colour = "mean")) +
    geom_point(aes(y = median, colour = "median")) + 
    facet_wrap(~ term)
```

We can reduce this problem by switching to a robust model fitted by `MASS::rlm()`. A robust model is a variation of the linear model which you can think of a fitting medians, instead of means (it's a bit more complicated than that, but that's a reasonable intuition). This greatly reduces the impact of the outliers on our estimates, and gives a result that does a good job of removing the day of week pattern:

```{r, warn=FALSE}
mod2 <- MASS::rlm(n ~ wday * term, data = daily)
daily <- daily %>% add_residuals(n_resid2 = mod2)

ggplot(daily, aes(date, n_resid2)) + 
  geom_hline(yintercept = 0, size = 2, colour = "white") + 
  geom_line() +
  geom_smooth(span = 0.25, se = FALSE)
```

It's now much easier to see the long-term trend, and the positive and negative outliers.

### Exercises

1.  Use your google sleuthing skills to brainstorm why there were fewer than
    expected flights on Jan 20, May 26, and Sep 9. (Hint: they all have the
    same explanation.) How would these days generalise to another year?

1.  What do the three days with high positive residuals represent?
    How would these days generalise to another year?

    ```{r}
    daily %>% filter(n_resid2 > 80)
    ```

1.  Create a new variable that splits the `wday` variable into terms, but only
    for Saturdays, i.e. it should have `Thurs`, `Fri`, but `Sat-summer`, 
    `Sat-spring`, `Sat-fall`. How does this model compare with the model with 
    every combination of `wday` and `term`?
    
1.  Create a new wday variable that combines the day of week, term 
    (for Saturdays), and public holidays. What do the residuals of 
    that model look like?

1.  What happens if you fit a day of week effect that varies by month?
    Why is this not very helpful? 

1.  Above we made the hypothesis that people leaving on Sundays are more 
    likely to be business travellers who need to be somewhere on Monday.
    Explore that hypothesis by seeing how it breaks down based on distance:
    if it's true, you'd expect to see more Sunday flights to places that
    are far away.

1.  It's a little frustrating that Sunday and Saturday are on separate ends
    of the plot. Write a small function to set the levels of the factor so
    that the week starts on Monday.

## Predictions

Focus on predictions from a model because this works for any type of model. Visualising parameters can also be useful, but tends to be most useful when you have many similar models. Visualising predictions works regardless of the model family.

Visualising high-dimensional models is challenging. You'll need to partition off a useable slice at a time.

### `rlm()` vs `lm()`

Let's start by exploring the difference between the `lm()` and `rlm()` predictions for the day of week effects. We'll first re-fit the models, just so we have them handy:

```{r}
mod1 <- lm(n ~ wday * term, data = daily)
mod2 <- MASS::rlm(n ~ wday * term, data = daily)
```

Next, we need to generate a grid of values to compute predictions for. The easiest way to do that is to use `tidyr::expand()`. It's first argument is a data frame, and for each subsequent argument it finds the unique variables and then generates all combinations:

```{r}
grid <- 
  daily %>% 
  tidyr::expand(wday, term) 

grid
```

Next we add predicitons. We'll use `modelr::add_predictions()` which works in exactly the same way as `add_residuals()`, but just compute predictions (so doesn't need a data frame that contains the response variable:)

```{r}
grid <- 
  grid %>% 
  add_predictions(linear = mod1, robust = mod2) 
grid
```

And then we plot the predictions. Plotting predictions is usually the hardest bit and you'll need to try a few times before you get a plot that is most informative. Depending on your model it's quite possible that you'll need multiple plots to fully convey what the model is telling you about the data.

```{r}
grid %>% 
  ggplot(aes(wday)) +
    geom_linerange(aes(ymin = linear, ymax = robust), colour = "grey70") + 
    geom_point(aes(y = linear, colour = "linear")) +
    geom_point(aes(y = robust, colour = "robust")) + 
    facet_wrap(~ term)
```

### Computed variables

```{r}
daily %>% 
  expand(date) %>% 
  mutate(
    term = cut(date, 
      breaks = as.POSIXct(ymd(20130101, 20130605, 20130825, 20140101)),
      labels = c("spring", "summer", "fall") 
    ),
    wday = wday(date, label = TRUE)
  ) %>% 
  add_predictions(pred = mod2) %>% 
  ggplot(aes(date, pred)) +
    geom_line()
```

If you're experimenting with many models and many visualisations, it's a good idea to bundle the creation of variables up into a function so there's no chance of accidentally applying a different transformation in different places.

### Nested variables

Another case that occassionally crops up is nested variables: you have an identifier that is locally unique, not globally unique. For example you might have this data about students in schools:

```{r}
students <- tibble::frame_data(
  ~student_id, ~school_id,
  1, 1,
  2, 1,
  1, 2,
  1, 3,
  2, 3,
  3, 3
)
```

The student id only makes sense in the context of the school: it doesn't make sense to generate every combination of student and school. You can use `nesting()` for this case:

```{r}
students %>% expand(nesting(school_id, student_id))
```

### Continuous variables

```{r}
grid <- nlme::Oxboys %>% 
  as_data_frame() %>% 
  tidyr::expand(Subject, age = seq_range(age, 2))

mod <- nlme::lme(height ~ age, random = ~1 | Subject, data = nlme::Oxboys)

grid %>% 
  add_predictions(mod = mod) %>% 
  ggplot(aes(age, mod)) + 
    geom_line(aes(group = Subject))
```

### Exercises

1.  How does the model of model coefficients compare to the plot of means
    and medians computed "by hand" in the previous chapter. Create a plot
    the highlights the differences and similarities.

## Delays and weather

```{r}
hourly <- flights %>% 
  group_by(origin, time_hour) %>% 
  summarise(
    delay = mean(dep_delay, na.rm = TRUE)
  ) %>% 
  inner_join(weather, by = c("origin", "time_hour"))

# ggplot(hourly, aes(time_hour, delay)) +
#   geom_point()
# 
# ggplot(hourly, aes(hour(time_hour), sign(delay) * sqrt(abs(delay)))) +
#   geom_boxplot(aes(group = hour(time_hour)))
# 
# hourly %>% 
#   filter(wind_speed < 999) %>% 
#   ggplot(aes(temp, delay)) +
#   geom_point() + 
#   geom_smooth()

```

## Learning more

<https://cran.rstudio.com/web/packages/condvis/>
