Regression

Chapter 12 · Think Data Science & Management

Correlation

12.1 · Think Data Science & Management

Today's goals

  • Read association from a scatter plot: direction and straightness
  • Compute r as the mean of products in standard units
  • Use the properties of r: no units, symmetric, between -1 and 1
  • Recognize when r misleads: causation, curves, outliers, aggregated data

The question: do ads go with sales?

stores = pd.read_csv(path_data + 'store_ad_sales.csv')
stores.head(3)
  store region  ad_spend  staff  store_age  sales
0   S01  North       6.0     12          4   77.3
1   S02  South       7.2     13         11   85.3
2   S03  North       2.0      9          9   50.2
  • 40 stores, simulated teaching data
  • ad_spend and sales are weekly, in $1,000s

A scatter plot: one dot per store

Scatter plot of weekly sales against weekly ad spend for 40 stores; the dots drift upward from lower left to upper right

  • Dots drift up to the right: a positive association
  • They cluster around a straight band: the association is linear

What r looks like

Five scatter plots of 100 simulated points each with r near -0.9, -0.5, 0, 0.5, and 0.9; the dots hug a line more tightly as r moves away from 0

  • Sign of r: the direction
  • Size of r (distance from 0): how tightly the dots follow a line

A plot slopes gently down, with dots widely scattered around a line. Which r fits best?

  1. r = 0.9
  2. r = -0.9
  3. r = -0.4
  4. r = 0

Standard units

How many SDs a value is above or below its mean:

def standard_units(values):
    return (values - np.mean(values)) / np.std(values)
  • np.std divides by n, as everywhere in this book
  • A constant column has SD 0: no standard units, so no r

r is the mean of the products

steps = pd.DataFrame({
    'ad_su': standard_units(stores['ad_spend']),
    'sales_su': standard_units(stores['sales']),
})
steps['product'] = steps['ad_su'] * steps['sales_su']
print(round(np.mean(steps['product']), 3))
0.689
  • np.corrcoef(x, y)[0, 1] gives the same 0.689

Why products?

Positive products

  • Above average on both: + × + = +
  • Below average on both: - × - = +

Negative products

  • High on one, low on the other: + × - = -
  • Stores far from average on both count the most

The sign of r depends on which kind of product outweighs the other, not on a head count.

Properties of r

  • Between -1 and 1; exactly ±1 only when all dots lie on a line
  • No units: 0.69 is not "0.69 thousand dollars"
  • Unchanged by a change of units
  • Symmetric: r(ad, sales) = r(sales, ad)
in_dollars = stores[['ad_spend', 'sales']] * 1000
print(round(correlation(stores, 'ad_spend', 'sales'), 3),
      round(correlation(in_dollars, 'ad_spend', 'sales'), 3))
0.689 0.689

A finance team reports sales in dollars instead of $1,000s and swaps x and y. The new r is...

  1. 1,000 times larger
  2. The same, 0.689
  3. 0.689 divided by 1,000
  4. -0.689, because x and y were swapped

Correlation is not causation

Simulated monthly sales at a seaside shop:

r (ice cream, sunscreen): 0.933
r (temperature, ice cream): 0.978
r (temperature, sunscreen): 0.97
r (ice cream, sunscreen), months 68 to 78 F: 0.058
  • A spurious correlation: neither product drives the other
  • The confounder is temperature; hold it fixed and r nearly vanishes
  • Stores that advertise more may also be bigger or better located

r measures only straight-line association

Left: units sold fall along a curve as price rises, r = -0.95. Right: weekly profit peaks at a middle price, r = -0.02

  • A strong curve can still give a high |r|: r hides the shape
  • A strong curve can give r near 0: no straight-line association, not no relationship

One store can move r a lot

Left: the 40 stores with r = 0.69. Right: the same stores plus one new store with high ad spend and low sales, r = 0.54

  • An invented new store: $9,500 a week on ads, only $40,000 in sales
  • r drops from 0.69 to 0.54

Anscombe's quartet: same r, different pictures

Four scatter plots with r = 0.816 or 0.817: a straight-line cloud, a smooth curve, a line with one outlier, and a vertical stack with one far point

  • Same means, SDs, r, and best line (about y = 3 + 0.5x)
  • I: a line · II: a curve · III: one outlier · IV: one point makes r

