12.2. Regression Line#

Hide code cell source

path_data = '../../data/'

import numpy as np
import pandas as pd
from scipy.optimize import minimize

%matplotlib inline
import matplotlib.pyplot as plt

# Helper functions from 1201 (standard units and correlation)
def standard_units(values):
    return (values - np.mean(values)) / np.std(values)

def correlation(table, x, y):
    return np.mean(standard_units(table[x]) * standard_units(table[y]))

# Helper functions taught in this section (slope and intercept)
def slope(table, x, y):
    r = correlation(table, x, y)
    return r * np.std(table[y]) / np.std(table[x])

def intercept(table, x, y):
    return np.mean(table[y]) - slope(table, x, y) * np.mean(table[x])

stores = pd.read_csv(path_data + 'store_ad_sales.csv')
reps = pd.read_csv(path_data + 'sales_reps.csv')

A regional manager at a retail chain is planning next quarter’s advertising budget. The manager has already seen, in Correlation, that stores that spend more on advertising tend to sell more. Now the manager wants a number: if a store spends $8,000 a week on ads, how much should it expect to sell?

This section turns the association into a prediction. You will build a straight line, called the regression line, that gives a predicted sales figure for any ad budget. You first work in standard units, where the line has a very simple form. You then convert it to the original units, check it against NumPy, and use it to predict and to measure how far each store is from its prediction. Along the way you will meet an effect that surprises many managers: the best performers in one period tend to look less impressive in the next, even when nothing has gone wrong. Finally, you will score lines by their prediction error and see why this line is the best straight line for the data, the least squares line.

The data are the same 40 stores as in Correlation (store_ad_sales.csv): weekly ad spend and weekly sales, both in thousands of dollars. The 40 stores are a simulated teaching data set built to look like store records, not real company data.

12.2.1. From Association to Prediction#

In a prediction problem, one variable is used to predict another. The variable used for prediction is the feature (also called the predictor, or the \(x\) variable). The variable to be predicted is the target (or the \(y\) variable). Here the feature is a store’s ad spend and the target is its sales.

The scatter plot shows why a line is a reasonable choice: the points rise from lower left to upper right and cluster around a straight band.

fig, ax = plt.subplots(figsize=(6, 3.8))
ax.scatter(stores['ad_spend'], stores['sales'], s=25, color='tab:blue')
ax.set_xlabel('Weekly ad spend ($1,000s)')
ax.set_ylabel('Weekly sales ($1,000s)')
ax.set_title('Stores that spend more on ads tend to sell more')
plt.show()

print('Correlation r:', round(correlation(stores, 'ad_spend', 'sales'), 4))
../../_images/262c78e666f08342a5db64d3abc4833075f8f394490b02c89c6c39b8673bd1f4.png
Correlation r: 0.6894

The correlation is about 0.69, a fairly strong positive association. The points do not lie exactly on a line, so sales cannot be predicted perfectly. The goal is a rule that gives a sensible average sales figure for each ad budget. A straight line is the simplest such rule: it needs only two numbers, and it is easy to explain to a manager.

Stores with the same ad spend still differ in sales, so any prediction will be off for some stores. Later sections measure how far off. First, decide which line to use.

12.2.2. The Line in Standard Units#

Correlation used standard units to define \(r\). A value in standard units says how many standard deviations (SDs) it is above or below the mean. The two helper functions are repeated here (they are also in the hidden setup cell, so the exercises can use them).

def standard_units(values):
    "Return values measured in standard deviations from their mean."
    return (values - np.mean(values)) / np.std(values)

def correlation(table, x, y):
    "Average of the products of the standard units of x and y."
    return np.mean(standard_units(table[x]) * standard_units(table[y]))

stores['ad_su'] = standard_units(stores['ad_spend'])
stores['sales_su'] = standard_units(stores['sales'])

stores[['store', 'ad_su', 'sales_su']].head(4).round(2)
store ad_su sales_su
0 S01 0.20 -0.08
1 S02 0.64 0.44
2 S03 -1.26 -1.85
3 S04 -0.75 -0.57

Store S01 has an ad-spend value of 0.2 in standard units, meaning its ad spend is a little above the average of the stores.

In standard units, both variables have mean 0 and \(SD\) 1, so the cloud of points is centered at \((0, 0)\) and has the same spread in both directions. The regression line in standard units has two properties:

  • It passes through the point \((0, 0)\), the center of the cloud (a store with average ad spend is predicted to have average sales).

  • Its slope is \(r\), the correlation.

So the rule is:

\[\text{predicted sales (standard units)} = r \times \text{ad spend (standard units)}\]

Because \(r\) is between \(-1\) and \(1\), the predicted value is never farther from 0 than the feature itself. You can see this by drawing the line next to the diagonal \(y = x\), which would be the rule if \(r\) were 1.

ad_sales_r = correlation(stores, 'ad_spend', 'sales')

