# Linear regression with one variable

## Contents

# Linear regression with one variable¶

Assume that you have \(N\) pairs of observations \((x_i, y_i)\) from two random variables \(X\) and \(Y\). Now, you suspect that there is a linear relationship between these two random variables. Namely, you suspect that there exist coefficients \(a\) and \(b\) such that:

where \(U\) is some unobserved factor that we are going to treat as noise.
How can you find \(a\) and \(b\) from the \(N\) observations we have?
This is a so-called *regression* problem.

Let’s develop the simplest possible approach for solving the regression problem.
It is called the *least squares* approach.
The approach basically says that you should pick \(a\) and \(b\) so as to minimize the sum of square errors:

The error here is the prediction you are making for \(y_i\) for given \(a\) and \(b\).

Okay, we proceed as usual. We take derivatives of \(L\) with respect to \(a\) and \(b\), set them equal to zero and solve for \(a\) and \(b\). Let’s do it:

Here is the other one:

Setting these two derivatives to zero, yields the following linear system:

This is a 2x2 system and we can solve it by substitution. Take the second equation and solve for \(b\):

where \(\hat{\mu}_X\) and \(\hat{\mu}_Y\) are the empirical estimates of the mean of \(X\) and \(Y\), respectively. Now let’s take this and substitute in the first equation of the linear system. We have:

Now the magic starts… Notice that the coefficient of \(a\) is actually the empirical estimate of the variance of \(X\):

Similarly, the right-hand-side is the empirical estimate of the covariance of \(X\) and \(Y\):

Putting everything together, gives us that:

Solving for \(a\):

which gives a relationship between \(a\) and the correlation coefficient between \(X\) and \(Y\):

This is very very interesting. Intuitively, dividing by \(\sigma_X\) removes the units of \(X\), multiplying with \(\sigma_Y\) puts units of \(Y\) and then you multiply with the correlation coefficient to get the direction right! Nice!

What about \(b\)? Let’s substitute back into the equation:

So, this is the difference between the mean of the data and the mean prediction of our fitted model.

Let’s end the theory by looking at the final square error. We will just plug in \(\hat{a}\) and \(\hat{b}\) in \(L\) and see what we get. This is the result:

What does this say? The following:

The error grows with the number of points. This makes sense. More points more error.

If the correlation coefficient is zero, then the error is maximized and it is \(N\) times the variance of \(Y\).

The error becomes zero if the correlation of coefficient is exactly one or minus one.

And this is the proof if you are interested:

## Example: Modeling `hvac`

as a function of `t_out`

¶

Let’s now calculate the estimate we developed for the correlation coefficient in the smart buildings dataset.
In particular, we are going to estimate the correlation coefficient between \(X=\)`t_out`

and \(Y=\)`hvac`

for heating and cooling.

```
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set(rc={"figure.dpi":100, 'savefig.dpi':300})
sns.set_context('notebook')
sns.set_style("ticks")
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('retina', 'svg')
import numpy as np
import scipy.stats as st
import requests
import os
def download(url, local_filename=None):
"""
Downloads the file in the ``url`` and saves it in the current working directory.
"""
data = requests.get(url)
if local_filename is None:
local_filename = os.path.basename(url)
with open(local_filename, 'wb') as fd:
fd.write(data.content)
# The url of the file we want to download
url = 'https://raw.githubusercontent.com/PurdueMechanicalEngineering/me-297-intro-to-data-science/master/data/temperature_raw.xlsx'
download(url)
import pandas as pd
df = pd.read_excel('temperature_raw.xlsx')
df = df.dropna(axis=0)
df.head()
df_heating = df[df['t_out'] < 60]
df_cooling = df[df['t_out'] > 70]
df_off = df[(df['t_out'] >= 60) & (df['t_out'] <= 70)]
```

First, we do the cooling:

```
xdata = df_cooling['t_out']
ydata = df_cooling['hvac']
# Estimate the statistics
mu_X = xdata.mean()
mu_Y = ydata.mean()
sigma_X = xdata.std()
sigma_Y = ydata.std()
rho_XY = np.corrcoef(xdata, ydata)[0, 1]
# The a coefficient
a = rho_XY * sigma_Y / sigma_X
# The b coefficient
b = mu_Y - a * mu_X
# Print the results
print('Model coefficients for cooling: ')
print('a = {0:1.2f}'.format(a))
print('b = {0:1.2f}'.format(b))
```

```
Model coefficients for cooling:
a = 3.78
b = -229.95
```

Here is how you can evaluate the model in arbitrary points:

```
xs = np.linspace(xdata.min(), xdata.max())
ys = a * xs + b
```

Let’s visualize the model we just built:

```
fig, ax = plt.subplots()
ax.scatter(df_cooling['t_out'], df_cooling['hvac'], label='Cooling')
ax.plot(xs, ys, 'r--', lw=2, label='Linear cooling model')
ax.set_xlabel('t_out (F)')
ax.set_ylabel('hvac (kWh)')
plt.legend(loc='best');
```

Now for heating:

```
xdata = df_heating['t_out']
ydata = df_heating['hvac']
# Estimate the statistics
mu_X = xdata.mean()
mu_Y = ydata.mean()
sigma_X = xdata.std()
sigma_Y = ydata.std()
rho_XY = np.corrcoef(xdata, ydata)[0, 1]
# The a coefficient
a = rho_XY * sigma_Y / sigma_X
# The b coefficient
b = mu_Y - a * mu_X
# Print the results
print('Model coefficients for heating: ')
print('a = {0:1.2f}'.format(a))
print('b = {0:1.2f}'.format(b))
# Visualize
xs = np.linspace(xdata.min(), xdata.max())
ys = a * xs + b
fig, ax = plt.subplots()
ax.scatter(df_heating['t_out'], df_heating['hvac'], label='Cooling')
ax.plot(xs, ys, 'r--', lw=2, label='Linear cooling model')
ax.set_xlabel('t_out (F)')
ax.set_ylabel('hvac (kWh)')
plt.legend(loc='best');
```

```
Model coefficients for heating:
a = -4.99
b = 296.26
```