Aggregated data: averages exaggerate

Left: 300 simulated stores colored by region, widely scattered, r = 0.60. Right: 10 region averages lying almost on a line, r = 0.98

  • Averaging smooths away individual noise: an ecological correlation
  • Within a region, r averages only about 0.20

A report shows r = 0.98 between regions' average ad spend and average sales. For one store, you can conclude...

  1. Its sales will rise almost exactly in line with its ad spend
  2. Little: individual stores can be far more scattered
  3. Ads cause 98% of its sales
  4. r for individual stores is also about 0.98

Your turn: which store trait tracks sales?

The stores table also has staff and store_age.

  1. Compute r between staff and sales
  2. Compute r between store_age and sales
  3. Print both, rounded to 3 decimals, and say which trait tracks sales more closely

Recap

  • Scatter plot first: direction and straightness
  • r is the mean of products in standard units, between -1 and 1
  • r has no units and is symmetric
  • r misleads with confounders, curves, outliers, and group averages

Regression Line

12.2 · Think Data Science & Management

Today's goals

  • Predict a target from a feature with the regression line
  • Explain the regression effect and why it misleads managers
  • Find and interpret the slope and intercept in original units
  • Compute fitted values, residuals, and RMSE
  • Explain why the regression line is the least squares line

From association to prediction

  • Feature (x): the variable used to predict, here ad spend
  • Target (y): the variable predicted, here sales
  • Stores with the same ad spend still differ, so predictions will miss
  • Goal: a sensible average sales figure for each ad budget
Correlation r: 0.6894

A straight line needs only two numbers and is easy to explain to a manager.

The line in standard units has slope r

Scatter of the stores in standard units with a gray diagonal y = x and a flatter red regression line of slope 0.69 through (0, 0)

Predict sales for an $8,000 ad budget

new_ad_su = (8 - ad_mean) / ad_sd            # 1. to standard units
pred_su = ad_sales_r * new_ad_su              # 2. multiply by r
pred_sales = pred_su * sales_sd + sales_mean  # 3. back to $1,000s
Ad spend in standard units:      0.94
Predicted sales, standard units: 0.64
Predicted sales ($1,000s):       88.5
  • About $88,500 a week

r = 0.69. A store's ad spend is 2 SDs above average. Its predicted sales are...

  1. 2 SDs above average
  2. 1.38 SDs above average
  3. 0.69 SDs above average
  4. 2.9 SDs above average

The regression effect

Simulated Q1 and Q2 sales for 200 reps (skill plus luck), r = 0.52:

cutoff = np.percentile(reps['q1_sales'], 90)
top = reps[reps['q1_sales'] >= cutoff]
print(len(top), round(np.mean(top['q1_sales']), 1),
      round(np.mean(top['q2_sales']), 1))
20 137.9 120.5
  • The top 10% fall back toward the mean of about 100; 16 of 20 sold less in Q2

Stars fall below the diagonal

Scatter of Q2 against Q1 sales for 200 reps; the top in Q1 are red and sit mostly below the dashed diagonal; the blue regression line is flatter than the diagonal

  • Skill carries over; luck is a fresh draw each quarter
  • The weaker the link (smaller r), the further extremes fall back

A manager gives the top 10% a bonus; their next-quarter sales fall. What can the manager conclude?

  1. Bonuses backfire
  2. The top reps got complacent
  3. Nothing yet: the regression effect alone predicts a fall
  4. The bonus caused a 13% drop

The line in original units

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])
Slope:     3.87
Intercept: 57.54

Reading the slope and intercept

  • Slope 3.87: about $3,870 more weekly sales per extra $1,000 of weekly ad spend, between stores along the line
  • Not a promise that raising one store's budget raises its sales by that much
  • Intercept 57.54: about $57,540 at zero ad spend, but no store spends less than $1,000, so it sets the line's height, not a forecast

Fitted values and residuals

stores['fitted'] = store_slope * stores['ad_spend'] + store_intercept
stores['residual'] = stores['sales'] - stores['fitted']
  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

Residuals are the vertical misses