fig, ax = plt.subplots(figsize=(6, 4.5))
ax.scatter(stores['ad_su'], stores['sales_su'], s=25, color='tab:blue', label='Stores')
z = np.array([-2, 2])
ax.plot(z, z, color='gray', linestyle='--', label='y = x (would need r = 1)')
ax.plot(z, ad_sales_r * z, color='tab:red', lw=2.5, label=f'Regression line, slope r = {ad_sales_r:.2f}')
ax.axhline(0, color='lightgray', lw=0.8)
ax.axvline(0, color='lightgray', lw=0.8)
ax.set_xlabel('Ad spend (standard units)')
ax.set_ylabel('Sales (standard units)')
ax.set_title('In standard units the regression line has slope r')
ax.legend(loc='upper left', fontsize=9)
plt.show()
../../_images/3f05a1f40bda27a5fdca4479de647656c7f030552e2e5537aed4a96351e5779e.png

The red regression line is flatter than the gray diagonal. For each SD a store’s ad spend is above average, the line predicts sales to be only \(r \approx 0.69\) SDs above average.

For a store that spends $8,000 a week, work through the steps: convert the ad spend to standard units, multiply by \(r\), then convert the result back to dollars.

ad_mean, ad_sd = np.mean(stores['ad_spend']), np.std(stores['ad_spend'])
sales_mean, sales_sd = np.mean(stores['sales']), np.std(stores['sales'])

new_ad = 8
new_ad_su = (new_ad - ad_mean) / ad_sd          # step 1: feature in standard units
pred_su = ad_sales_r * new_ad_su                         # step 2: multiply by r
pred_sales = pred_su * sales_sd + sales_mean    # step 3: back to $1,000s

print('Ad spend in standard units:    ', round(new_ad_su, 2))
print('Predicted sales, standard units:', round(pred_su, 2))
print('Predicted sales ($1,000s):      ', round(pred_sales, 1))
Ad spend in standard units:     0.94
Predicted sales, standard units: 0.64
Predicted sales ($1,000s):       88.5

A store that spends $8,000 a week is 0.94 SDs above the average ad spend. The line predicts its sales to be 0.64 SDs above average sales, which is about $88,500 a week.

### Exercise: Prediction in Standard Units
# Using the store data:
#   1. Find r for ad_spend and sales.
#   2. Convert a $2,000 ad spend to standard units, using the mean and SD of ad_spend.
#   3. Multiply by r to get the predicted sales in standard units.
#   4. Convert back to $1,000s using the mean and SD of sales.
#   5. Print the three values below, rounded to 2 decimals.
# Print exactly:
# Ad spend (standard units): -1.26
# Predicted sales (standard units): -0.87
# Predicted sales ($1,000s): 65.27
import numpy as np
import pandas as pd

ex_stores = pd.read_csv('../../data/store_ad_sales.csv')
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
import pandas as pd

ex_stores = pd.read_csv('../../data/store_ad_sales.csv')

def standard_units(values):
    return (values - np.mean(values)) / np.std(values)

r = np.mean(standard_units(ex_stores['ad_spend']) * standard_units(ex_stores['sales']))

ad_su = (2 - np.mean(ex_stores['ad_spend'])) / np.std(ex_stores['ad_spend'])
pred_su = r * ad_su
pred_sales = pred_su * np.std(ex_stores['sales']) + np.mean(ex_stores['sales'])

print('Ad spend (standard units):', round(ad_su, 2))
print('Predicted sales (standard units):', round(pred_su, 2))
print('Predicted sales ($1,000s):', round(pred_sales, 2))
Ad spend (standard units): -1.26
Predicted sales (standard units): -0.87
Predicted sales ($1,000s): 65.27

12.2.3. The Regression Effect#

The fact that the regression line has slope \(r\) in standard units, with \(|r| < 1\) unless the points lie exactly on a line, has a striking consequence. Consider the file sales_reps.csv: first-quarter (Q1) and second-quarter (Q2) sales, in thousands of dollars, for 200 sales representatives. The 200 reps are simulated, and simulation is used here on purpose: each rep’s results are built from a fixed skill plus random luck, so you know the regression effect below is not caused by anything the reps did.

print(reps.shape)
reps.head(4)
(200, 3)
rep_id q1_sales q2_sales
0 R001 127.4 120.7
1 R002 89.6 105.4
2 R003 134.9 107.7
3 R004 98.8 86.9
r_reps = correlation(reps, 'q1_sales', 'q2_sales')
print('Mean Q1 sales:', round(np.mean(reps['q1_sales']), 1))
print('Mean Q2 sales:', round(np.mean(reps['q2_sales']), 1))
print('Correlation r between Q1 and Q2:', round(r_reps, 2))
Mean Q1 sales: 99.6
Mean Q2 sales: 100.1
Correlation r between Q1 and Q2: 0.52

Both quarters average about $100,000 and the correlation is about 0.52: reps who sell more in one quarter tend to sell more in the next, but the relationship is far from perfect. Now look at the best performers. Take the top 10% in Q1 (the 20 reps at or above the 90th percentile) and see what happened to them in Q2.

