Linear Models and Trend Lines
A trend line is the straight line that fits a cloud of data points best. "Best" usually means least squares: the line that makes the sum of squared vertical errors as small as possible. There are closed-form formulas for and , so you can compute the line with a few sums, and every dashboard library that draws a "trend" does exactly this.
The model
A linear model predicts from with two numbers (equations of lines):
For data points the residual of point is , how far the point is above (+) or below (−) the line. Least squares picks and to minimise
Squaring makes all errors count as positive and punishes big misses more than small ones.
The formulas
Setting the derivatives of with respect to and to zero (a short calculus argument, or see least squares for the matrix view) gives two linear equations, the normal equations. Solving them:
An equivalent form that uses only running sums (handy when data streams in):
Two facts fall out: the line always passes through the mean point , and the residuals add up to zero.
How good is the fit? The coefficient of determination compares the leftover error with the total spread of :
By hand vs NumPy
Daily active users of a small app over 10 days:
import numpy as np
days = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
users = [120, 132, 129, 141, 150, 148, 161, 166, 170, 182]
n = len(days)
xbar, ybar = sum(days) / n, sum(users) / n
sxy = sum((x - xbar) * (y - ybar) for x, y in zip(days, users))
sxx = sum((x - xbar) ** 2 for x in days)
m = sxy / sxx
b = ybar - m * xbar
print(f"formulas : m = {m:.4f}, b = {b:.4f}")
m2, b2 = np.polyfit(days, users, 1) # degree 1: [slope, intercept]
print(f"polyfit : m = {float(m2):.4f}, b = {float(b2):.4f}")
pred = [m * x + b for x in days]
ss_res = sum((y - p) ** 2 for y, p in zip(users, pred))
ss_tot = sum((y - ybar) ** 2 for y in users)
print(f"R^2 = {1 - ss_res / ss_tot:.4f}")
print(f"sum of residuals = {sum(y - p for y, p in zip(users, pred)):.2e}")formulas : m = 6.4667, b = 114.3333
polyfit : m = 6.4667, b = 114.3333
R^2 = 0.9716
sum of residuals = -1.14e-13
The app gains about 6.5 users per day. says the line explains about 97% of the day-to-day variation. The tiny sum of residuals is zero up to rounding.
Note:
np.polyfit(x, y, 1)returns coefficients from the highest power down, so the slope comes first. NumPy 2 prints its scalars asnp.float64(…)inside containers; wrapping them infloat()keeps output clean.
A trend line in a dashboard
Dashboards draw the data, the fitted line and often a dashed forecast that extends the line a few periods ahead. Extending is easy (just plug in a larger ) but it assumes the trend continues; treat it as a guess, not a promise.
import numpy as np
import matplotlib.pyplot as plt
days = np.arange(1, 11)
users = np.array([120, 132, 129, 141, 150, 148, 161, 166, 170, 182])
m, b = np.polyfit(days, users, 1)
future = np.arange(10, 15)
print("forecast:", {int(d): round(float(m * d + b)) for d in future[1:]})
fig, ax = plt.subplots(figsize=(6, 4))
ax.bar(days, users, color="#9ecae1", label="daily active users")
ax.plot(days, m * days + b, color="#08519c", label=f"trend y = {m:.2f}x + {b:.1f}")
ax.plot(future, m * future + b, "--", color="#08519c", label="forecast")
ax.set_xlabel("day"); ax.set_ylabel("users"); ax.set_ylim(100, 220)
ax.legend(loc="upper left")forecast: {11: 185, 12: 192, 13: 198, 14: 205}
When the model lies
- Outliers: one huge value pulls the whole line toward it, because errors are squared.
- Curved data: a line through exponential growth fits badly; fit a line to instead, or a polynomial (
np.polyfit(x, y, 2)). - Extrapolation: the further from the data, the less the line means.
- Correlation is not cause: a good fit says the variables move together, not why (correlation).
In software
- Dashboards and monitoring: trend lines, "disk full in N days" alerts (solve for ).
- Machine learning: linear regression is the simplest model, and the starting point for neural networks (linear regression in ML); gradient descent finds the same and iteratively.
- Performance work: fit time against input size to estimate the cost per item and the fixed overhead (the intercept).
Exercises
Exercise 1: Four points by hand
Find the least-squares line through , , , .
Answer
Solution
import numpy as np
print([round(float(c), 6) for c in np.polyfit([1, 2, 3, 4], [2, 3, 5, 6], 1)])[1.4, 0.5]
Exercise 2: When is the disk full?
A server's disk usage follows the trend , where is days from today. The disk holds 500 GB. On which day does the trend cross the limit?
Answer
, so during day 80.
Solution
Day 79 still ends below the limit (); the disk fills during day 80.
Exercise 3: The outlier effect (code)
Fit a line to , , then change the last to 40 and fit again. Print both slopes and intercepts.
Answer
Without the outlier: , . With it: , . One bad point nearly triples the slope.
Solution
The first data lie exactly on . Raising the last by 27 raises by , and by ; with the slope grows by .
import numpy as np
x = [1, 2, 3, 4, 5, 6]
for y in ([3, 5, 7, 9, 11, 13], [3, 5, 7, 9, 11, 40]):
m, b = np.polyfit(x, y, 1)
print(f"m = {float(m):.3f}, b = {float(b):.3f}")m = 2.000, b = 1.000
m = 5.857, b = -8.000
Test yourself
Which point does every least-squares line pass through?
- (0, 0)
- The first data point
- The point with the largest
What does np.polyfit(x, y, 1) return?
- [slope, intercept]
- [intercept, slope]
- only
- The residuals
A fit has . What does that mean?
- The slope is 0.2
- The line explains only about 20% of the variation in
- 20% of the points lie on the line
- The data has no errors