Python ML Capstone A: Predict House Prices
This capstone predicts house prices on the California Housing data. It runs the full loop: look, clean, split, train, and compare.
Look at the data first
The data holds 20,640 rows and 8 features. The average price is about 2.07, in hundreds of thousands of dollars.
import numpy as np
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing()
print("Rows:", housing.data.shape[0])
print("Features:", housing.data.shape[1])
print("Target mean:", round(float(np.mean(housing.target)), 2))A simple model first
Ridge regression is the plain baseline. Its error sets the bar the tree models must beat.
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X_train, X_test, y_train, y_test = train_test_split(housing.data, housing.target, test_size=0.2, random_state=42)
ridge = Pipeline([("scale", StandardScaler()), ("model", Ridge(random_state=42))])
ridge.fit(X_train, y_train)
print("Ridge RMSE:", round(float(np.sqrt(mean_squared_error(y_test, ridge.predict(X_test)))), 4))The forest beats the baseline
A Random Forest cuts the error from 0.75 to 0.51. The trees find patterns the straight line misses.
from sklearn.ensemble import RandomForestRegressor
forest = Pipeline([("scale", StandardScaler()), ("model", RandomForestRegressor(n_estimators=100, random_state=42))])
forest.fit(X_train, y_train)
print("Random Forest RMSE:", round(float(np.sqrt(mean_squared_error(y_test, forest.predict(X_test)))), 4))Example
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from xgboost import XGBRegressor
housing = fetch_california_housing()
print("Rows:", housing.data.shape[0], "Features:", housing.data.shape[1])
X_train, X_test, y_train, y_test = train_test_split(
housing.data, housing.target, test_size=0.2, random_state=42)
models = {
"Random Forest": Pipeline([
("scale", StandardScaler()),
("model", RandomForestRegressor(n_estimators=100, random_state=42)),
]),
"XGBoost": Pipeline([
("scale", StandardScaler()),
("model", XGBRegressor(n_estimators=200, random_state=42)),
]),
}
for name, model in models.items():
model.fit(X_train, y_train)
pred = model.predict(X_test)
rmse = float(np.sqrt(mean_squared_error(y_test, pred)))
print(name, "RMSE:", round(rmse, 4))Key points
- Capstone: a full project that joins the course skills into one working model
- Use fetch_california_housing to load 20,640 rows of housing data
- Use a Pipeline to keep the scaling step inside the model
- RMSE: the average prediction error in the same units as the price
- Use RandomForestRegressor for a strong baseline that needs no scaling
- Use XGBRegressor for a boosting model on the same rows
In this example, fetch_california_housing loads 20,640 rows with 8 features. train_test_split sets aside a fifth of the rows for testing. The models dict holds two pipelines, and each pipeline scales the features before the model runs. The loop fits each pipeline, predicts the test prices, and prints the RMSE. Random Forest scores 0.5059, and XGBoost wins with 0.4591. Both beat the Ridge baseline of 0.7456 from the snippets. In short, a house-price model is a regression model that turns rooms, income, and location into a price guess, and RMSE says how far the guess lands.
Note
The prices are in hundreds of thousands of dollars, so an RMSE of 0.46 means about $46,000.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which model wins the house-price capstone?