cutoff = np.percentile(reps['q1_sales'], 90)
top = reps[reps['q1_sales'] >= cutoff]

print('Number of top reps:         ', len(top))
print('Their average Q1 sales:     ', round(np.mean(top['q1_sales']), 1))
print('Their average Q2 sales:     ', round(np.mean(top['q2_sales']), 1))
print('Share who sold less in Q2:  ', np.mean(top['q2_sales'] < top['q1_sales']))
Number of top reps:          20
Their average Q1 sales:      137.9
Their average Q2 sales:      120.5
Share who sold less in Q2:   0.8

The top 20 reps averaged about 138 in Q1 but only about 120 in Q2. Sixteen of the 20 sold less in Q2 than in Q1. They are still above the overall average of about 100, but they moved a long way back toward it.

This is the regression effect, also called regression to the mean. The scatter plot shows it.

fig, ax = plt.subplots(figsize=(6.5, 4.5))
ax.scatter(reps['q1_sales'], reps['q2_sales'], s=18, color='lightgray', label='All 200 reps')
ax.scatter(top['q1_sales'], top['q2_sales'], s=30, color='tab:red', label='Top 10% in Q1')
lims = np.array([50, 160])
ax.plot(lims, lims, color='gray', linestyle='--', label='Same sales in both quarters')
slope_reps = slope(reps, 'q1_sales', 'q2_sales')
int_reps = intercept(reps, 'q1_sales', 'q2_sales')
ax.plot(lims, slope_reps * lims + int_reps, color='tab:blue', lw=2.5, label='Regression line')
ax.set_xlabel('Q1 sales ($1,000s)')
ax.set_ylabel('Q2 sales ($1,000s)')
ax.set_title('Q1 stars fall below the diagonal in Q2')
ax.legend(fontsize=9, loc='upper left')
plt.show()
../../_images/0bc02702b54dde93b9c553e7286cfa15468a6cfb981708f19dbd91e662c32525.png

The red points (the Q1 stars) sit mostly below the dashed diagonal: most sold less in Q2. The blue regression line passes through the point of averages (about 99.6 in Q1 and 100.1 in Q2). Because the two quarters have about the same average, the line crosses the diagonal near that point, at about 100.6. It is flatter than the diagonal, so it falls below the diagonal for high Q1 values and rises above it for low Q1 values.

Why does this happen? A rep’s sales in a quarter reflect two things:

  • Skill, which is stable from quarter to quarter.

  • Luck: which customers called, which deals closed on time, which accounts happened to renew.

Reps reach the top 10% in Q1 through high skill, good luck, or both, so as a group they had better-than-average luck in Q1. In Q2 their skill is still there, but luck is a fresh draw, and on average a fresh draw is average. So the group’s average Q2 sales fall back toward the mean, though not all the way. The weaker the link between the two quarters (the smaller \(r\)), the further they fall.

The same thing happens at the bottom: the lowest 10% in Q1 tend to do better in Q2, for the same reason. In the output below, the bottom group rises from about 60 to about 81.

bottom = reps[reps['q1_sales'] <= np.percentile(reps['q1_sales'], 10)]
print('Bottom 10% in Q1 -> average Q1:', round(np.mean(bottom['q1_sales']), 1),
      ' average Q2:', round(np.mean(bottom['q2_sales']), 1))
Bottom 10% in Q1 -> average Q1: 60.4  average Q2: 81.1

A warning for managers

The regression effect is not a slump, and it is not a sign that the stars got complacent or that the low performers learned their lesson. If a manager gives a bonus to the top 10% and then sees their sales fall, the manager may conclude that bonuses backfire. If the manager scolds the bottom 10% and sees them improve, it may look as if scolding works. Both conclusions can be produced by the regression effect alone. To judge a bonus or a training program, compare against a group that did not receive it, as in the randomized experiments of Causality, rather than comparing a selected extreme group with its own earlier result.

### Exercise: Regression Effect in Sales Reps
# Using the sales reps data (sales_reps.csv):
#   1. Select the reps in the bottom 25% of Q1 sales: those with Q1 sales at or
#      below the 25th percentile of q1_sales (use np.percentile).
#   2. Print how many reps are in the group.
#   3. Print their average Q1 sales and their average Q2 sales, rounded to 1 decimal.
# Print exactly:
# Number of reps: 50
# Average Q1: 69.4
# Average Q2: 85.1
import numpy as np
import pandas as pd

ex_reps = pd.read_csv('../../data/sales_reps.csv')
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
import pandas as pd

ex_reps = pd.read_csv('../../data/sales_reps.csv')

cutoff = np.percentile(ex_reps['q1_sales'], 25)
low = ex_reps[ex_reps['q1_sales'] <= cutoff]

