Skip to content

MLDay 7 of 50Foundations

Use Many Features

Multiple Linear Regression

8 min read

Day 4's line gives every 25 °C hour the same forecast. But a dry 25 °C afternoon and a muggy 25 °C night are very different hours for a bike-share. To tell them apart, the model needs more than one input.

The idea

In Day 4, one feature had one weight. Now each hour is described by several features at once: temperature, humidity, wind speed and the hour of the day. Written as a list, such as (25, 60, 13, 17), they form a feature vector: one row of the table.

The model gives each feature its own weight. It multiplies each feature by its weight, adds the products, then adds the bias. Multiply-then-add is called the dot product. Fitting works as before: choose the weights and bias that leave the smallest squared residuals.

To read a weight:

  • Sign: a positive weight raises the prediction as the feature grows; a negative one lowers it.
  • Size: how much the prediction moves when that feature grows by 1 and the others stay fixed.
  • Units: "by 1" means one unit of that feature. A weight of −2 per percent of humidity is the same as −200 per unit, if humidity is stored as a fraction from 0 to 1. So a bigger weight doesn't mean a more important feature. Day 9 puts features on one scale.

The model is still linear: each feature pushes the prediction along a straight line, by the same amount everywhere. It can't see a curve, like rentals peaking at 8 a.m. and 5 p.m. It also can't see an interaction, where one feature's effect depends on another, like warmth mattering more at rush hour.

A tiny example

Say rentals ≈ 8 × temperature − 2 × humidity + 150, with temperature in °C and humidity in percent.

Hour Temperature (°C) Humidity (%) Prediction
A 20 30 160 − 60 + 150 = 250
B 20 90 160 − 180 + 150 = 130
C 30 70 240 − 140 + 150 = 250

A and B have the same temperature, yet the model expects 120 fewer rentals in the muggy hour. A one-feature line can't make that difference. C is 10 °C warmer than A but 40 points more humid, and the two pushes cancel.

The formula

The prediction is the dot product of the weights and the features, plus the bias:

y^=w⋅x+b=w1x1+w2x2+⋯+wdxd+b\hat{y} = \mathbf{w}\cdot\mathbf{x} + b = w_1 x_1 + w_2 x_2 + \dots + w_d x_d + b
Symbol Meaning
y^\hat{y} the prediction
x\mathbf{x} the feature vector (x1,…,xd)(x_1, \dots, x_d): one row's inputs (bold marks a list of numbers)
w\mathbf{w} the weights (w1,…,wd)(w_1, \dots, w_d), one per feature
dd the number of features
bb the bias: the prediction when every feature is 0
⋅\cdot the dot product: multiply matching entries, then add them up

Worked: w=(20,−3)\mathbf{w} = (20, -3), x=(10,5)\mathbf{x} = (10, 5) and b=40b = 40 give y^=20×10+(−3)×5+40=200−15+40=225\hat{y} = 20 \times 10 + (-3) \times 5 + 40 = 200 - 15 + 40 = 225.

Try it

Weigh temperature and humidity

Each weight says how much its feature counts; the bias b is the starting point. Move the sliders to bring the predictions close to the targets.

z = 5·Temperature (°C) + 0·Humidity (%) + 50

Every row
Temperature (°C)Humidity (%)z = ŷtarget y
108010075
1540125185
2060150200
2530175280
3070200255
2090150135

row 1: z = 100RMSE 59.161

The humidity weight starts at 0, so this is a one-feature line, and the RMSE (a typical miss, from Day 5) is about 59. Using temperature alone, the best you can reach is about 36.5. Now make the humidity weight negative and adjust the other two: near w=(8,−1.8)w = (8, -1.8), b=140b = 140, the RMSE drops to about 4.5.

In code

LinearRegression fits one weight per column of the table, so more features just means more columns.

# script_id: day_007_multiple_linear_regression/tiny_fit
import numpy as np
from sklearn.linear_model import LinearRegression

w, b = np.array([20, -3]), 40
x = np.array([10, 5])
print("w · x + b =", np.dot(w, x) + b)                  # 200 - 15 + 40

