TExcelTAD
Home › Algebra › Linear Models and Trend Lines

Linear Models and Trend Lines

A trend line is the straight line y=m⋅x+by = m \cdot x + b 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 mm and bb, 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 yy from xx with two numbers (equations of lines):

y^=m⋅x+bm=slope (change in y per unit of x),b=intercept (y^ at x=0)\hat{y} = m \cdot x + b \qquad m = \text{slope (change in } y \text{ per unit of } x\text{)},\quad b = \text{intercept (}\hat{y} \text{ at } x = 0\text{)}

For data points (x1,y1),…,(xn,yn)(x_1, y_1), \ldots, (x_n, y_n) the residual of point ii is ei=yi−y^ie_i = y_i - \hat{y}_i, how far the point is above (+) or below (−) the line. Least squares picks mm and bb to minimise

S(m,b)=∑(yi−m⋅xi−b)2S(m, b) = \sum (y_i - m \cdot x_i - b)^2

Squaring makes all errors count as positive and punishes big misses more than small ones.

The formulas

Setting the derivatives of SS with respect to mm and bb to zero (a short calculus argument, or see least squares for the matrix view) gives two linear equations, the normal equations. Solving them:

xˉ=∑xinyˉ=∑yinm=∑(xi−xˉ)(yi−yˉ)∑(xi−xˉ)2b=yˉ−m⋅xˉ\begin{aligned} \bar{x} &= \frac{\sum x_i}{n} \qquad \bar{y} = \frac{\sum y_i}{n} \\ m &= \frac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sum (x_i - \bar{x})^2} \\ b &= \bar{y} - m \cdot \bar{x} \end{aligned}

An equivalent form that uses only running sums (handy when data streams in):

m=n⋅∑xy−∑x⋅∑yn⋅∑x2−(∑x)2m = \frac{n \cdot \sum xy - \sum x \cdot \sum y}{n \cdot \sum x^2 - (\sum x)^2}

Two facts fall out: the line always passes through the mean point (xˉ,yˉ)(\bar{x}, \bar{y}), 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 yy:

R2=1−∑(yi−y^i)2∑(yi−yˉ)21=perfect line, 0=no better than the meanR^2 = 1 - \frac{\sum (y_i - \hat{y}_i)^2}{\sum (y_i - \bar{y})^2} \qquad 1 = \text{perfect line},\ 0 = \text{no better than the mean}

By hand vs NumPy

Daily active users of a small app over 10 days:

python · try it yourself
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. R2≈0.97R^2 \approx 0.97 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 as np.float64(…) inside containers; wrapping them in float() 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 xx) but it assumes the trend continues; treat it as a guess, not a promise.

python · try it yourself
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 log⁡(y)\log(y) 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 m⋅x+b=capacitym \cdot x + b = \text{capacity} for xx).
  • Machine learning: linear regression is the simplest model, and the starting point for neural networks (linear regression in ML); gradient descent finds the same mm and bb 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 (1,2)(1, 2), (2,3)(2, 3), (3,5)(3, 5), (4,6)(4, 6).

Answer

y^=1.4x+0.5\hat{y} = 1.4x + 0.5

Solution
xˉ=2.5,yˉ=4xi−xˉ:−1.5, −0.5, 0.5, 1.5yi−yˉ:−2, −1, 1, 2∑(x−xˉ)(y−yˉ)=3+0.5+0.5+3=7∑(x−xˉ)2=2.25+0.25+0.25+2.25=5m=75=1.4b=4−1.4⋅2.5=0.5\begin{aligned} &\bar{x} = 2.5,\quad \bar{y} = 4 \\ &x_i - \bar{x}\text{:}\quad -1.5,\ -0.5,\ 0.5,\ 1.5 \\ &y_i - \bar{y}\text{:}\quad -2,\ -1,\ 1,\ 2 \\ \textstyle\sum (x - \bar{x})(y - \bar{y}) &= 3 + 0.5 + 0.5 + 3 = 7 \\ \textstyle\sum (x - \bar{x})^2 &= 2.25 + 0.25 + 0.25 + 2.25 = 5 \\ m &= \frac{7}{5} = 1.4 \\ b &= 4 - 1.4 \cdot 2.5 = 0.5 \end{aligned}
python · try it yourself
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 y^=2.4x+310 GB\hat{y} = 2.4x + 310\ \text{GB}, where xx is days from today. The disk holds 500 GB. On which day does the trend cross the limit?

Answer

x=190/2.4≈79.2x = 190/2.4 \approx 79.2, so during day 80.

Solution
2.4x+310=5002.4x=190x=79.17 days\begin{aligned} 2.4x + 310 &= 500 \\ 2.4x &= 190 \\ x &= 79.17\ \text{days} \end{aligned}

Day 79 still ends below the limit (2.4⋅79+310=499.6 GB2.4 \cdot 79 + 310 = 499.6\ \text{GB}); the disk fills during day 80.

Exercise 3: The outlier effect (code)

Fit a line to x=1…6x = 1 \ldots 6, y=[3,5,7,9,11,13]y = [3, 5, 7, 9, 11, 13], then change the last yy to 40 and fit again. Print both slopes and intercepts.

Answer

Without the outlier: m=2m = 2, b=1b = 1. With it: m≈5.857m \approx 5.857, b≈−8.0b \approx -8.0. One bad point nearly triples the slope.

Solution

The first data lie exactly on y=2x+1y = 2x + 1. Raising the last yy by 27 raises yˉ\bar{y} by 27/6=4.527/6 = 4.5, and ∑(x−xˉ)(y−yˉ)\sum (x - \bar{x})(y - \bar{y}) by 27⋅(6−3.5)=67.527 \cdot (6 - 3.5) = 67.5; with ∑(x−xˉ)2=17.5\sum (x - \bar{x})^2 = 17.5 the slope grows by 67.5/17.5≈3.85767.5/17.5 \approx 3.857.

python · try it yourself
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?

  1. (0, 0)
  2. The first data point
  3. (xˉ,yˉ)(\bar{x}, \bar{y})
  4. The point with the largest yy

What does np.polyfit(x, y, 1) return?

  1. [slope, intercept]
  2. [intercept, slope]
  3. R2R^2 only
  4. The residuals

A fit has R2=0.2R^2 = 0.2. What does that mean?

  1. The slope is 0.2
  2. The line explains only about 20% of the variation in yy
  3. 20% of the points lie on the line
  4. The data has no errors