print('Number of reps:', len(low))
print('Average Q1:', round(np.mean(low['q1_sales']), 1))
print('Average Q2:', round(np.mean(low['q2_sales']), 1))
# Their average moves up toward the overall mean of about 100 in Q2.
Number of reps: 50
Average Q1: 69.4
Average Q2: 85.1

12.2.4. The Line in Original Units#

Standard units are convenient for thinking, but a manager wants predictions in dollars. Now convert the regression line to the original units. A line is described by its slope (how much the target changes when the feature increases by 1, which is \(r\) in standard units) and its intercept (the predicted value when the feature, or \(x\) variable, is 0):

\[\text{predicted } y = \text{slope} \times x + \text{intercept}\]

Start from the standard-units rule, \(\dfrac{\hat y - \bar y}{\text{SD}(y)} = r \cdot \dfrac{x - \bar x}{\text{SD}(x)}\), where \(\hat y\) (“y hat”) is the predicted value. Solving for \(\hat y\) gives:

\[\text{slope} = r \times \frac{\text{SD of } y}{\text{SD of } x}, \qquad \text{intercept} = \text{mean of } y - \text{slope} \times \text{mean of } x\]

The intercept formula says the line passes through the point of averages \((\bar x, \bar y)\). Turn the two formulas into functions. Both take a table and the names of the feature and target columns.

def slope(table, x, y):
    "Slope of the regression line for predicting column y from column x."
    r = correlation(table, x, y)
    return r * np.std(table[y]) / np.std(table[x])

def intercept(table, x, y):
    "Intercept of the regression line: the line passes through the point of averages."
    return np.mean(table[y]) - slope(table, x, y) * np.mean(table[x])

store_slope = slope(stores, 'ad_spend', 'sales')
store_intercept = intercept(stores, 'ad_spend', 'sales')
print('Slope:    ', round(store_slope, 2))
print('Intercept:', round(store_intercept, 2))
Slope:     3.87
Intercept: 57.54

The regression line for the stores is

\[\text{predicted sales} = 3.87 \times \text{ad spend} + 57.54.\]

Units of the slope. The slope is in units of the target per unit of the feature: about 3.87 thousand dollars of weekly sales per thousand dollars of weekly ad spend. The fitted line predicts about $3,870 more weekly sales for each additional $1,000 of weekly ad spend. This is a difference between stores along the line, not a promise that raising one store’s ad budget will raise its sales by that amount (recall the caution about causation in Correlation).

Units of the intercept. The intercept is in the units of the target: about $57,540 of weekly sales for a store that spends nothing on ads. The data have no store near zero ad spend (the smallest budget is $1,000), so treat the intercept as the part of the line that sets its height, not as a forecast.

You can check the formulas against NumPy’s np.polyfit, which fits a straight line (degree 1) to the points and returns the slope and then the intercept.

np_slope, np_intercept = np.polyfit(stores['ad_spend'], stores['sales'], 1)
print('np.polyfit slope:    ', round(np_slope, 2))
print('np.polyfit intercept:', round(np_intercept, 2))
print('Same as the formulas:', np.isclose(np_slope, store_slope) and np.isclose(np_intercept, store_intercept))
np.polyfit slope:     3.87
np.polyfit intercept: 57.54
Same as the formulas: True

The two methods agree. The last part of this section, Choosing the Best Line, explains why this line is the best straight-line predictor; for now, you can think of np.polyfit as a second route to the same line.

The same two functions work for the sales reps. If a rep sold 130 in Q1, what does the line predict for Q2?

reps_slope = slope(reps, 'q1_sales', 'q2_sales')
reps_intercept = intercept(reps, 'q1_sales', 'q2_sales')
print('Slope:', round(reps_slope, 2), ' Intercept:', round(reps_intercept, 2))
print('Predicted Q2 for a rep with Q1 = 130:', round(reps_slope * 130 + reps_intercept, 1))
Slope: 0.49  Intercept: 51.32
Predicted Q2 for a rep with Q1 = 130: 115.0

The slope is about 0.49, well below 1, and a rep who sold 130 in Q1 is predicted to sell about 115 in Q2: the regression effect again, now in the original units.

### Exercise: Slope and Intercept for Sales Reps
# Using the sales reps data (sales_reps.csv), predict Q2 sales from Q1 sales:
#   1. Compute r for q1_sales and q2_sales.
#   2. Compute the slope (r * SD of q2 / SD of q1) and the intercept
#      (mean of q2 - slope * mean of q1).
#   3. Predict Q2 sales for a rep who sold 90 in Q1.
#   4. Print the three values below, rounded to 2 decimals.
# Print exactly:
# Slope: 0.49
# Intercept: 51.32
# Predicted Q2 for Q1 = 90: 95.41
import numpy as np
import pandas as pd

ex_reps = pd.read_csv('../../data/sales_reps.csv')
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
import pandas as pd

ex_reps = pd.read_csv('../../data/sales_reps.csv')

def standard_units(values):
    return (values - np.mean(values)) / np.std(values)