The 40 stores with the red regression line and vertical black segments from a few points to the line

  • The residuals average 0: misses above and below balance
  • The largest miss is about $25,400 (store S10)

Do not extrapolate

  • The line is built from stores spending $1,000 to $10,000 a week
  • Inside that range (interpolation) the prediction rests on evidence
  • At $30,000 the line says $173,600, but sales may level off long before

The line will produce a number for any input. It cannot warn you the number is unreliable.

Score a line by its RMSE

Manager's rule: predicted sales = 50 + 5 × ad spend

def rmse(table, a, b, x='ad_spend', y='sales'):
    errors = table[y] - (a + b * table[x])
    return np.sqrt(np.mean(errors ** 2))
Average error: 1.38   (errors run from -23.6 to 24.0)
RMSE of the manager's line: 11.61
  • Plain averages let errors cancel; squaring stops that
  • RMSE is in the target's units: a typical miss of about $11,600

Comparing candidate lines

Four lines over the store scatter: manager's rule 50 + 5x, flatter 60 + 3x, low base 40 + 4x, and a flat line at the mean

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

Let the computer find the best line

def rmse_of_line(params):
    return rmse(stores, params[0], params[1])

best = minimize(rmse_of_line, [50, 5])
Intercept found: 57.535
Slope found:     3.869
Smallest RMSE:   11.106
  • Same as the formulas: the regression line is the least squares line

The regression line is called the least squares line because...

  1. It passes through the most data points
  2. Among all straight lines, it has the smallest mean squared error
  3. Its residuals are all as small as possible
  4. Its average error is 0

Your turn: slope and intercept for sales reps

Predict Q2 sales from Q1 sales (sales_reps.csv):

  1. Compute r for q1_sales and q2_sales
  2. Compute the slope and the intercept from r, the SDs, and the means
  3. Predict Q2 sales for a rep who sold 90 in Q1; print all three, rounded to 2 decimals

Recap

  • In standard units, the regression line has slope r through (0, 0)
  • The regression effect: extremes move back toward the mean
  • Slope = r × SD(y) / SD(x); the line passes through the point of averages
  • Residual = observed - fitted; do not extrapolate
  • The regression line has the smallest RMSE: the least squares line

Diagnostics and Inference

12.3 · Think Data Science & Management

Today's goals

  • Read a residual plot: no pattern, centered on 0, even spread
  • Spot nonlinearity, uneven spread, and influential points
  • Bootstrap the slope and build a 95% confidence interval
  • Test whether the true slope could be 0
  • State the limits of the line and the interval

A healthy residual plot

Left: the stores with the fitted line. Right: residuals against ad spend, a shapeless cloud around a horizontal line at 0

  1. No pattern: no curve, tilt, or clump
  2. Centered on 0 in every range of ad spend
  3. Even spread from left to right

Why the center alone tells you nothing

Average residual:  0.0
Smallest residual: -25.37
Largest residual:  24.04
Residual SD:       11.11
  • Every least squares line has residuals averaging 0, however poor
  • So judge the shape of the plot, not its center
  • Residual SD 11.11: the typical miss, about $11,100

Nonlinearity: a U shape

Left: units sold against price bend away from a straight line. Right: residuals are positive at low prices, negative in the middle, positive at high prices

  • r = -0.95, yet the line is wrong in a predictable direction

What the curve costs, and three fixes

Average residual, prices under $6:    47.3 units
Average residual, prices $9 to $12:  -27.7 units
Average residual, prices over $14:    18.9 units
  1. Transform: fit log(units) on price; the U disappears
  2. Fit a curve
  3. Use the line only over a narrow range
  • On the log scale the slope is -0.184: about 17% fewer units per extra $1

Residuals are positive at both ends of the x range and negative in the middle. This means...

  1. The line fits well, since residuals average 0
  2. A curve would describe the data better than a line
  3. The spread is uneven
  4. There is one influential point

Uneven spread: a fan

Left: 5,000 New York taxi fares against distance with a fitted line. Right: residuals narrow at short distances and widening at long ones, with a horizontal band near $52

  • Heteroscedasticity: residuals spread out as distance grows
  • Real data: 5,000 NYC yellow-taxi trips, March 4-10, 2019 (NYC TLC)

