ML Multiple Regression
Simple linear regression predicts a value from one input. Real outcomes usually depend on several things at once. The price of a used bike depends on its age, and on its original price, and on how many kilometres it has done. Multiple regression is linear regression with more than one input variable:
y = b0 + b1*x1 + b2*x2 + b3*x3 + ...Each input gets its own coefficient (b1, b2, …), which tells you how much y changes when that input increases by 1 while the others stay the same.
The data set
Let's use an invented table of 15 used e-bikes. Data is often stored as CSV; since the playground cannot read files, we put the CSV text in a string and read it with io.StringIO, which behaves like a file:
import io
import pandas as pd
csv = """age_years,new_price,km,price
1,2400,1200,1980
2,2400,4800,1650
3,2400,9000,1290
1,1800,2500,1420
2,1800,3100,1290
4,1800,15000,760
1,3200,800,2750
2,3200,6000,2390
3,3200,7500,2120
5,3200,21000,1350
2,1500,5200,1010
3,1500,8800,820
1,2800,3000,2330
4,2800,12500,1520
6,2000,26000,560"""
bikes = pd.read_csv(io.StringIO(csv))
print(bikes.head())
print(bikes.shape) age_years new_price km price
0 1 2400 1200 1980
1 2 2400 4800 1650
2 3 2400 9000 1290
3 1 1800 2500 1420
4 2 1800 3100 1290
(15, 4)
Fitting the model
In scikit-learn the inputs are a table X (here three columns) and the target is a single column y. Selecting several pandas columns with a list gives exactly the 2-D table scikit-learn expects:
import io
import pandas as pd
from sklearn.linear_model import LinearRegression
csv = """age_years,new_price,km,price
1,2400,1200,1980
2,2400,4800,1650
3,2400,9000,1290
1,1800,2500,1420
2,1800,3100,1290
4,1800,15000,760
1,3200,800,2750
2,3200,6000,2390
3,3200,7500,2120
5,3200,21000,1350
2,1500,5200,1010
3,1500,8800,820
1,2800,3000,2330
4,2800,12500,1520
6,2000,26000,560"""
bikes = pd.read_csv(io.StringIO(csv))
X = bikes[["age_years", "new_price", "km"]]
y = bikes["price"]
model = LinearRegression()
model.fit(X, y)
new_bike = pd.DataFrame({"age_years": [3], "new_price": [2600], "km": [7000]})
print("predicted price:", model.predict(new_bike).round(0))
print("R^2 on the data:", round(model.score(X, y), 3))predicted price: [1620.]
R^2 on the data: 0.974
We passed the new bike as a DataFrame with the same column names as X. If you pass a plain list instead, scikit-learn still works but warns that the feature names are missing.
Reading the coefficients
The fitted model stores one coefficient per input in coef_ and the constant in intercept_:
import io
import pandas as pd
from sklearn.linear_model import LinearRegression
csv = """age_years,new_price,km,price
1,2400,1200,1980
2,2400,4800,1650
3,2400,9000,1290
1,1800,2500,1420
2,1800,3100,1290
4,1800,15000,760
1,3200,800,2750
2,3200,6000,2390
3,3200,7500,2120
5,3200,21000,1350
2,1500,5200,1010
3,1500,8800,820
1,2800,3000,2330
4,2800,12500,1520
6,2000,26000,560"""
bikes = pd.read_csv(io.StringIO(csv))
X = bikes[["age_years", "new_price", "km"]]
model = LinearRegression().fit(X, bikes["price"])
for name, coef in zip(X.columns, model.coef_):
print(f"{name:10} {coef:9.4f}")
print(f"intercept {model.intercept_:9.2f}")age_years -254.0531
new_price 0.7661
km -0.0013
intercept 398.65
Read them like this:
- every extra year of age changes the price by the
age_yearscoefficient, if new price and kilometres stay the same, - every extra unit of new price adds a fraction of a unit to the used price,
- every extra kilometre lowers the price only very slightly (multiply the
kmcoefficient by 1 000 to see the effect of 1 000 km).
Note: You cannot compare coefficients directly to decide which feature "matters most": they depend on the units. A kilometre is tiny compared with a year. The next lesson, Scale, fixes this by putting all features on the same scale.
What-if questions
Because the model is linear, the effect of each input is additive. Let's compare otherwise identical bikes:
import io
import pandas as pd
from sklearn.linear_model import LinearRegression
csv = """age_years,new_price,km,price
1,2400,1200,1980
2,2400,4800,1650
3,2400,9000,1290
1,1800,2500,1420
2,1800,3100,1290
4,1800,15000,760
1,3200,800,2750
2,3200,6000,2390
3,3200,7500,2120
5,3200,21000,1350
2,1500,5200,1010
3,1500,8800,820
1,2800,3000,2330
4,2800,12500,1520
6,2000,26000,560"""
bikes = pd.read_csv(io.StringIO(csv))
model = LinearRegression().fit(bikes[["age_years", "new_price", "km"]], bikes["price"])
what_if = pd.DataFrame({
"age_years": [2, 2, 2, 3],
"new_price": [2400, 2400, 3400, 2400],
"km": [5000, 10000, 5000, 5000],
})
what_if["predicted"] = model.predict(what_if).round(0)
print(what_if) age_years new_price km predicted
0 2 2400 5000 1723.0
1 2 2400 10000 1717.0
2 2 3400 5000 2489.0
3 3 2400 5000 1469.0
The first row is the baseline; each of the other rows changes exactly one thing, so the difference in prediction is that feature's effect.
Test yourself
What makes a regression 'multiple'?
- It predicts several targets
- It uses more than one input variable
- It is trained several times
- It uses a curved line
Where does a fitted LinearRegression store one coefficient per feature?
model.coef_model.weightsmodel.intercept_model.features_
Why can't you rank feature importance by comparing raw coefficients?
- Coefficients are random
- They depend on each feature's units and scale
- Only the intercept matters
- scikit-learn hides the real values