q1, q2 = ex_reps['q1_sales'], ex_reps['q2_sales']
r = np.mean(standard_units(q1) * standard_units(q2))
reps_slope = r * np.std(q2) / np.std(q1)
reps_intercept = np.mean(q2) - reps_slope * np.mean(q1)

print('Slope:', round(reps_slope, 2))
print('Intercept:', round(reps_intercept, 2))
print('Predicted Q2 for Q1 = 90:', round(reps_slope * 90 + reps_intercept, 2))
Slope: 0.49
Intercept: 51.32
Predicted Q2 for Q1 = 90: 95.41

12.2.5. Fitted Values and Residuals#

The prediction for a store already in the data is its fitted value: the height of the regression line at that store’s ad spend. The difference between what the store actually sold and its fitted value is its residual:

\[\text{residual} = \text{observed value} - \text{fitted value}\]

A positive residual means the store sold more than the line predicted; a negative residual means it sold less. Add both to the table.

stores['fitted'] = store_slope * stores['ad_spend'] + store_intercept
stores['residual'] = stores['sales'] - stores['fitted']
stores[['store', 'ad_spend', 'sales', 'fitted', 'residual']].head(5).round(1)
store ad_spend sales fitted residual
0 S01 6.0 77.3 80.7 -3.4
1 S02 7.2 85.3 85.4 -0.1
2 S03 2.0 50.2 65.3 -15.1
3 S04 3.4 69.8 70.7 -0.9
4 S05 10.0 91.4 96.2 -4.8

Store S01 spent $6,000 a week and sold $77,300; the line predicted about $80,700, so its residual is about \(-3.4\) (it did a bit worse than the line expected). Here is the line drawn through the scatter, with a few residuals shown as vertical segments.

fig, ax = plt.subplots(figsize=(7, 4.2))
ax.scatter(stores['ad_spend'], stores['sales'], s=25, color='tab:blue', label='Stores')
xs = np.array([1, 10])
ax.plot(xs, store_slope * xs + store_intercept, color='tab:red', lw=2.5, label='Regression line')
for i in range(0, 40, 5):
    row = stores.iloc[i]
    ax.plot([row['ad_spend']] * 2, [row['fitted'], row['sales']], color='black', lw=1)
ax.set_xlabel('Weekly ad spend ($1,000s)')
ax.set_ylabel('Weekly sales ($1,000s)')
ax.set_title('The regression line and some residuals (vertical segments)')
ax.legend(loc='upper left')
plt.show()

print('Average residual:      ', round(np.mean(stores['residual']), 2))
print('Largest absolute residual:', round(np.max(np.abs(stores['residual'])), 1))
../../_images/cdafe02ef2ea28a1a23c0d5f23629626babb80b4393108b3a21b5b80a5bc7746.png
Average residual:       0.0
Largest absolute residual: 25.4

The residuals average 0 (to within rounding), which is a property of the regression line: its positive and negative misses balance. The largest miss is about $25,400, so individual stores can be far from their predictions even though the line describes the overall pattern well.

Predicting for a new store. Suppose a store not in the data plans to spend $5,000 a week on ads. Use the slope and the intercept.

new_spend = 5
print(f'Predicted weekly sales for a $5,000 ad budget: ${store_slope * new_spend + store_intercept:.1f} thousand')
print('Observed ad spend ranges from', stores['ad_spend'].min(), 'to', stores['ad_spend'].max())
Predicted weekly sales for a $5,000 ad budget: $76.9 thousand
Observed ad spend ranges from 1.0 to 10.0

The prediction is about $76,900 a week, and $5,000 is well inside the range of observed ad budgets.

Do not extrapolate

The line is built from stores that spend between $1,000 and $10,000 a week. A prediction inside that range (interpolation) rests on evidence. A prediction far outside it (extrapolation) assumes the straight-line pattern continues where there are no data. Ad spend of $30,000 a week would give a predicted sales figure of about $173,600, but sales may level off long before then, because the audience can only be reached so many times. The line itself will happily produce a number for any input; it cannot warn you that the number is unreliable.

extreme_spend = 30
print('Line output at $30,000 ad spend (outside the data):', round(store_slope * extreme_spend + store_intercept, 1))
Line output at $30,000 ad spend (outside the data): 173.6
### Exercise: Fitted Values and Residuals
# Using the store data:
#   1. Compute the slope and intercept of the regression line for sales on ad_spend.
#   2. Compute the fitted value and the residual (observed - fitted) for every store.
#   3. Find the store with the most negative residual (it did worst relative to the line).
#   4. Print the store ID and its residual (rounded to 2 decimals), and whether the
#      average residual is 0 up to rounding error (use np.isclose(value, 0)).
# Print exactly:
# Store with most negative residual: S10
# Its residual: -25.37
# Average residual is 0: True
import numpy as np
import pandas as pd

ex_stores = pd.read_csv('../../data/store_ad_sales.csv')
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
import pandas as pd

