I predicted house prices with 50 lines of Python — here's the code breakdown
People think machine learning requires thousands of lines of code. It doesn't.
Here's a real ML model in ~50 lines of Python:
# Step 1: Import libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_absolute_error, r2_score
from sklearn.datasets import fetch_california_housing
# Step 2: Load the data
data = fetch_california_housing(as_frame=True)
df = data.frame
# Step 3: Split features and target
X = df.drop("MedHouseVal", axis=1)
y = df["MedHouseVal"]
# Step 4: Train/test split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Step 5: Train the model
model = GradientBoostingRegressor(
n_estimators=200,
max_depth=4,
learning_rate=0.1,
random_state=42
)
model.fit(X_train, y_train)
# Step 6: Evaluate
predictions = model.predict(X_test)
mae = mean_absolute_error(y_test, predictions)
r2 = r2_score(y_test, predictions)
print(f"Mean Absolute Error: ${mae * 100_000:,.0f}")
print(f"R² Score: {r2:.3f}")
# Output: MAE ~$32,000, R² ~0.78Breaking it down:
Lines 1-4: Import the tools. Pandas for data, scikit-learn for ML.
Lines 7-8: Load a real housing dataset with 20,000+ California homes.
Lines 11-12: Separate the features (bedrooms, location, etc.) from what we're predicting (price).
Lines 15-17: Split data — 80% for training, 20% for testing.
Lines 20-25: Create and train a Gradient Boosting model. This is one of the most powerful algorithms for tabular data.
Lines 28-32: Test the model and measure accuracy.
The result?
This model predicts California house prices within ~$32,000 on average, with an R² score of 0.78 (meaning it explains 78% of price variation).
50 lines. No PhD required.
---
This is the exact type of project you build in Chapter 3 of our Python to AI Mastery course. We go from print("hello world") to this in 16 lessons.
👉 Join CodeMind AI — code LAUNCH = 20% off first 3 months.
