Linear Regression: Understanding the Line of Best Fit

These notes explain how to calculate a simple linear regression equation from a dataset, using Python and the mathematics behind the calculations.

1. What Is Linear Regression?

Linear regression is a statistical method used to describe the relationship between two numerical variables using a straight line.

We begin with a collection of observed data points. We want to find a straight line that represents the overall relationship between those points as closely as possible.

For example, we might investigate whether temperature is related to the number of fatal crashes.

WHY?

Rather than simply looking at individual observations, regression allows us to summarize the overall relationship and use it to estimate or predict values.

2. Understand the Variables

Our dataset contains three columns:

VariableDescriptionRole
MonthMonth of the yearTime identifier
Avg.TempAverage temperatureIndependent variable (X)
TotalFatalCrashesTotal fatal crashesDependent variable (Y)

For our regression analysis:

WHY?

We need to identify which variable we are using to explain or predict the other. Here, temperature is our predictor (X), and fatal crashes are our response (Y).

3. The Regression Equation

Our goal is to find the equation of a straight line.

ŷ = bX + a
SymbolMeaning
ŷPredicted value of Y
XIndependent variable
bSlope of the regression line
aY-intercept

This is the same mathematical structure as the familiar algebraic equation:

y = mx + c

The letters are different, but the concepts are the same. In our regression notation, b is the slope and a is the intercept.

4. Calculate the Averages

Before calculating the slope, we need the average of X and Y.

Average X (temperature)

X̄ = Sum of X values / Number of observations

Our temperature values add up to 531.

Therefore:

X̄ = 531 / 12 = 44.25

Average Y (fatal crashes)

Our fatal crash values add up to 4,061.

Ȳ = 4061 / 12 = 338.4167
WHY DO WE CALCULATE THE AVERAGES?

The averages give us a reference point. We will measure how far each observation is above or below its respective average.

An important property of ordinary least-squares regression with an intercept is that the fitted line passes through the point (X̄, Ȳ).

Python

avg_temp = sum(Avg_Temps) / len(Avg_Temps)

total_fatal_crashes = sum(TotalFatalCrashes)

average_number_of_fatal_crashes = (
    total_fatal_crashes / len(TotalFatalCrashes)
)

5. Calculate the Deviations

A deviation is the difference between an observation and its average.

X deviation = X - X̄
Y deviation = Y - Ȳ

Let's examine the first observation.

CalculationResult
17 - 44.25 (X deviation)-27.25
297 - 338.4167 (Y deviation)-41.4167

Positive and negative deviations tell us where an observation sits relative to its average:

WHY?

We don't want to compare raw values alone. We want to understand how X and Y move together relative to their respective averages.

Python

temp_dev = []

for temp in Avg_Temps:
    temp_dev.append(temp - avg_temp)

crash_dev = []

for crashes in TotalFatalCrashes:
    crash_dev.append(
        crashes - average_number_of_fatal_crashes
    )

6. Calculate the Slope Numerator

Now we multiply each X deviation by its corresponding Y deviation.

Σ[(X - X̄)(Y - Ȳ)]

Notice that we multiply matching observations. The first temperature deviation is multiplied by the first crash deviation, the second by the second, and so on.

For our first observation:

(-27.25) × (-41.4167)

The result is positive because a negative multiplied by a negative produces a positive.

We repeat this process for all 12 observations and add the products together.

Our numerator:

9,043.75

WHY?

This calculation measures how X and Y vary together. When deviations tend to have matching signs, the products tend to be positive. When signs tend to differ, products tend to be negative.

Adding all the products gives us a measure of their overall joint variation.

Python

slope_numerator = 0

for values in zip(temp_dev, crash_dev):
    slope_numerator += values[0] * values[1]

7. Calculate the Slope Denominator

Next, we square every X deviation and add the squared values.

Σ(X - X̄)²

For our first observation:

(-27.25)² = 742.5625

We repeat this for all 12 temperature deviations.

Our denominator:

4,218.25

WHY?

The denominator measures how much the X values vary around their average.

Squaring the deviations prevents positive and negative differences from cancelling each other out.

Python

slope_denominator = 0

for temp in temp_dev:
    slope_denominator += temp * temp

8. Calculate the Slope (b)

Now we have everything needed to calculate the slope.

b = Numerator / Denominator

Substitute our results:

b = 9043.75 / 4218.25
Our slope:

b ≈ 2.14396

WHY?

The slope tells us how much the predicted value of Y changes when X increases by one unit.

Our positive slope means the model predicts approximately 2.14 additional fatal crashes for each one-unit increase in average temperature.

Python

slope = slope_numerator / slope_denominator

print(f"Slope: {slope}")

9. Calculate the Y-Intercept (a)

We now know the slope, but we still need the intercept.

Remember our regression equation:

ŷ = bX + a

We also know that the regression line passes through the point formed by the two averages:

(X̄, Ȳ) = (44.25, 338.4167)

Substitute the averages into the equation:

338.4167 = 2.14396(44.25) + a

Rearrange to isolate a:

a = Ȳ - bX̄

Substitute the numbers:

a = 338.4167 - (2.14396 × 44.25)
Our intercept:

a ≈ 243.5465

WHY?

The intercept is the predicted value of Y when X equals zero. We use the averages and the slope to position the line correctly.

Python

a = average_number_of_fatal_crashes - slope * avg_temp

print(f"Intercept: {a}")

10. Our Final Regression Equation

We now have both components:

The completed equation

ŷ = 2.14396X + 243.5465

We have successfully constructed a linear regression equation from our original dataset.

What does this equation tell us?

If the average temperature is 50, the predicted number of fatal crashes is:

ŷ = 2.14396(50) + 243.5465
ŷ ≈ 350.74

The model therefore predicts approximately 351 fatal crashes.

11. What Makes This the Line of Best Fit?

We did not simply connect two data points. We used all 12 observations to calculate the regression line.

The ordinary least-squares method chooses the slope and intercept that minimize the sum of squared vertical residuals.

A residual is the difference between an actual observed Y value and the value predicted by the regression equation.

Residual = Actual Y - Predicted Y
WHY SQUARE THE RESIDUALS?

Squaring prevents positive and negative residuals from cancelling one another out. It also penalizes larger errors more heavily.

The regression line does not have to pass through every observed data point. Instead, it minimizes the total squared prediction error.

12. Important Statistical Caution

Our equation describes an association in this dataset. It does not demonstrate that temperature causes fatal crashes.

Other factors could influence fatal crashes, including traffic volume, road conditions, holidays, weather, and seasonal behavior.

Also, our dataset contains only 12 monthly observations. More data and additional analysis would be needed before drawing strong conclusions.

13. The Entire Process at a Glance

  1. Identify X and Y.
  2. Calculate the average of X.
  3. Calculate the average of Y.
  4. Calculate each X deviation.
  5. Calculate each Y deviation.
  6. Multiply corresponding deviations and add the products.
  7. Square the X deviations and add them.
  8. Divide the numerator by the denominator to obtain the slope.
  9. Use the averages and slope to calculate the intercept.
  10. Put the slope and intercept into the regression equation.
Remember:

The entire process produces two numbers: the slope and the intercept. Those two numbers define our regression line.