<style type="text/css"> 
body{
  background-color: #FAFAFA;
  font-size: 18px;
  line-height: 1.8; 
}
code.r{
  font-size: 12pt;
}
</style>

```{r setup, include=FALSE}
# knitr::opts_chunk$set(echo = TRUE, results = 'asis', fig.show = 'asis')
knitr::opts_chunk$set(echo = TRUE, message=FALSE, warning=FALSE)
``` 

<br/>
<br/>


# Regression Basics

The purpose of machine learning is to predict  an outcome variable, $y$, given a set of features (covariates), $x_1,x_2,\ldots,x_p$. We can represent our prediction model using the following 
equation: 
$$
y = f(x_1, x_2, \ldots,x_p)+\epsilon
$$
where $f(\cdot)$ is some function and $\epsilon$ is an unobservable random error term. The prediction based on a given set of features can be written as 
$$
\hat{y}=f(x_1, x_2, \ldots,x_p)
$$
This framework is familiar to the students of econometrics. If we assume that the prediction function is linear we obtain
$$
y = \beta_0 + \beta_1 x_1 + \beta_2x_2 \ldots + \beta_p x_p +\epsilon
$$
which is the familiar linear regression model.

The Ordinary Least Squares (OLS) estimation works fine if the number of features is relatively small.  

## `lm()` function in base R 

Example from the ISLR text: 

```{r}
library(MASS)
library(ISLR)
library(tidyverse)

# Simple Linear Regression
# Boston house data set
names(Boston) 
# see the explanation of the variables
# ?Boston
```

Run the regression of `medv` (median house value in \$1000) on lower income status
```{r}
reg1 = lm(formula = medv ~ lstat, data=Boston) 
summary(reg1)
names(reg1)
coef(reg1)
```

We can also use `tidy()`, `glance()` and `augment()` functions from the `{broom}` package to summarize the results and create separate data frames: 
```{r}
library(broom)
tidy(reg1)
```
```{r} 
glance(reg1)
```

```{r} 
augment(reg1)
```

Note that `augment()` creates a data frame that contains both observed variables and fitted values so that we can inspect the fit of the model directly. 

  

Compute the 95% confidence interval: 
```{r}
# 95% confidence interval 
confint(reg1)
```


Compute average predictions for a given set of lstat values: 
```{r}
# predictions from the model reg1
predict(reg1, data.frame(lstat=(c(5,10,15))), interval="confidence")
```

Compute predictions for single observations: 
```{r}
# predictions from the model reg1 
# for a single observation
predict(reg1, data.frame(lstat=(c(5,10,15))), interval="prediction")
```

Graph of fitted values: 
```{r}
plot(Boston$lstat, Boston$medv) 
abline(reg1,lwd=3)
```

Or, alternatively,
```{r}
# create a new data frame and call it Boston1
# I don't want to modify the original data set
Boston1 <- Boston
Boston1$yhat1 <- predict(reg1, Boston1)

Boston1 %>% ggplot(aes(lstat, medv)) + 
  geom_point() + 
  geom_line(aes(lstat, yhat1, color="red")) +
  theme(legend.position = "none") 
```

An alternative is to use the `augment()` function from the  `broom` package (loaded above): 
```{r}
augment(reg1) %>% 
  ggplot(mapping = aes(x = lstat)) +
  geom_point(mapping = aes(y = medv)) +
  geom_line(mapping = aes(y = .fitted), color = "red")
```  

It seems that there are some kind of nonlinearity in the relationship that cannot be captured in the regression above. Plotting the residuals and predicted values we obtain: 
```{r}
# Residuals vs Fitted values plot
Boston1$resid1 <- residuals(reg1)

Boston1 %>% ggplot(aes(yhat1, resid1)) + 
  geom_point() 
```

We expect the residuals to be dispersed around zero randomly. But the graph above indicates that there are same patterns not captured in the estimated relationship. 

