Downloaded and adapted from NbViewer

*Adapted from Chapter 3 of An Introduction to Statistical Learning*

statsmodels : basic tools in statistics

pandas : tools for real database analysis

matplotlib : best visualization library

scikit-learn : most used library in machine learning

In [10]:

```
# imports
import pandas as pd
import matplotlib.pyplot as plt
# this allows plots to appear directly in the notebook
%matplotlib inline
#figsize = (16,8)
figsize = (8,5)
```

Let's take a look at some data, ask some questions about that data, and then use linear regression to answer those questions!

In [11]:

```
# read data into a DataFrame
#data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)
data = pd.read_csv('Advertising.csv', index_col=0)
data.head()
#data[199:200]
```

Out[11]:

What are the **features**?

**TV**: advertising dollars spent on TV for a single product in a given market (in thousands of dollars)**Radio**: advertising dollars spent on Radio**Newspaper**: advertising dollars spent on Newspaper

What is the **response**?

**Sales**: sales of a single product in a given market (in thousands of widgets)

In [12]:

```
# print the shape of the DataFrame
data.shape
```

Out[12]:

There are 200 **observations**, and thus 200 markets in the dataset.

In [13]:

```
# visualize the relationship between the features and the response using scatterplots
fig, axs = plt.subplots(1, 3, sharey=True)
data.plot(kind='scatter', x='TV', y='Sales', ax=axs[0], figsize= figsize)
data.plot(kind='scatter', x='Radio', y='Sales', ax=axs[1])
data.plot(kind='scatter', x='Newspaper', y='Sales', ax=axs[2])
```

Out[13]:

Let's pretend you work for the company that manufactures and markets this widget. The company might ask you the following: On the basis of this data, how should we spend our advertising money in the future?

This general question might lead you to more specific **questions**:

- Is there a relationship between ads and sales?
- How strong is that relationship?
- Which ad types contribute to sales?
- What is the effect of each ad type of sales?
- Given ad spending in a particular market, can sales be predicted?

We will explore these questions below!

Simple linear regression is an approach for predicting a **quantitative response** using a **single feature** (or "predictor" or "input variable"). The model takes the following form:

What does each term represent?

- $Y$ is the response
- $X$ is the feature
- $\beta_0$ is the intercept
- $\beta_1$ is the coefficient for $X$

Together, $\beta_0$ and $\beta_1$ are called the **model coefficients**. To answer the questions, we must "estimate" (or "learn") the values of these coefficients. And once we've learned these coefficients, we can use them to predict Sales!

Generally speaking, coefficients are estimated using the **least squares criterion**, which means we are to find the line (mathematically) which minimizes the **sum of squared residuals** (or "sum of squared errors"):

What elements are present in the diagram?

- The black dots are the
**observed values**of x and y. - The blue line is our
**least squares line**. - The red lines are the
**residuals**, which are the distances between the observed values and the least squares line.

How do the model coefficients relate to the least squares line?

- $\hat\beta_0$ is an estimator of the
**intercept**$\beta_0$ - $\hat\beta_1$ is an estimator of the
**slope**(coefficient of $x$) $\beta_1$

Predictions at the points of the design are $$\hat y_i = \hat\beta_0 + \hat\beta_1 X_i$$

Let's use **Statsmodels** to estimate the model coefficients for the advertising data:

In [14]:

```
# this is the standard import if you're using "formula notation" (similar to R)
import statsmodels.formula.api as smf
# create a fitted model in one line
lm = smf.ols(formula='Sales ~ TV', data=data).fit()
# print the coefficients
lm.params
```

Out[14]:

How do we interpret the TV coefficient $\beta_1$?

- A "unit" increase in TV ad spending is
**associated with**a 0.047537 "unit" increase in Sales. - Or more clearly: An additional $1,000 spent on TV ads is
**associated with**an increase in sales of 47 widgets.

(Note that if an increase in TV ad spending was associated with a **decrease** in sales, $\beta_1$ would be **negative**)