X = np.array([[10, 80], [15, 40], [20, 60], [25, 30], [30, 70], [20, 90]])  # °C, humidity %
y = np.array([75, 185, 200, 280, 255, 135])
model = LinearRegression().fit(X, y)                    # one weight per column
print("w =", model.coef_.round(2), " b =", round(model.intercept_, 1))
print("20 °C at 30% and 90% humidity:", model.predict([[20, 30], [20, 90]]).round())
w · x + b = 225
w = [ 8.05 -1.74]  b = 134.7
20 °C at 30% and 90% humidity: [244. 139.]

The fit lands close to the best point you found in the playground. Now the real hours. The file stores temperature ÷ 41, humidity ÷ 100 and wind ÷ 67, so the script undoes each. The model trains on the oldest 75% of hours and is scored on the newest 25% (from July 2012 on), a time-ordered split from Day 6. Features are added one at a time.

# script_id: day_007_multiple_linear_regression/bikes
import os
from pathlib import Path

import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import root_mean_squared_error
from sklearn.model_selection import train_test_split

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])
df = df.assign(temp_c=df["temp"] * 41, hum_pct=df["hum"] * 100, wind_kmh=df["windspeed"] * 67)
train, test = train_test_split(df, test_size=0.25, shuffle=False)  # time order: oldest 75% trains

features = []
for name in ["temp_c", "hum_pct", "wind_kmh", "hr"]:
    features.append(name)
    model = LinearRegression().fit(train[features], train["cnt"])
    rmse = root_mean_squared_error(test["cnt"], model.predict(test[features]))
    print(f"{', '.join(features):30s} test RMSE {rmse:5.1f}  w = {model.coef_.round(2)}")
temp_c                         test RMSE 217.2  w = [8.52]
temp_c, hum_pct                test RMSE 207.7  w = [ 8.19 -2.44]
temp_c, hum_pct, wind_kmh      test RMSE 207.7  w = [ 8.2  -2.39  0.42]
temp_c, hum_pct, wind_kmh, hr  test RMSE 198.1  w = [ 7.45 -1.84  0.05  6.61]

The first row is Day 6's temperature-only line, with the same test RMSE of 217.2. Humidity cuts the typical miss by about 10 rentals, and its weight is negative, as in the tiny example. Wind adds nothing. The hour helps about as much as humidity, yet the model still misses by about 200 rentals an hour. The weights also shift as features join, because each now means "with the others held fixed".

Two checks show the limits: one on units, and one on what a straight line can't bend to.

# script_id: day_007_multiple_linear_regression/bikes
raw = LinearRegression().fit(train[["temp_c", "hum"]], train["cnt"])  # humidity as stored, 0 to 1
print("humidity weight per unit of the 0-1 column:", raw.coef_[1].round(1))

print("average rentals at 3, 8, 17, 23 h:", train.groupby("hr")["cnt"].mean()[[3, 8, 17, 23]].round().tolist())
for h in [3, 17]:
    rows = train[train["hr"] == h]
    slope = LinearRegression().fit(rows[["temp_c"]], rows["cnt"]).coef_[0]
    print(f"at {h:2d} h, each extra °C adds {slope:4.1f} rentals")
humidity weight per unit of the 0-1 column: -244.4
average rentals at 3, 8, 17, 23 h: [11.0, 315.0, 409.0, 77.0]
at  3 h, each extra °C adds  0.4 rentals
at 17 h, each extra °C adds 15.7 rentals

The same humidity effect is −2.44 per percent or −244.4 per unit; only the unit changed. The hour weight of 6.61 says each later hour adds about 7 rentals, so 11 p.m. should be the busiest. Really, rentals peak at 8 a.m. and 5 p.m. and fall to 77 by 11 p.m. Warmth adds 0.4 rentals at 3 a.m. but 15.7 at 5 p.m., an interaction one fixed weight can't hold.

Quick check

Quick check

1. w = (20, −3), x = (10, 5) and b = 40. What is the prediction?

2. The humidity weight is −2.44 per percent. What does it mean?

3. Why does the model with the hour still miss the rush hours?

Next

Day 8: Project 1 puts Phase 1 together into an honest bike-share baseline and a report on what it still can't do.

Data: Bike Sharing Dataset (UCI Machine Learning Repository, dataset 275), CC BY 4.0; cite Fanaee-T, H. and Gama, J. (2013), "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence, doi:10.1007/s13748-013-0040-3.

Next · Day 8 · 7 minProject 1: a Bike-Share Demand Baseline← Previous: Day 6 · Split Data Without Leaking
Not tapped yet