Diagnostic plots can easily be obtained after the `lm()` estimation: 
```{r}
par(mfrow=c(2,2))
plot(reg1)
```

The first graph (up left) is the residuals vs fitted graph which we just discussed. The second graph (up right) is Q-Q plot of the standardized residuals which displays deviations from the normality. If the standardized residuals are normally distributed, they should be close to the dashed line. We see that there are some deviations on the upper left tail of the distribution (draw the histogram of the residuals to see this). 

The third grap (lower left) is the scale-location graph for the residuals and fitted values. We have square root of the absolute standardized residuals on the vertical axis. Again, we expect a random dispersion without any visible pattern that may be indicative of heteroscedasticity. The picture above suggests that the residual variance is more or less constant. 

The fourth graph (lower right) is the leverage graph. This may be useful to diagnose influential observations (outliers that may affect the regression output). In this graph, we particularly focus on the upper right and lower right corners for the existence of influential observations. The picture also includes dashed lines (Cook's distance). Any observations falling outside the the Cook's distance may be treated as influential. The graph above suggests that there are no influential observations. 


Here is a simulated simple regression together with diagnostic pictures. 
```{r}
set.seed(1) # for replication
n   <- 200
x1  <- rnorm(n, mean=0, sd=1) 
y   <- 1 + 2*x1 + rnorm(n, mean=0, sd=1)
df1 <- tibble(id=1:n, y, x1)
reg_df1 <- lm(y ~ x1, data = df1)
# diagnostic plots
par(mfrow=c(2,2))
plot(reg_df1)
```

An alternative diagnostic plot tool that uses `ggplot`: 
```{r}
# diagnostics using lindia package 
library(lindia)
reg_df1 %>% gg_diagnose(plot.all=TRUE)
```

# Multiple Linear Regression 

The Boston house value data set includes several features. To include all the 
variables in the regression we can use the following command: 
```{r}
reg2 <- lm(medv ~ . , data = Boston)
summary(reg2)
```

If we want to exclude a variable, say age, we can use: 
```{r}
reg3 <- lm(medv ~ . -age, data = Boston)
summary(reg3)
```

Also remove indus
```{r}
reg4 <- lm(medv ~ . -age -indus, data = Boston)
summary(reg4)
```

Regression diagnostics: 
```{r}
par(mfrow=c(2,2))
plot(reg4)
```

These plots suggest that there is still some evidence of nonlinearity. 

## Interaction Effects  

To add the interaction between `lstat` and `age` we can just use 
```{r}
reg5 <- lm(medv ~ lstat * age, data = Boston)
summary(reg5)
```

Note that all variables are automatically included. Alternatively we can use 

```{r}
reg6 <- lm(medv ~ lstat + age + lstat:age, data = Boston)
summary(reg6)
```

## Nonlinear Transformations 

It's easy to add nonlinear transformations of variables such as quadratics, 
logs, higher order terms, etc. For example, to add quadratic terms we use 
```{r}
reg7 <- lm(medv ~ lstat + I(lstat^2), data = Boston)
summary(reg7)
```

Quadratic term is statistically significant. To compare the fit of the 
quadratic fit and the linear fit we can just use `anova` function: 
```{r}
anova(reg1, reg7)
```

Note that reg1 (model1) is nested within reg7 (model2). This is the simple F test. 
The result suggest that model2 is superior. 

Let's check the residual diagnostics to see if there are still unmodeled nonlinearity: 
```{r}
par(mfrow=c(2,2))
plot(reg7)
```


To add higher order polynomial terms, we can use `poly()` function within the `lm()` as follows. For example, to add the fifth order polynomial of lstat: 
```{r}
reg8 <- lm(medv ~ poly(lstat,5), data = Boston)
summary(reg8)
```

## Qualitative Predictors
We can easily add qualitative (dummy variables) in the multiple regression. This example is from the ISLR textbook: 
```{r}
library(ISLR)
names(Carseats)
fit1 <- lm(Sales~ . + Income:Advertising + Price:Age, data=Carseats)
summary(fit1)
```

ShelveLoc is an indicator of the quality of the shelving location (bad, medium, good). 
Because ShelveLoc is defined as a factor variable, R automaticaly included dummy variables (one of the levels is used as the based group). 
```{r}
contrasts(Carseats$ShelveLoc)
```

# Comparing Training vs Test 

Let's go back to the Boston house data. We want to compare the prediction performance of two models, linear model vs quadratic model in terms of lstat. 

We split the sample into training part and test part randomly. To this end, we can use 
`sample()` function. 
```{r}
set.seed(1)
train <- sample(506, 253)
```
Note that `set.seed()` is required for replication. 
There are $n=506$ observations in the Boston house data set. A random half will be 
used in training (estimation) and the other half will be used in the testing. Note that 
`train` contains row numbers of the observations that are selected to be included in the training sample. More explicitly, we can create two data sets for training and testing from the Boston house data set: 
```{r}
train_Boston <- Boston[train,]
test_Boston <- Boston[-train,]
```

Note that, `-train` index only selects observations that are **not** in the training set. 
Now, we are ready to estimate our alternative models using only training data: 
```{r}
lfit <- lm(medv ~ lstat, data = train_Boston)
qfit <- lm(medv ~ lstat + I(lstat^2), data = train_Boston) 
```

We compute the predictions using only the test data set and then compare the alternative models using Mean Squared Error (MSE)

```{r}
lin_predict <- predict(lfit, test_Boston)
lin_error <- test_Boston$medv - lin_predict
MSE_lfit <- mean(lin_error^2)
MSE_lfit
```

Similarly, for the quadratic fit: 
```{r}
qu_predict <- predict(qfit, test_Boston)
qu_error <- test_Boston$medv - qu_predict
MSE_qfit <- mean(qu_error^2)
MSE_qfit
```

The quadratic model has a much smaller MSE suggesting a more successful prediction model. 

# Test and Training MSE revisited 

Let us consider a simulation experiment in which we know the true relationship but estimate the model using different levels of complexity. 
```{r}
set.seed(1) # for replication
n   <- 100
x1  <- runif(n,-2,5)
f   <- -x1^3 + 5*x1^2 -x1 +5 
y   <- f + rnorm(n, mean=0, sd=3)
df <- tibble(id=1:n, y, x1)
head(df) 

df %>% ggplot(aes(x=x1,y=y))+
  geom_point() +
  geom_line(aes(x1,f))
```

Determine the training and test sets: 
```{r}
set.seed(1)
train_df <- sample(n,n/2)
# note that train_df contains observation numbers 
train_data <- df[train_df,]
test_data <- df[-train_df,]
```

We will estimate polynomial regressions upto order 6. 
```{r}
maxd = 6
trMSE = rep(0,maxd)
teMSE = rep(0,maxd)

for (i in 1:maxd) {
  trainfit <- lm(y ~ poly(x1, i), data=train_data)
  teMSE[i] <- mean((test_data$y - predict(trainfit, test_data) )^2)
  trMSE[i] <- mean(resid(trainfit)^2)
}
```


```{r}
MSE <- tibble(model=rep(1:maxd,2), 
              MSEsubset=rep(c("train","test"), each = maxd), 
              MSE=c(trMSE,teMSE))
MSE
```

Graph of MSEs: 
```{r}
MSE %>% ggplot(aes(model,MSE, color=MSEsubset))+
  geom_point() + 
  geom_line() 
```

As expected, training MSE keeps getting smaller as the order of the polynomial increases. On the other hand, test MSE is minimum at degree=3 and then increases. This suggests that the most successful prediction model is the one that includes third power (which is the true model). 




<div class="tocify-extend-page" data-unique="tocify-extend-page" style="height: 0;"></div>