ex_stores = pd.read_csv('../../data/store_ad_sales.csv')

def standard_units(values):
    return (values - np.mean(values)) / np.std(values)

x, y = ex_stores['ad_spend'], ex_stores['sales']
r = np.mean(standard_units(x) * standard_units(y))
ex_slope = r * np.std(y) / np.std(x)
ex_intercept = np.mean(y) - ex_slope * np.mean(x)

fitted = ex_slope * x + ex_intercept
residual = y - fitted

worst = residual.idxmin()
print('Store with most negative residual:', ex_stores.loc[worst, 'store'])
print('Its residual:', round(residual[worst], 2))
print('Average residual is 0:', np.isclose(np.mean(residual), 0))
Store with most negative residual: S10
Its residual: -25.37
Average residual is 0: True

12.2.6. Choosing the Best Line#

You now have a regression line from two formulas (slope = r * SD_y/SD_x; intercept = y_bar - slope*x_bar). A fair question is why that line and not some other. A regional manager may have a rule of thumb, such as “every $1,000 of ads brings in $5,000 of sales, on top of a base of $50,000.” How would you show that one line is better than another?

This part gives a numerical answer. You will score any line by its typical prediction error, compare several lines on the same data, and let the computer search for the line with the smallest error. The winner is the regression line from the formulas, which is why it is also called the least squares line.

12.2.6.1. Measuring Prediction Error#

Take one candidate line, the manager’s rule of thumb: predicted sales = 50 + 5 x ad spend. For each store, the error of a prediction is the observed value minus the predicted value, in thousands of dollars of weekly sales. A positive error means the store sold more than the line predicted.

def line_predictions(table, a, b, x='ad_spend'):
    "Predicted values from the line  a + b * x."
    return a + b * table[x]

manager = stores.copy()
manager['predicted'] = line_predictions(manager, 50, 5)
manager['error'] = manager['sales'] - manager['predicted']
manager[['store', 'ad_spend', 'sales', 'predicted', 'error']].head()
store ad_spend sales predicted error
0 S01 6.0 77.3 80.0 -2.7
1 S02 7.2 85.3 86.0 -0.7
2 S03 2.0 50.2 60.0 -9.8
3 S04 3.4 69.8 67.0 2.8
4 S05 10.0 91.4 100.0 -8.6

Store S01 spent $6,000 on ads, so the rule predicts 50 + 5 x 6 = 80 and the store sold 77.3: an error of about -2.7. The goal is a single number that summarizes all 40 errors. The obvious choice is their average.

print('Average error:', round(manager['error'].mean(), 2))
print('Smallest error:', round(manager['error'].min(), 2))
print('Largest error: ', round(manager['error'].max(), 2))
Average error: 1.38
Smallest error: -23.6
Largest error:  24.0

The average error is only about 1.4, yet individual errors range from about -23.6 to +24.0. Positive and negative errors cancel in a plain average, so a line that is badly wrong in both directions can look perfect. What is needed is a measure that does not let errors cancel.

The usual fix is to square each error first. Squares are never negative, and large errors count much more than small ones. Then take the mean and undo the squaring with a square root. The result is the root mean squared error (RMSE): the square root of the mean of the squared errors.

def rmse(table, a, b, x='ad_spend', y='sales'):
    "Root mean squared error of the line  a + b * x  for the column y."
    errors = table[y] - (a + b * table[x])
    return np.sqrt(np.mean(errors ** 2))

print('RMSE of the manager\'s line:', round(rmse(stores, 50, 5), 2))
RMSE of the manager's line: 11.61

The RMSE is about 11.6. Because the calculation squares and then takes a square root, it is in the same units as the target: on these 40 stores, the manager’s line misses actual weekly sales by about $11,600 in the root-mean-square sense, a rough measure of a typical error. A smaller RMSE means a line that fits these stores better, and an RMSE of 0 would mean every prediction was exactly right.

### Exercise: Prediction Error
# A bakery predicts daily sales (in $100s) with the line: sales = 10 + 2 * staff.
#   1. Compute the error for each day (observed minus predicted).
#   2. Compute the average error and the RMSE.
#   3. Print both, rounded to 2 decimals. Why is the average error misleading?
# Print exactly:
# Average error: 0.0
# RMSE: 3.16
import numpy as np

staff = np.array([2, 3, 4, 5, 6])
sales = np.array([17, 13, 22, 16, 22])
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np

staff = np.array([2, 3, 4, 5, 6])
sales = np.array([17, 13, 22, 16, 22])

errors = sales - (10 + 2 * staff)
print('Average error:', round(np.mean(errors), 2))
print('RMSE:', round(np.sqrt(np.mean(errors ** 2)), 2))
# The errors are 3, -3, 4, -4, 0: positives and negatives cancel in the average,
# but squaring them first shows the typical miss is about 3 (in $100s).
Average error: 0.0
RMSE: 3.16

12.2.6.2. Comparing Lines#