Let's say that there was a new market where the TV advertising spend was **$50,000**. What would we predict for the Sales in that market?

In [15]:

```
# manually calculate the prediction
sales = 1000*(7.032594 + 0.047537*50)
print("expected Sales = {} widgets".format(sales))
```

In [16]:

```
# use the model to make predictions on a new value
X_new = pd.DataFrame({'TV' : [50]})
lm.predict(X_new)
```

Out[16]:

Let's make predictions for the **smallest and largest observed values of x**, and then use the predicted values to plot the least squares line:

In [17]:

```
# create a DataFrame with the minimum and maximum values of TV
X_new = pd.DataFrame({'TV': [data.TV.min(), data.TV.max()]})
#X_new.head()
# make predictions for those x values and store them
preds = lm.predict(X_new)
#preds
# first, plot the observed data
data.plot(kind='scatter', x='TV', y='Sales')
# then, plot the least squares line
plt.plot(X_new, preds, c='red', linewidth=2)
```

Out[17]:

Statsmodels calculates 95% confidence intervals on the model coefficients. It means that if we assume that the model $Y=\beta_0+\beta_1 X +\xi$ holds then with probability tending to 95%, the "true" coefficients $\beta_0$ and $\beta_1$ belong to these intervals.

In [18]:

```
# print the confidence intervals for the model coefficients
lm.conf_int()
```

Out[18]:

We want to study the following test problem:

**null hypothesis:**There is no relationship between TV ads and Sales $$H_0 : \beta_1 = 0$$**alternative hypothesis:**There is a relationship between TV ads and Sales $$H_1 : \beta_1\neq0$$

How do we test this hypothesis? Intuitively, we reject the null (and thus believe the alternative) if the 95% confidence interval **does not include zero**. Conversely, the **p-value** represents the probability that the coefficient is actually zero:

In [19]:

```
# print the p-values for the model coefficients
lm.pvalues
```

Out[19]:

If the 95% confidence interval **includes zero**, the p-value for that coefficient will be **greater than 0.05**. If the 95% confidence interval **does not include zero**, the p-value will be **less than 0.05**. Thus, a p-value less than 0.05 is one way to decide whether there is likely a relationship between the feature and the response. (Again, using 0.05 as the cutoff is just a convention.)

In this case, the p-value for TV is far less than 0.05, and so we have a high confidence in rejecting ($H_0$). As a consequence, we highly believe that there is a strong connection between TV ads and Sales.

(Note that we generally ignore the p-value for the intercept).

The most common way to evaluate the overall fit of a linear model is by the **R-squared** value. R-squared is the **proportion of variance explained**, meaning the proportion of variance in the observed data that is explained by the model, or the reduction in error over the **null model**. (The null model just predicts the mean of the observed response, and thus it has an intercept and no slope.)

where $\hat y$ is the prediction vector via least squares.

R-squared is between 0 and 1, and higher is better because it means that more variance is explained by the model. Here's an example of what R-squared "looks like":

