Learning path: Predict a Number: Regression from Scratch to Regularisation · Step 3 of 6
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
What you will learn
- Fit LinearRegression on one column and read coef_ and intercept_
- Explain what predict does with the slope and the intercept
- Put LinearRegression at the end of a preprocessing pipeline and read one coefficient per column
- Explain why LinearRegression does not choose features for you
Before you start
- Linear Regression and the Cost Function
- Train-Test Split and Data Leakage
- Pipelines and ColumnTransformer
Think of an insurance bill as a shop receipt. Everyone pays a base fee. Then every year of age adds a fixed price. Add it up and you have the bill.
That's all a straight line is. The base fee is the intercept (our b), the price per year is the coefficient (our w), and the total is the prediction. In Linear Regression and the Cost Function we drew and scored lines by hand, and in Gradient Descent the computer walked to the best one. Now scikit-learn does that search for us, on real data.
Load the data and split first
The dataset is insurance.csv: 1,338 people, with their age, sex, bmi, children, smoker, region and the yearly medical bill, charges. That's the number we predict.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
df = pd.read_csv("insurance.csv")
X = df.drop(columns="charges")
y = df["charges"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
print(X_train.shape, X_test.shape)
(1070, 6) (268, 6)
1,070 people to learn from, 268 kept back to test. As always, we split before anything learns from the data (see Train-Test Split and Data Leakage).
One input: age
Same pattern as every scikit-learn model: create, then fit. We give fit only the age column. The double brackets in X_train[["age"]] keep it a table with one column, which is what fit expects.
simple = LinearRegression()
simple.fit(X_train[["age"]], y_train)
print(simple.coef_.round(2))
print(round(simple.intercept_, 2))
[240.6]
3876.93
coef_is the price per year of age: $240.60.intercept_is the base fee: $3,876.93.
Note the trailing underscore. In scikit-learn, attributes that end in _ are learned during fit.
What predict does
new = pd.DataFrame({"age": [40]})
print(simple.predict(new).round(2))
[13500.79]
Nothing magic, just the receipt: base fee plus price tag times age, 3876.93 + 240.6 * 40. That's about $13,500. (The printed 240.6 is rounded; predict uses the full slope, which is why the result is 13500.79.)
More inputs, more price tags
Age alone isn't the whole story. With more inputs the formula simply grows, one knob per column:
y_hat = b + w1·age + w2·bmi + w3·children + w4·smoker_yes + ...
Number columns go in as they are. Text columns need a small change first: smoker becomes a new column smoker_yes, which is 1 for yes and 0 for no. That's one-hot encoding (see Encoding Categorical Data). It's still one straight-line formula, just with more knobs.
Every column, one pipeline
This is the same idea as Pipelines and ColumnTransformer: prepare the number and text columns in separate lanes, then put the model at the end.
First, find the number columns and the text columns:
num_cols = X.select_dtypes(include="number").columns
cat_cols = X.select_dtypes(exclude="number").columns
print(list(num_cols), list(cat_cols))
['age', 'bmi', 'children'] ['sex', 'smoker', 'region']
Number columns get any gaps filled with the median. Text columns get gaps filled with the most frequent value, then the one-hot encoder makes the 0/1 columns. drop="first" keeps one column less per group, so every tag reads as "compared with the dropped group".
cat_steps = Pipeline([
("fill", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(drop="first",
handle_unknown="ignore")),
])
preprocess = ColumnTransformer([
("num", SimpleImputer(strategy="median"), num_cols),
("cat", cat_steps, cat_cols),
], verbose_feature_names_out=False)
Then LinearRegression goes at the end of the pipeline:
model = Pipeline([("preprocess", preprocess),
("reg", LinearRegression())])
model.fit(X_train, y_train)
print(list(model.named_steps))
['preprocess', 'reg']
There's no scaler here, on purpose. Without scaling, every tag stays in plain dollars.
Read the price tags
Take the column names from the preprocess step and the fitted model from the reg step, and put each name next to its coefficient:
prep = model.named_steps["preprocess"]
reg = model.named_steps["reg"]
names = prep.get_feature_names_out()
tags = pd.Series(reg.coef_, index=names)
print(tags.round(0).astype(int).to_string())
print("intercept", round(reg.intercept_))
age 257
bmi 337
children 425
sex_male -19
smoker_yes 23651
region_northwest -371
region_southeast -658
region_southwest -810
intercept -11931
Each tag is what one extra unit adds to the bill when everything else stays the same:
- age: $257 per year.
- bmi: $337 per bmi point.
- children: $425 per child.
- smoker_yes: $23,651. For the same age and bmi, a smoker pays that much more. The biggest tag by far.
Three people the model never saw
Does using every column help? Take the first three people from the test rows and compare the real bill with both models:
people = X_test.head(3)
out = people[["age", "bmi", "smoker"]].copy()
out["actual"] = y_test.head(3)
out["age_only"] = simple.predict(people[["age"]])
out["all_cols"] = model.predict(people)
out.round({"actual": 0, "age_only": 0,
"all_cols": 0})
age bmi smoker actual age_only all_cols
764 45 25.175 no 9095.0 14704.0 8970.0
887 36 30.020 no 5272.0 12538.0 7069.0
890 64 26.885 yes 29331.0 19275.0 36858.0
The 45-year-old non-smoker really paid $9,095. Age only guessed $14,704; all columns guessed $8,970. The 64-year-old smoker paid $29,331, and age only said $19,275 because it can't see the smoker. For all three people, the all-columns guess lands closer. Three people are not a proper score, though. That's what Regression Metrics is for.
LinearRegression does not choose features
Look at sex_male again: -19 dollars. Tiny, but it's still there. Linear regression gives every column a tag. It doesn't drop a column that doesn't help, and it doesn't choose features for you. Choosing the columns is your job.
Common mistakes
- Passing
X_train["age"]with single brackets. That's a Series, not a table. UseX_train[["age"]]. - Reading the tags after scaling as dollars. These tags are in dollars only because there's no scaler in this pipeline.
- Forgetting the dropped group. With
drop="first",region_southwest= -810 means "compared with the dropped region", not compared with zero. - Expecting the model to ignore useless columns. It won't; every column gets a coefficient.
Quick recap
| Step | Code | Insurance result |
|---|---|---|
| Split first | train_test_split(..., test_size=0.2) | 1,070 train, 268 test |
| Fit on one column | simple.fit(X_train[["age"]], y_train) | coef 240.6, intercept 3876.93 |
| Predict | simple.predict(new) | age 40: 13500.79 |
| Every column | pipeline + LinearRegression() | 8 tags, smoker_yes 23651 |
| Read the tags | get_feature_names_out() + coef_ | intercept -11931 |
Try it yourself
Fit simple on bmi instead of age. What is the price tag for one extra bmi point? Then predict the charge for a person with bmi 30.
The notebook and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Gradient Descent Explained: Feel the Slope, Step Downhill
Next →Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.
Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
Give a linear model extra columns with PolynomialFeatures and it can bend. Then watch train and test scores split apart: degrees 1, 2 and 16 on Canada's income per person, and degrees 1 to 5 on the insurance model.