These notes explain how to calculate a simple linear regression equation from a dataset, using Python and the mathematics behind the calculations.
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.
Rather than simply looking at individual observations, regression allows us to summarize the overall relationship and use it to estimate or predict values.
Our dataset contains three columns:
| Variable | Description | Role |
|---|---|---|
| Month | Month of the year | Time identifier |
| Avg.Temp | Average temperature | Independent variable (X) |
| TotalFatalCrashes | Total fatal crashes | Dependent variable (Y) |
For our regression analysis:
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).
Our goal is to find the equation of a straight line.
| Symbol | Meaning |
|---|---|
| ŷ | Predicted value of Y |
| X | Independent variable |
| b | Slope of the regression line |
| a | Y-intercept |
This is the same mathematical structure as the familiar algebraic equation:
The letters are different, but the concepts are the same. In our regression notation, b is the slope and a is the intercept.
Before calculating the slope, we need the average of X and Y.
Our temperature values add up to 531.
Therefore:
Our fatal crash values add up to 4,061.
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̄, Ȳ).
avg_temp = sum(Avg_Temps) / len(Avg_Temps)
total_fatal_crashes = sum(TotalFatalCrashes)
average_number_of_fatal_crashes = (
total_fatal_crashes / len(TotalFatalCrashes)
)
A deviation is the difference between an observation and its average.
Let's examine the first observation.
| Calculation | Result |
|---|---|
| 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:
We don't want to compare raw values alone. We want to understand how X and Y move together relative to their respective averages.
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
)
Now we multiply each X deviation by its corresponding Y deviation.
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:
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.
9,043.75
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.
slope_numerator = 0
for values in zip(temp_dev, crash_dev):
slope_numerator += values[0] * values[1]
Next, we square every X deviation and add the squared values.
For our first observation:
We repeat this for all 12 temperature deviations.
4,218.25
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.
slope_denominator = 0
for temp in temp_dev:
slope_denominator += temp * temp
Now we have everything needed to calculate the slope.
Substitute our results:
b ≈ 2.14396
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.
slope = slope_numerator / slope_denominator
print(f"Slope: {slope}")
We now know the slope, but we still need the intercept.
Remember our regression equation:
We also know that the regression line passes through the point formed by the two averages:
Substitute the averages into the equation:
Rearrange to isolate a:
Substitute the numbers:
a ≈ 243.5465
The intercept is the predicted value of Y when X equals zero. We use the averages and the slope to position the line correctly.
a = average_number_of_fatal_crashes - slope * avg_temp
print(f"Intercept: {a}")
We now have both components:
We have successfully constructed a linear regression equation from our original dataset.
If the average temperature is 50, the predicted number of fatal crashes is:
The model therefore predicts approximately 351 fatal crashes.
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.
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.
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.
The entire process produces two numbers: the slope and the intercept. Those two numbers define our regression line.