Learning path: Ship Your First Model: From Notebook to a FastAPI Service · Step 4 of 9
Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
The whole ML workflow on 205 cars: clean the brand out of CarName, split first, audition five regressors on the same folds, tune the random forest, test once (RMSE 2,195, R2 0.939), save it and serve prices with FastAPI.
What you will learn
- Explore and clean a small regression dataset, including a brand column hidden in a text field
- Split first and wrap preprocessing and any regressor in one pipeline
- Compare five models on the same five folds, tune the winner and test once
- Save the pipeline with joblib and serve prices from a FastAPI POST /predict route
Before you start
- Pipelines and ColumnTransformer
- Cross-Validation: KFold and cross_validate
- Deploy a Machine Learning Model with FastAPI
This project puts the whole machine learning workflow into one notebook. We start with a CSV of 205 cars and finish with a working price API. Every step is something you've seen on its own. The new part is doing them together, in the right order.
Think of it as building a house. You learned the bricks, the plumbing and the wiring one at a time. Now you build the whole thing:
Step 1: look at the data
import warnings
warnings.filterwarnings("ignore")
import joblib
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.metrics import root_mean_squared_error, r2_score
from sklearn.model_selection import (
train_test_split, KFold, cross_validate, RandomizedSearchCV)
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from xgboost import XGBRegressor
df = pd.read_csv("CarPrice.csv")
print(df.shape, "missing:", df.isna().sum().sum())
stats = df["price"].agg(["min", "median", "mean", "max"])
print(stats.round(0).astype(int).to_dict())
(205, 26) missing: 0
{'min': 5118, 'median': 10295, 'mean': 13277, 'max': 45400}
205 cars, 26 columns and no missing values. Prices run from $5,118 to $45,400, and half the cars cost under $10,295. The mean is higher than the median, so a few expensive cars pull it up.
Which columns move the price? Correlation of every number column with the price, sorted:
corr = df.corr(numeric_only=True)["price"].drop("price")
corr = corr.sort_values(ascending=False)
top = pd.concat([corr.head(4), corr.tail(2)])
print(top.round(2).to_string())
enginesize 0.87
curbweight 0.84
horsepower 0.81
carwidth 0.76
citympg -0.69
highwaympg -0.70
Bigger, heavier, stronger cars cost more, and thirsty cars cost more too. We keep the top four plus highwaympg.
Step 2: the brand hides in CarName
The brand matters a lot, but there's no brand column. It hides in CarName, as the first word. So we make a new column from an old one:
df["brand"] = df["CarName"].str.split().str[0].str.lower()
brands = sorted(df["brand"].unique())
print(len(brands), "brands")
print(brands[8:12])
print(brands[-4:])
27 brands
['jaguar', 'maxda', 'mazda', 'mercury']
['vokswagen', 'volkswagen', 'volvo', 'vw']
27 brands, but look closer: maxda next to mazda, vokswagen and vw next to volkswagen. Typos. A small dictionary fixes them:
fix = {"maxda": "mazda", "porcshce": "porsche",
"toyouta": "toyota", "vokswagen": "volkswagen",
"vw": "volkswagen"}
df["brand"] = df["brand"].replace(fix)
print(df["brand"].nunique(), "brands")
22 brands
Without this step, every typo would become an extra car maker, and the model would learn them as different companies.
Step 3: split first
Five number columns, four category columns, and price as the label. Then split before anything is fitted:
num = ["enginesize", "curbweight", "horsepower",
"carwidth", "highwaympg"]
cat = ["brand", "carbody", "drivewheel", "fueltype"]
X, y = df[num + cat], df["price"]
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)
(164, 9) (41, 9)
164 cars to train on, 41 to test. The 41 test cars are now locked away. We touch them once, at the very end.
Step 4: one pipeline for every model
The number lane fills gaps with the median and scales. The category lane fills gaps with the most frequent value and one-hot encodes; handle_unknown="ignore" means a value it hasn't seen before (say, a rare brand that only appears in a test car) is simply ignored instead of crashing. make_model puts any regressor behind this recipe, so every model is treated the same way and nothing leaks from the test cars.
num_lane = make_pipeline(
SimpleImputer(strategy="median"), StandardScaler())
cat_lane = make_pipeline(
SimpleImputer(strategy="most_frequent"),
OneHotEncoder(handle_unknown="ignore"))
preprocess = ColumnTransformer([
("num", num_lane, num), ("cat", cat_lane, cat)])
def make_model(reg):
return Pipeline([("preprocess", preprocess),
("model", reg)])
print(X_train.shape, "->",
preprocess.fit_transform(X_train).shape)
(164, 9) -> (164, 37)
Nine columns go in, 37 numbers come out: 5 scaled numbers plus 32 one-hot columns for the categories. All of it fitted on the training cars only. (More on this pattern in Pipelines and ColumnTransformer.)
Step 5: the model zoo
Think of it as auditions. Five models, default settings:
zoo = {
"dummy": DummyRegressor(),
"linear": LinearRegression(),
"ridge": Ridge(),
"forest": RandomForestRegressor(random_state=42),
"xgboost": XGBRegressor(random_state=42),
}
cv = KFold(n_splits=5, shuffle=True, random_state=42)
scoring = {"rmse": "neg_root_mean_squared_error",
"r2": "r2"}
The dummy always guesses the average price, like the friend who gives the same answer to every question. It's the bar to beat. The other four are the real contestants. cv is a shuffled 5-fold KFold with a fixed random_state, so every model gets the very same folds, and we score RMSE and R squared.
rows = {}
for name, reg in zoo.items():
pipe = make_model(reg)
s = cross_validate(pipe, X_train, y_train,
cv=cv, scoring=scoring)
rows[name] = [-s["test_rmse"].mean(),
s["test_r2"].mean()]
board = pd.DataFrame(rows, index=["RMSE", "R2"]).T
board["RMSE"] = board["RMSE"].round().astype(int)
print(board.round(3))
RMSE R2
dummy 7767 -0.052
linear 2987 0.836
ridge 2734 0.862
forest 2584 0.884
xgboost 2766 0.866
scikit-learn reports RMSE as a negative score (higher is better for every scorer), so we flip the sign back with the minus.
The dummy is off by $7,767 on average, and its R squared is below zero. The random forest wins with RMSE 2,584 and R squared 0.884, with ridge and XGBoost close behind. All five were scored on the same folds, so the board is fair.
Step 6: tune the winner
params is the menu: 3 × 3 × 3 × 3 = 81 combinations. RandomizedSearchCV tries 10 of them on the same five folds, scored by RMSE, on the training data only.
params = {"model__n_estimators": [100, 200, 400],
"model__max_depth": [None, 5, 10],
"model__min_samples_leaf": [1, 2, 4],
"model__max_features": [1.0, 0.5, "sqrt"]}
search = RandomizedSearchCV(
make_model(RandomForestRegressor(random_state=42)),
params, n_iter=10, cv=cv, random_state=42,
scoring="neg_root_mean_squared_error")
search.fit(X_train, y_train)
for k, v in search.best_params_.items():
print(k[7:], v)
print("CV RMSE", round(-search.best_score_))
n_estimators 100
min_samples_leaf 1
max_features sqrt
max_depth None
CV RMSE 2392
The model__ prefix tells the search which step of the pipeline each setting belongs to (k[7:] just cuts it off for printing). The best setting is 100 trees, no depth limit, one sample per leaf and max_features="sqrt", and the cross-validated RMSE drops from 2,584 to 2,392.
Step 7: the test set, once
best = search.best_estimator_
pred = best.predict(X_test)
rmse = root_mean_squared_error(y_test, pred)
print("test RMSE", round(rmse),
"R2", round(r2_score(y_test, pred), 3))
dummy = DummyRegressor().fit(X_train, y_train)
base = root_mean_squared_error(
y_test, dummy.predict(X_test))
print("dummy RMSE", round(base))
test RMSE 2195 R2 0.939
dummy RMSE 8889
On 41 cars it has never seen, the model is off by about $2,200, with R squared 0.939. The dummy is off by $8,889 on the same cars. Not perfect, but far better than guessing.
Test once. All the choosing happened on the training cars, with cross-validation. If you go back and tweak after seeing this number, the test set stops being an honest exam.
Step 8: save the whole pipeline
One file holds the cleaning, the encoding and the forest. Then load it back and price the first test car:
joblib.dump(best, "car_model.joblib")
loaded = joblib.load("car_model.joblib")
car = X_test.iloc[[0]]
show = ["brand", "carbody", "enginesize",
"horsepower", "drivewheel"]
print(car[show].to_string(index=False))
print("predicted", round(loaded.predict(car)[0]),
"actual", round(y_test.iloc[0]))
brand carbody enginesize horsepower drivewheel
bmw sedan 209 182 rwd
predicted 29904 actual 30760
A BMW sedan with a 209 engine size, 182 horsepower and rear-wheel drive. Predicted $29,904, actual $30,760. Note the double brackets in X_test.iloc[[0]]: they keep it a one-row DataFrame, because even one car must be a table. (The full story is in Saving and Loading Models with joblib.)
Step 9: serve it with FastAPI
The finished project folder has app.py, the same shape as the rain predictor API:
from typing import Literal
import joblib
import pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel
class Car(BaseModel):
enginesize: float
curbweight: float
horsepower: float
carwidth: float
highwaympg: float
brand: str
carbody: Literal["convertible", "hardtop", "hatchback",
"sedan", "wagon"]
drivewheel: Literal["fwd", "rwd", "4wd"]
fueltype: Literal["gas", "diesel"]
app = FastAPI(title="Car Price Predictor")
model = joblib.load("car_model.joblib") # loaded once
@app.post("/predict")
def predict(car: Car):
row = pd.DataFrame([car.model_dump()])
return {"price": round(float(model.predict(row)[0]))}
The model is loaded once, at startup. The Car class describes the input: five numbers, the brand as free text, and three categories with fixed choices. A request to POST /predict is checked field by field, turned into a one-row DataFrame, and the pipeline predicts.
To run it as a server, use python -m uvicorn app:app --port 8000 in that folder and open /docs. In the notebook, we call it without a server, using FastAPI's TestClient (more on it in Testing a FastAPI App with pytest), and post the same BMW as JSON:
from fastapi.testclient import TestClient
import app as car_app
client = TestClient(car_app.app)
payload = car.to_dict("records")[0]
r = client.post("/predict", json=payload)
print(r.status_code, r.json())
200 {'price': 29904}
Status 200 and the same $29,904 as the notebook. Now any app or website can ask the model for a price.
The project's requirements.txt:
scikit-learn==1.9.1
pandas==3.0.6
numpy==2.5.3
xgboost==3.4.1
joblib
fastapi==0.162.0
uvicorn
httpx
httpx is there because TestClient uses it. The model libraries are pinned; pin joblib and uvicorn too if you want the setup to repeat exactly.
Recap
| Part | Step | Result |
|---|---|---|
| Foundation | Look, clean the brand | 205 × 26, no missing values; 27 brands fixed to 22 |
| Walls | Split first, one pipeline | 164 / 41 cars; 9 columns become 37 numbers |
| Rooms | Five models, then tune | forest CV RMSE 2,584, tuned to 2,392 |
| Roof | Test once | RMSE 2,195, R2 0.939 (dummy 8,889) |
| Keys | Save, serve | car_model.joblib; POST /predict gives 200 {'price': 29904} |
The same recipe works for almost any table of data. The starter notebook (with TODOs), the finished notebook and the dataset are in the community, free to join.
Try it yourself
Add carlength and citympg to the num list and run everything again. Does the test RMSE improve? (Remember: decide with cross-validation first, then test once.)
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Deploy a Machine Learning Model with FastAPI: POST /predict for a Saved Model
Next →Python Virtual Environments: One Project, One Toolbox
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)