The RMSE lets you rank any set of lines. Besides the manager’s rule, try three others: a flatter line (60 + 3 x ad spend), a line with a similar slope but a much lower base (40 + 4 x ad spend), and a line that ignores ad spend and always predicts average sales.

mean_sales = stores['sales'].mean()
candidates = {
    "Manager's rule: 50 + 5x": (50, 5),
    'Flatter line: 60 + 3x': (60, 3),
    'Low base: 40 + 4x': (40, 4),
    'Always the mean': (mean_sales, 0),
}

for name, (a, b) in candidates.items():
    print(f'{name:26s} RMSE = {rmse(stores, a, b):6.2f}')
Manager's rule: 50 + 5x    RMSE =  11.61
Flatter line: 60 + 3x      RMSE =  11.58
Low base: 40 + 4x          RMSE =  20.16
Always the mean            RMSE =  15.33

The manager’s rule (11.61) and the flatter line (11.58) are nearly tied, and the flatter line is a hair better. The low-base line is much worse (20.16) because it under-predicts for almost every store. The “always the mean” line, which uses no information about ads, has an RMSE of 15.33, so both of the first two lines gain a good deal from using ad spend. The picture shows why.

fig, ax = plt.subplots(figsize=(7, 4))
ax.scatter(stores['ad_spend'], stores['sales'], s=22, color='gray', label='Stores')
xs = np.array([1, 10])
colors = ['tab:red', 'tab:blue', 'tab:green', 'tab:orange']
for (name, (a, b)), color in zip(candidates.items(), colors):
    ax.plot(xs, a + b * xs, color=color, lw=2.5, label=name)
ax.set_xlabel('Weekly ad spend ($1,000s)')
ax.set_ylabel('Weekly sales ($1,000s)')
ax.set_title('Four candidate lines on the store data')
ax.legend(fontsize=9)
plt.show()
../../_images/a799669782f10d5ab79f78e0025fad1473284227b4dee6864e6b6216ec398a59.png

Two quite different lines score almost the same, so it is hard to say which is best by eye. Can anyone do better? Trying lines by hand could go on forever. Instead, ask the computer to search for the best line.

12.2.6.3. Finding the Best Line Numerically#

An RMSE belongs to a pair of numbers, an intercept and a slope. So you can write a function that takes the pair and returns the RMSE, and ask a routine to find the pair that makes it as small as possible. The function scipy.optimize.minimize does this: you give it a function and a starting guess, and it tries nearby values, moving downhill until the function stops getting smaller.

def rmse_of_line(params):
    "RMSE for a pair [intercept, slope] on the store data."
    return rmse(stores, params[0], params[1])

start = [50, 5]                      # the manager's rule is a reasonable first guess
best = minimize(rmse_of_line, start)

print('Intercept found:', round(best.x[0], 3))
print('Slope found:    ', round(best.x[1], 3))
print('Smallest RMSE:  ', round(best.fun, 3))
print('Search succeeded:', best.success)
Intercept found: 57.535
Slope found:     3.869
Smallest RMSE:   11.106
Search succeeded: True

The search starts at the manager’s line and ends at an intercept of about 57.5 and a slope of about 3.87. Compare these with the formulas from The Line in Original Units.

print('Formula intercept:', round(intercept(stores, 'ad_spend', 'sales'), 3))
print('Formula slope:    ', round(slope(stores, 'ad_spend', 'sales'), 3))
print('Formula RMSE:     ', round(rmse(stores, intercept(stores, 'ad_spend', 'sales'),
                                       slope(stores, 'ad_spend', 'sales')), 3))
Formula intercept: 57.535
Formula slope:     3.869
Formula RMSE:      11.106

The numbers agree to the 3 decimals shown; any differences further out come from the search stopping when it is close enough. The regression line from the formulas is the line with the smallest RMSE. This is why it is called the least squares line: among all straight lines, it makes the mean of the squared errors, and so the RMSE, as small as possible.

Its RMSE of 11.11 is better than the manager’s 11.61 and the flatter line’s 11.58. In business terms, on these 40 stores the best line misses weekly sales by about $11,100 in the root-mean-square sense. How well it would predict new stores is a separate question. No other straight line, whatever the slope or base, does better on these 40 stores.

The search reports best.success as True. That means only that the search stopped, not that it found the best line: a search started far enough away can stop early and still report success. When a formula exists, as it does for the least squares line, compare the search’s answer with it, as the previous cell does.

Is there one best line, or could a search find different answers? For a straight line, the RMSE as a function of the intercept and slope is shaped like a single bowl with one lowest point (as long as the stores do not all have the same ad spend). So there is exactly one best line. A search that moves downhill should end there from any reasonable start, and the next cell shows a very different start ending at the same line. That agreement, together with the formula check above, is the evidence that the search found the best line.

other_start = minimize(rmse_of_line, [0, 0])
print('From [0, 0]: intercept', round(other_start.x[0], 3), 'slope', round(other_start.x[1], 3))
From [0, 0]: intercept 57.535 slope 3.869

