TExcelTAD
Home › Data Science › DS Slope & Intercept

DS Slope & Intercept

A straight line is fully described by two numbers: its slope and its intercept. In this lesson you'll compute them from points, find the best-fitting line for the Riverside Bikes data, and learn what the two numbers mean in plain language.

Slope: rise over run

The slope measures how much y changes when x increases by one unit. From two points (x1, y1) and (x2, y2) on a line:

text
slope = (y2 − y1) / (x2 − x1)        "rise over run"

Once you know the slope, the intercept follows from either point: intercept = y1 − slope × x1.

python · try it yourself
def line_through(p1, p2):
    (x1, y1), (x2, y2) = p1, p2
    slope = (y2 - y1) / (x2 - x1)
    intercept = y1 - slope * x1
    return slope, intercept

# two rides on the pay-per-minute plan: (minutes, price)
slope, intercept = line_through((10, 3.50), (35, 8.50))
print("slope:", round(slope, 2), "EUR per minute")
print("intercept:", round(intercept, 2), "EUR")
slope: 0.2 EUR per minute
intercept: 1.5 EUR

From just two receipts we recovered the price list: €0.20 per minute plus a €1.50 unlock fee.

Interpreting the sign

Slope Meaning Riverside Bikes example
positive y rises as x rises warmer → more rides
negative y falls as x rises more rain → fewer rides
zero y doesn't depend on x a day pass costs the same for any length

Real data isn't on one line

With measurements, every pair of points gives a slightly different slope, because real data has noise:

python · try it yourself
temp = [6.4, 29.4, 23.8, 24.4, 7.3, 15.7]      # days 5 to 10
rides = [254, 523, 497, 428, 209, 368]

for i in range(len(temp) - 1):
    s = (rides[i + 1] - rides[i]) / (temp[i + 1] - temp[i])
    print(f"day {i + 5} -> day {i + 6}: slope {s:6.1f} rides per degree")
day 5 -> day 6: slope   11.7 rides per degree
day 6 -> day 7: slope    4.6 rides per degree
day 7 -> day 8: slope -115.0 rides per degree
day 8 -> day 9: slope   12.8 rides per degree
day 9 -> day 10: slope   18.9 rides per degree

The slopes jump around wildly: from day 7 to day 8 the temperature barely changed (0.6 °C) while rides fell by 69, giving a slope of −115. Instead of picking two points, we want the line that fits all points best. The standard choice is the least-squares line: the line that makes the sum of squared vertical distances between points and line as small as possible.

The best-fitting line

np.polyfit(x, y, 1) finds the least-squares straight line (a polynomial of degree 1) and returns [slope, intercept]. Let's use all 60 days of Riverside Bikes data:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

slope, intercept = np.polyfit(bikes["temp_c"], bikes["rides"], 1)
print(f"rides = {intercept:.2f} + {slope:.2f} x temp_c")

for t in [10, 20, 25]:
    print(f"predicted rides at {t} °C: {intercept + slope * t:.0f}")
rides = 135.81 + 12.54 x temp_c
predicted rides at 10 °C: 261
predicted rides at 20 °C: 387
predicted rides at 25 °C: 449

Read the result as:

  • Slope ≈ 12.5: each extra degree brings about 12.5 more rentals per day.
  • Intercept ≈ 136: the line's value at 0 °C — about 136 rides.

Be careful with the intercept

The intercept is the prediction at x = 0. Sometimes that's meaningful (the unlock fee at 0 minutes), but our data only covers 4–30 °C. Predicting at 0 °C — or worse, at −15 °C — is extrapolation: the line may not hold outside the observed range (frozen paths, snow…).

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

slope, intercept = np.polyfit(bikes["temp_c"], bikes["rides"], 1)
x = np.linspace(-15, 30, 100)
plt.scatter(bikes["temp_c"], bikes["rides"], s=15, label="Observed days")
plt.plot(x, intercept + slope * x, color="red", label="Least-squares line")
plt.axvspan(-15, bikes["temp_c"].min(), color="grey", alpha=0.2, label="No data here")
plt.xlabel("Temperature (°C)")
plt.ylabel("Rides")
plt.legend()
plt.show()
print(f"Prediction at -15 °C: {intercept + slope * -15:.0f} rides (an extrapolation!)")
Prediction at -15 °C: -52 rides (an extrapolation!)

The model happily predicts about −52 rides at −15 °C, which is impossible. A model is only trustworthy in the range of data it was fitted on.

Test yourself

A line passes through (2, 10) and (6, 30). What is its slope?

  1. 4
  2. 5
  3. 10
  4. 20

The fitted line is rides = 136 + 12.5 × temp. What does 12.5 mean?

  1. Rides at 0 °C
  2. About 12.5 more rides per day for each extra degree
  3. The average temperature
  4. The number of days

Why is predicting rides at −15 °C with this line risky?

  1. The slope is negative
  2. It is an extrapolation far outside the observed 4–30 °C range
  3. polyfit can't handle negative numbers
  4. The intercept is too small