You can see that the **blue line** explains some of the variance in the data (R-squared=0.54), the **green line** explains more of the variance (R-squared=0.64), and the **red line** fits the training data even further (R-squared=0.66). (Does the red line look like it's overfitting?)

Let's calculate the R-squared value for our simple linear model:

In [20]:

```
# print the R-squared value for the model
lm.rsquared
```

Out[20]:

Is that a "good" R-squared value? It's hard to say. The threshold for a good R-squared value depends widely on the domain. Therefore, it's most useful as a tool for **comparing different models**.

Simple linear regression can easily be extended to include multiple features. This is called **multiple linear regression**:

Each $X^{(j)}$ represents a different feature ( = coordinates of the design $X=(X^{(1)}, \ldots, X^{(k)})$, and each feature has its own coefficient. In this case:

$$\boxed{Y = \beta_0 + \beta_1 \times TV + \beta_2 \times Radio + \beta_3 \times Newspaper +\xi}$$Let's use Statsmodels to estimate these coefficients:

In [21]:

```
# create a fitted model with all three features
lm = smf.ols(formula='Sales ~ TV + Radio + Newspaper', data=data).fit()
# print the coefficients
lm.params
```

Out[21]:

How do we interpret these coefficients? For a given amount of Radio and Newspaper ad spending, an **increase of $1000 in TV ad spending** is associated with an **increase in Sales of 45.765 widgets**.

A lot of the information we have been reviewing piece-by-piece is available in the model summary output:

In [15]:

```
# print a summary of the fitted model
lm.summary()
```

Out[15]:

What are a few key things we learn from this output?

- TV and Radio have significant
**p-values**, whereas Newspaper does not. Thus we reject the null hypothesis for TV and Radio (that there is no association between those features and Sales), and fail to reject the null hypothesis for Newspaper. - TV and Radio ad spending are both
**positively associated**with Sales, whereas Newspaper ad spending is**slightly negatively associated**with Sales. (However, this is irrelevant since we have failed to reject the null hypothesis for Newspaper.) - This model has a higher
**R-squared**(0.897) than the previous model, which means that this model provides a better fit to the data than a model that only includes TV.

How do I decide **which features to include** in a linear model? Here's one idea:

- Try different models, and only keep predictors in the model if they have small p-values.
- Check whether the R-squared value goes up when you add new predictors.

What are the **drawbacks** to this approach?

- Linear models rely upon a lot of
**assumptions**(such as the features being independent), and if those assumptions are violated (which they usually are), R-squared and p-values are less reliable. - Using a p-value cutoff of 0.05 means that if you add 100 predictors to a model that are
**pure noise**, 5 of them (on average) will still be counted as significant. - R-squared is susceptible to
**overfitting**, and thus there is no guarantee that a model with a high R-squared value will generalize. Below is an example:

In [14]:

```
# only include TV and Radio in the model
lm = smf.ols(formula='Sales ~ TV + Radio', data=data).fit()
lm.rsquared
```

Out[14]:

In [15]:

```
# add Newspaper to the model (which we believe has no association with Sales)
lm = smf.ols(formula='Sales ~ TV + Radio + Newspaper', data=data).fit()
lm.rsquared
```

Out[15]:

**R-squared will always increase as you add more features to the model**, even if they are unrelated to the response. Thus, selecting the model with the highest R-squared is not a reliable approach for choosing the best linear model.

There is alternative to R-squared called **adjusted R-squared** that penalizes model complexity (to control for overfitting), but it generally under-penalizes complexity.

So is there a better approach to feature selection? **Cross-validation.** It provides a more reliable estimate of out-of-sample error, and thus is a better way to choose which of your models will best **generalize** to out-of-sample data. There is extensive functionality for cross-validation in scikit-learn, including automated methods for searching different sets of parameters and different models. Importantly, cross-validation can be applied to any model, whereas the methods described above only apply to linear models.

In [17]:

```
# print a summary of the fitted model that includes only TV and Radio in the model
lm = smf.ols(formula='Sales ~ TV + Radio', data=data).fit()
lm.rsquared
lm.summary()
```

Out[17]:

Let's redo some of the Statsmodels code above in scikit-learn:

In [49]:

```
# create X and y
feature_cols = ['TV', 'Radio', 'Newspaper']
X = data[feature_cols]
y = data.Sales
# follow the usual sklearn pattern: import, instantiate, fit
from sklearn.linear_model import LinearRegression
lm = LinearRegression()
lm.fit(X, y)
# print intercept and coefficients
print lm.intercept_
print lm.coef_
```

In [50]:

```
# pair the feature names with the coefficients
zip(feature_cols, lm.coef_)
```

Out[50]:

In [51]:

```
# predict for a new observation
lm.predict([100, 25, 25])
```

Out[51]:

In [52]:

```
# calculate the R-squared
lm.score(X, y)
```

Out[52]:

Note that **p-values** and **confidence intervals** are not (easily) accessible through scikit-learn.