For a straight line, the formulas give the best line directly, so in practice it is computed with slope and intercept rather than a search. The search matters because the same idea, minimizing the error, still works for models that have no simple formula.

### Exercise: Search for the Best Line
# A bakery records the number of staff on duty and daily sales (in $100s).
#   1. Write a function bakery_rmse(params) that returns the RMSE of the line
#      params[0] + params[1] * staff on sales.
#   2. Use minimize with the starting guess [10, 2] (the bakery's own rule) to find
#      the best intercept and slope.
#   3. Print the intercept, slope, and RMSE, rounded to 2 decimals.
# Print exactly:
# Intercept: 12.8
# Slope: 1.3
# RMSE: 3.0
import numpy as np
from scipy.optimize import minimize

staff = np.array([2, 3, 4, 5, 6])
sales = np.array([17, 13, 22, 16, 22])
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np
from scipy.optimize import minimize

staff = np.array([2, 3, 4, 5, 6])
sales = np.array([17, 13, 22, 16, 22])

def bakery_rmse(params):
    predicted = params[0] + params[1] * staff
    return np.sqrt(np.mean((sales - predicted) ** 2))

result = minimize(bakery_rmse, [10, 2])
print('Intercept:', round(result.x[0], 2))
print('Slope:', round(result.x[1], 2))
print('RMSE:', round(result.fun, 2))
# The best line, 12.8 + 1.3 * staff, has an RMSE of 3.0, a little below the
# bakery rule's 3.16 from the Prediction Error exercise.
Intercept: 12.8
Slope: 1.3
RMSE: 3.0

12.2.7. Section Practice#

Apply the slope and intercept formulas, and then the RMSE, to a coffee chain’s data. Check your answers against the printed output.

### Exercise: Practice Regression Line
# Using the coffee chain's data:
#   1. Compute the slope (r * SD of sales / SD of temperature) and the intercept
#      (mean of sales - slope * mean of temperature).
#   2. Predict iced-drink sales on an 80-degree day.
#   3. Print the slope, intercept, and prediction, rounded to 2 decimals.
# Print exactly:
# Slope: 3.95
# Intercept: -113.22
# Predicted sales at 80 F: 202.62
import numpy as np

temperature = np.array([58, 62, 66, 70, 75, 79, 83, 88])
iced_sales = np.array([120, 135, 150, 148, 180, 205, 210, 240])
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
import numpy as np

temperature = np.array([58, 62, 66, 70, 75, 79, 83, 88])
iced_sales = np.array([120, 135, 150, 148, 180, 205, 210, 240])

def standard_units(x):
    return (x - np.mean(x)) / np.std(x)

r = np.mean(standard_units(temperature) * standard_units(iced_sales))
iced_slope = r * np.std(iced_sales) / np.std(temperature)
iced_intercept = np.mean(iced_sales) - iced_slope * np.mean(temperature)

print('Slope:', round(iced_slope, 2))
print('Intercept:', round(iced_intercept, 2))
print('Predicted sales at 80 F:', round(iced_slope * 80 + iced_intercept, 2))
Slope: 3.95
Intercept: -113.22
Predicted sales at 80 F: 202.62
### Exercise: Practice Least Squares
# A manager proposes the line: sales = 4 * temperature - 120.
#   1. Compute the RMSE of the manager's line on the coffee chain's data.
#   2. Compute the RMSE of the regression line (slope and intercept as in the previous exercise).
#   3. Print both, rounded to 2 decimals, and print which line has the smaller RMSE.
# Print exactly:
# Manager's line RMSE: 7.43
# Regression line RMSE: 6.78
# Smaller RMSE: regression line
import numpy as np

temperature = np.array([58, 62, 66, 70, 75, 79, 83, 88])
iced_sales = np.array([120, 135, 150, 148, 180, 205, 210, 240])
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
import numpy as np

temperature = np.array([58, 62, 66, 70, 75, 79, 83, 88])
iced_sales = np.array([120, 135, 150, 148, 180, 205, 210, 240])

def cafe_rmse(predicted):
    return np.sqrt(np.mean((iced_sales - predicted) ** 2))

r = np.corrcoef(temperature, iced_sales)[0, 1]
cafe_slope = r * np.std(iced_sales) / np.std(temperature)
cafe_intercept = np.mean(iced_sales) - cafe_slope * np.mean(temperature)

manager_rmse = cafe_rmse(4 * temperature - 120)
regression_rmse = cafe_rmse(cafe_slope * temperature + cafe_intercept)

print("Manager's line RMSE:", round(manager_rmse, 2))
print('Regression line RMSE:', round(regression_rmse, 2))
print('Smaller RMSE:', 'regression line' if regression_rmse < manager_rmse else "manager's line")
# The regression line is the least squares line, so no straight line has a smaller RMSE.
Manager's line RMSE: 7.43
Regression line RMSE: 6.78
Smaller RMSE: regression line