---
title: "Lab: linear regression"
format: html
---

## 0. Data

We continue to use the 2024 NBA regular season stats dataset from previous labs.

In the NBA, and more generally in team sports, a coach must make decisions about how many minutes each player should play.
Typically, these decisions are informed by a player's skills, along with other factors such as fatigue, matchups, etc.
Our goal is to use measurements of a few (quantifiable) player attributes to predict the minutes per game a player plays. 
In particular, we will focus on the following data, measured over the 2024 NBA regular season for over 400 players:

*   `player`: names of each player (not useful for modeling purposes, but just for reference)
*   `min_per_game`: our **response variable**, measuring the minutes per game a player played during the 2024 NBA regular season.
*   `field_goal_percentage`: potential (continuous) **explanatory variable**, calculated as (number of made field goals) / (number of field goals attempted).
*   `free_throw_percentage`: potential (continuous) **explanatory variable**, calculated as (number of made free throws) / (number of free throws attempted).
*   `three_point_percentage`: potential (continuous) **explanatory variable**, calculated as (number of made 3 point shots) / (number of 3 point shots attempted),
*   `age`: potential (continuous/discrete) **explanatory variable**, player's reported age for the 2024 season, 
*   `position`: potential (categorical) explanatory variable, one of `SG` (shooting guard), `PG` (point guard), `C` (center), `PF` (power forward) or `SF` (small forward).

Execute the following code chunk to 
(a) load the necessary data for this lab,
(b) compute variables we will use in this lab,
(c) remove players with missing data (just to simplify things),
and (d) subset out players with low minute totals (fewer than 250 minutes played in a season):

```{r}
#| message: false
library(tidyverse)
nba_stats <- read_csv("https://raw.githubusercontent.com/36-SURE/2024/main/data/nba_stats.csv")

nba_stats <- nba_stats |>
  # summarize player stats across multiple teams they played for
  group_by(player) |>
  summarize(
    age = first(age),
    position = first(position),
    games = sum(games, na.rm = TRUE),
    minutes_played = sum(minutes_played, na.rm = TRUE),
    field_goals = sum(field_goals, na.rm = TRUE),
    field_goal_attempts = sum(field_goal_attempts, na.rm = TRUE),
    three_pointers = sum(three_pointers, na.rm = TRUE),
    three_point_attempts = sum(three_point_attempts, na.rm = TRUE),
    free_throws = sum(free_throws, na.rm = TRUE),
    free_throw_attempts = sum(free_throw_attempts, na.rm = TRUE)
  ) |>
  ungroup() |>
  mutate(
    field_goal_percentage = field_goals / field_goal_attempts,
    three_point_percentage = three_pointers / three_point_attempts,
    free_throw_percentage = free_throws / free_throw_attempts,
    min_per_game = minutes_played / games
  ) |>
  # remove rows with missing missing values
  drop_na() |>
  filter(minutes_played > 250)
```

## 1. EDA

Spend time exploring the dataset, to visually assess which of the **explanatory** variables listed above is most associated with our response the minutes played per game (`min_per_game`).
Create scatterplots between the response and each continuous explanatory variable.
**Does any of the relationships appear to be linear?**
Describe the direction and strength of the association between the explanatory and response variables.

In your opinion, **which of the possible continuous explanatory variables displays the strongest relationship with minutes per game**?

Create an appropriate visualization comparing the distribution of minutes per game *by position*.
**Do you think there is a relationship between minutes per game and position?**

## 2. Fit a simple linear model

Now that you've performed some EDA, it's time to actually fit some linear models to the data.
Start the variable you think displays the strongest relationship with the response variable.
**Update the following code by replacing `INSERT_VARIABLE` with your selected variable, and run to fit the model**:

```{r}
#| eval: false
init_nba_lm <- lm(min_per_game ~ INSERT_VARIABLE, data = nba_stats)
```