Measure the spread in distance bands

Under 2 miles:  2971 trips, residual SD: $ 2.77
2 to 10 miles:  1723 trips, residual SD: $ 3.45
Over 10 miles:   306 trips, residual SD: $ 7.31
All trips:      5000 trips, residual SD: $ 3.52
  • Long trips: 2.6 times the spread of short ones
  • The line still gives a fair average fare up to about 20 miles
  • A single long-trip prediction can miss by many dollars: plan a wider margin

Influential points

The 40 stores with a gold line of slope 3.87, plus one red new store at high ad spend and low sales that pulls a red line down to slope 3.19

  • One store out of 41 lowers the slope by almost a fifth
  • Refit without it, report both, and ask whether it is typical

Anscombe's quartet, revisited

Top row: the four Anscombe data sets with the same fitted line. Bottom row: their residual plots, a cloud, a curve, one huge residual, and one point far to the right

  • Same line, y = 3 + 0.5x, for all four; the residual plots tell them apart

In which data set does a single point determine the slope by itself?

  1. Data set I
  2. Data set II
  3. Data set III
  4. Data set IV

The slope is an estimate

  • The 40 stores are a sample; the true slope describes all stores like them
  • Split the stores in half and the slope changes:
Slope from all 40 stores:      3.87
Slope from the first 20 stores: 5.04
Slope from the last 20 stores:  3.39
  • That is sampling variability: is the true slope 3, 4, or 5?

Bootstrap the slope: resample whole rows

def one_bootstrap_slope():
    resample = stores.sample(len(stores), replace=True)
    return slope(resample, 'ad_spend', 'sales')

np.random.seed(42)
bstrap_slopes = np.array([one_bootstrap_slope()
                          for i in range(5000)])
  • Each row keeps a store's ad spend and sales together
  • Resampling the columns separately would destroy the association

A 95% confidence interval for the slope

Histogram of 5,000 bootstrap slopes centered near 3.87, with a gold bar from 2.79 to 4.98 marking the middle

left, right = np.percentile(bstrap_slopes, [2.5, 97.5], method='nearest')
2.79 4.98

Association, not a business case

  • The interval describes an association: big ad spenders may differ in location or size
  • Break-even: at 30 cents of gross profit per sales dollar, ads pay only if $1 of ads causes more than $3.33 of sales
  • The interval reaches below 3.33, and it is not causal anyway

To decide, the manager needs an experiment that assigns ad budgets at random.

Testing whether the true slope is 0

  • Null: the true slope is 0 (no linear association)
  • Alternative: the true slope is not 0
  • 0 outside the 95% interval: reject at about the 5% cutoff
  • Ad spend: 0 is far outside 2.79 to 4.98, so reject

Histogram of 5,000 bootstrap slopes of sales on store age with a gold interval from -0.97 to 0.37 that contains the red line at 0

The store-age interval is -0.97 to 0.37. Which conclusion is right?

  1. Older stores sell less
  2. Store age has no effect on sales
  3. The data are consistent with no linear association, but cannot rule out a loss of $800 a week per year
  4. Reject the null hypothesis at the 5% cutoff

Cautions

  • Diagnostics first. A curve or an influential store distorts the interval. A fan is less of a problem for the slope, because each resample keeps the observed spread
  • How the data were collected. The bootstrap assumes independent rows that represent the population; no plot can check this
  • Range and sample size. The interval estimates one population slope; use the line only for ad spend of about $1,000 to $10,000. More repetitions do not fix a small sample

Your turn: is staffing associated with sales?

  1. Collect 1,000 bootstrap slopes of sales on staff, with ex_stores.sample(len(ex_stores), replace=True, random_state=i) for i = 0, ..., 999
  2. Compute the 95% interval with np.percentile(..., method='nearest')
  3. Print the interval, rounded to 2 decimals, and whether 0 is inside it

Recap

  • A healthy residual plot: no pattern, centered on 0, even spread
  • A U means a curve; a fan means uneven precision; check influential points
  • Bootstrap whole rows for a 95% confidence interval for the true slope
  • 0 outside the interval: evidence of a linear association, not of cause
  • Use the line only within the observed range