Before looking at the model summary, **you need to check the diagnostics** to see if it meets the necessary assumptions.
To do this you can try running `plot(init_nba_lm)` in the console (what happens?).
Equivalently, another way to make the same plots but with `ggplot2` perks is with the [`ggfortify`](https://cran.r-project.org/web/packages/ggfortify/vignettes/plot_lm.html) package by running the following code:

```{r}
#| eval: false
library(ggfortify) # install.packages("ggfortify")
init_nba_lm |> 
  autoplot() +
  theme_light()
```

The first plot is **residuals vs. fitted**: this plot should NOT display any clear patterns in the data, no obvious outliers, and be symmetric around the horizontal line at zero.
The smooth line provided is just for reference to see how the residual average changes.
**Do you see any obvious patterns in your plot for this model?**

The second plot is a Q-Q plot ([see page 93 for more details](http://www.stat.cmu.edu/~cshalizi/TALR/TALR.pdf)).
Without getting too much into the math behind them, **the closer the observations are to the dashed reference line, the better your model fit is.**
It is bad for the observations to diverge from the dashed line in a systematic way; that means we are violating the assumption of normality discussed in lecture.
**How do your points look relative to the dashed reference line?**

The third plot looks at the square root of the absolute value of the standardized residuals.
We want to check for homoskedascity of errors (equal, constant variance). 
**If we did have constant variance, what would we expect to see?**
**What does your plot look like?**

The fourth plot is residuals vs. leverage which helps us identify **influential** points.
**Leverage** quantifies the influence the observed response for a particular observation has on its predicted value, i.e. if the leverage is small then the observed response has a small role in the value of its predicted response, while a large leverage indicates the observed response plays a large role in the predicted response.
It's a value between 0 and 1, where the sum of all leverage values equals the number of coefficients (including the intercept). Specifically the leverage for observation $i$ is computed as
$$
h_{ii} = \frac{1}{n} + \frac{(x_i - \bar{x})^2}{\sum_i^n (x_i - \bar{x})^2}
$$
where $\bar{x}$ is the average value for variable $x$ across all observations.
[See page 191 for more details on leverage and the regression hat matrix](http://www.stat.cmu.edu/~cshalizi/TALR/TALR.pdf).
We're looking for points in the upper right or lower right corners, where dashed lines for [Cook's distance](https://en.wikipedia.org/wiki/Cook%27s_distance) values would indicate potential outlier points that are displaying too much influence on the model results.
**Do you observed any such influential points in upper or lower right corners?**

**What is your final assessment of the diagnostics, do you believe all assumptions are met? Any potential outlier observations to remove?**

## 3. Assess the model summary

Interpret the results of your initial model using the `tidy()` function from the `broom` package (or the `summary()` function).
**Do you think there is sufficient evidence to reject the null hypothesis that the coefficient is 0? What is the interpretation of the $R^2$ value?**
Compare the square root of the raw (unadjusted) $R^2$ of your linear model to the correlation between that explanatory variable and the response using the `cor()` function.
**What do you notice?**

To assess the fit of a linear model, we can also plot the predicted values vs the actual values, to see how closely our predictions align with reality, and to decide whether our model is making any systematic errors.
Execute the following code chunk to show the actual minutes per game against our model's predictions:

```{r}
#| eval: false
nba_stats |>
  mutate(init_preds = predict(init_nba_lm)) |>
  ggplot(aes(x = init_preds, y = min_per_game)) +
  geom_point(alpha = 0.75) +
  geom_abline(slope = 1, intercept = 0, linetype = "dashed", color = "red") +
  labs(x = "Predictions", y = "Observed minutes per game") +
  theme_light()
```

## 4. Include multiple covariates

Repeat steps 2 and 3 above but including more than one variable in your model.
You can easily do this in the `lm()` function by adding another variable to the formula with the `+` operator as so (but just replace the `INSERT_VARIABLE` parts):

```{r}
#| eval: false
multi_nba_lm <- lm(min_per_game ~ INSERT_VARIABLE_1 + INSERT_VARIABLE_2, data = nba_stats)
```

**Experiment with different sets of the continuous variables**.
What sets of continuous variables do you think model minutes per game best?
(Remember to use the **Adjusted $R^2$** when comparing models that have different numbers of variables).

Beware of collinearity!
Load the `car` library (install it if necessary!) and use the `vif()` function to check for possible (multi)collinearity.
The `vif()` function computes the **variance inflation factor (VIF)** for predictor $x_j$ with $j \in 1,\dots, p$ as
$$
\text{VIF}_j = \frac{1}{1 - R^2_j}
$$
where $R^2_j$ is the $R^2$ from a variable with variable $x_j$ as the response and the other $p-1$ predictors as the explanatory variables.
VIF values close to 1 indicate the variable is not correlated with other predictors, while VIF values over 5 indicate strong presence of collinearity.
If present, remove a variable with VIF over 5, and redo the fit.
Repeat this process until the `vif()` outputs are all less than 5.
The follow code chunk displays an example of using this function:

```{r}
#| eval: false
library(car) # install.packages("car")
vif(multi_nba_lm)
```

## 5. Linear model with one categorical variable

Run the following code to fit a model using only the `position` variable:

```{r}
#| eval: false
pos_nba_lm <- lm(min_per_game ~ position, data = nba_stats)
```

Next, use the following code to first create a column called `pos_preds` containing the predictions of the model above, to display the predictions of this model against the actual observed minutes per game, but facet by the player's position:

```{r}
#| eval: false
nba_stats |>
  mutate(pos_preds = predict(pos_nba_lm)) |>
  ggplot(aes(x = min_per_game, y = pos_preds)) +
  geom_point(alpha = 0.5) +
  facet_wrap(~ position, ncol = 3) +
  labs(x = "Actual minutes per game", 
       y = "Predicted minutes per game") +
  theme_light()
```

As the figure above, **we are changing the intercept of our regression line** by including a categorical variable.
To make this more clear, view the output of the summary:

```{r}
#| eval: false
summary(pos_nba_lm)
```

**Notice how only four coefficients are provided in addition to the intercept.**
This is because, by default, `R` turns the categorical variables of $m$ levels (e.g. we have 5 positions in this dataset) into $m - 1$ indicator variables (binary with values of 1 if in that level versus 0 if not that level) for different categories relative to a **baseline level**.
In this example, `R` has created an indicator for four positions: `PF`, `PG`, `SF`, and `SG`.
By default, `R` will use alphabetical order to determine the baseline category, which in this example the center position `C`.
The values for the coefficient estimates indicate the expected change in the response variable relative to the baseline.
In other words, **the intercept term gives us the baseline's average y**, e.g. the average minutes per game for centers.
This matches what you displayed in the predictions against observed minutes/game scatterplots by position above. 

**Beware the default baseline `R` picks for categorical variables!**
We typically want to choose the baseline level to be the group **with the most observations**.
In this example, each position has a similar number of observations so the results are reasonable.
But in general, we can change the reference level by modifying the factor levels of the categorical variables (similar to how we reorder things in `ggplot2`).
For example, after viewing `table(nba_stats$position)` we see how the `SG` position has the most observations.
We can use the following code to modify the position variable so that `SG` is the baseline (we can use `fct_relevel()` to update `position` so that `SG` is the first factor level - and we do not need to modify the order of the remaining levels):

```{r}
#| eval: false
nba_stats <- nba_stats |>
  mutate(position = fct_relevel(position, "SG")) 
```

**Refit the linear regression model using `position` above, how has the summary changed?**

## 6. Linear model with one categorical and one continuous variable

Pick a single continuous variable from yesterday, use it to replace `INSERT_VARIABLE` below, then run the code to fit a model with the `position` included:

```{r}
#| eval: false
x_pos_nba_lm <- lm(min_per_game ~ position + INSERT_VARIABLE, data = nba_stats)
```

**Create scatterplots with your predictions on the y-axis, your `INSERT_VARIABLE` on the x-axis, and color by position**.
What do you observe?

Given similarities between different types of positions, we can easily collapse the positions together into a smaller number of categories using `fct_collapse()`:

```{r}
#| eval: false
nba_stats <- nba_stats |>
  mutate(
    position_group = fct_collapse(position, Guard = c("SG", "PG"), Forward = c("SF", "PF"), Center = "C")
  ) 
```

**Refit the model with this new `position_group` variable**, but assign it to a different name, e.g. `x_pos_group_nba_lm`.
What changed in the summary?

## 7. Interactions

Remember with `ggplot2` you can directly compute and plot the results from running linear regression using `geom_smooth()` or `stat_smooth()` and specifying that `method = "lm"`.
Try running the following code (replace `INSERT_VARIABLE`) to generate the linear regression fits with `geom_smooth` versus your own model's predictions (note the different `y` mapping for the point versus smooth layers):

```{r}
#| eval: false
nba_stats |>
  mutate(pos_preds = predict(x_pos_nba_lm)) |>
  ggplot(aes(x = INSERT_VARIABLE, color = position)) +
  geom_point(aes(y = pos_preds), alpha = 0.5) +
  geom_smooth(aes(y = min_per_game), method = "lm") 
  facet_wrap(~ position, ncol = 3) +
  labs(x = "INSERT YOUR LABEL HERE", 
       y = "Predicted minutes per game") +
  theme_light()
```

**The `geom_smooth()` regression lines do NOT match!**
This is because `ggplot2` is fitting **separate regressions for each position**, meaning the slope for the continuous variable on the x-axis is changing for each position.
We can match the output of the `geom_smooth()` results with **interactions**.
We can use interaction terms to build more complex models.
Interaction terms allow for a different linear model to be fit for each category; that is, they allow for different slopes across different categories.
If we believe relationships between continuous variables, and outcomes, differ across categories, we can use interaction terms to better model these relationships.

To fit a model with an interaction term between two variables, include the interaction via the `*` operator like so:

```{r}
#| eval: false
pos_int_nba_lm <- lm(min_per_game ~ position * INSERT_VARIABLE, data = nba_stats)
```

**Replace the predictions in the previous plot's `mutate` code with this interaction model's predictions.**
How do they compare to the results from `geom_smooth()` now?

You can model interactions between any type of variables using the `*` operator, feel free to experiment on your different possible continuous variables.

## 8. Polynomials

Another way to increase the explanatory power of your model is to include transformations of continuous variables.
For instance you can directly create a column that is a square of a variable with `mutate()` and then fit the regression with the original variable and its squared term:

```{r}
#| eval: false
nba_stats <- nba_stats |>
  mutate(fg_perc_squared = field_goal_percentage ^ 2)
squared_fg_lm <- lm(min_per_game ~ field_goal_percentage + fg_perc_squared, data = nba_stats)
summary(squared_fg_lm)
```

**What are some difficulties with interpreting this model fit?** 
View the predictions for this model or other covariates you squared.

## 9. Training and testing

As we've seen, using transformations such as higher-order polynomials may decrease the interpretability and increase the potential for overfitting associated with our models; however, they can also dramatically improve the explanatory power.

We need a way for making sure our more complicated models have not overly fit to the noise present in our data.
Another way of saying this is that a good model should generalize to a different sample than the one on which it was fit.
This intuition motivates the idea of training/testing.
We split our data into two parts, use one part -- the training set -- to fit our models, and the other part -- the testing set -- to evaluate our models.
Any model which happens to fit to the noise present in our training data should perform poorly on our testing data.  

The first thing we will need to do is split our sample.
Run the following code chunk to divide our data into two halves, which we will refer to as a training set and a test set.
Briefly summarize what each line in the code chunk is doing.

```{r}
#| eval: false
nba_train <- nba_stats |> 
  slice_sample(prop = 0.5, replace = FALSE)
nba_test <- nba_stats |> 
  anti_join(nba_train)
```

We will now compare three candidate models for predicting minutes played using position and field goal percentage.
We will fit these models on the **training data** only, ignoring the testing data for the moment.
Run the below two code chunks to create two candidate models:

```{r}
#| eval: false
# model with interaction terms
candidate_model_1 <- lm(min_per_game ~ position * poly(field_goal_percentage, 2, raw = TRUE), 
                        data = nba_train)
```

```{r}
#| eval: false
# model without interaction terms
candidate_model_2 <- lm(min_per_game ~ position + poly(field_goal_percentage, 2, raw = TRUE), 
                        data = nba_train)
```

(Note: The `poly()` function is useful for getting higher-order polynomial transformations of variables. And here's an [explanation](https://stackoverflow.com/questions/29999900/poly-in-lm-difference-between-raw-vs-orthogonal) of the `raw` argument.)

Using `broom::glance()` or `summary()`, which of these models has more explanatory power according to the training data?
Which of the models is less likely to overfit?

**Fit another model to predict minutes per game using a different set of variables or polynomials**. 

Now that we've built our candidate models, we will evaluate them on our test set, using the criterion of mean squared error (MSE).
Run the following code chunk to compute, on the test set, the MSE of predictions given by the first model compared to the actual minutes played.

```{r}
#| eval: false
model_1_preds <- predict(candidate_model_1, newdata = nba_test)
model_1_mse <- mean((model_1_preds - nba_test$min_per_game) ^ 2)
```

**Do this for each of your candidate models**.
Compare the MSE on the test set, which model performed best (in terms of lowest test MSE)?
