Sunday , November 29 2026
Beginner machine learning project: predict house prices with pandas and scikit-learn, compare Linear Regression and Random Forest, explain and predict.

House Price Prediction Project with Python (Beginner ML Project)

Updated: 28 November 2026Level: BeginnerReading time: about 14 minutespandas · scikit-learn · tested

In this beginner project you build a model that predicts house prices (in lakh rupees) from area, bedrooms, age and distance to the city centre. You will go through every step of a real ML project: data, exploration, training, evaluation and prediction.

What You Will Learn

  • Create and explore a dataset
  • Check which features relate to price
  • Train Linear Regression and Random Forest
  • Evaluate with MAE and R²
  • Explain the model and predict a new house

Prerequisites

Pandas and Linear Regression.

Step 1: The Data

Example
import numpy as np
import pandas as pd

rng = np.random.default_rng(7)
n = 500
df = pd.DataFrame({
    "area_sqft":   rng.integers(600, 3500, n),
    "bedrooms":    rng.integers(1, 6, n),
    "age_years":   rng.integers(0, 40, n),
    "distance_km": rng.uniform(1, 25, n).round(1),
})
df["price_lakh"] = (10 + 0.035*df.area_sqft + 4*df.bedrooms - 0.4*df.age_years
                    - 1.2*df.distance_km + rng.normal(0, 6, n)).round(1)
print(df.head())
Output
   area_sqft  bedrooms  age_years  distance_km  price_lakh
0       3340         2         39         11.9       106.4
1       2412         2         16         16.9        66.6
2       2584         4         11         13.2       100.1
3       3201         3         33          5.0       122.4
4       2277         2         18          4.3        83.2

Explanation: So that everyone gets the same results without downloading files, we generate a realistic dataset with a known pattern plus random noise. To use real data, replace this step with pd.read_csv("house_prices.csv") – for example a city housing dataset from Kaggle.

Step 2: Explore

Example
print(df.describe().loc[["mean", "min", "max"]].round(1))
print(df.corr()["price_lakh"].round(2))
Output
      area_sqft  bedrooms  age_years  distance_km  price_lakh
mean     2097.5       3.0       19.3         12.8        72.5
min       609.0       1.0        0.0          1.0         5.2
max      3497.0       5.0       39.0         25.0       158.0
area_sqft      0.91
bedrooms       0.20
age_years     -0.13
distance_km   -0.24
price_lakh     1.00

Explanation: Area has a strong positive correlation (0.91) with price; age and distance are negative – older and farther houses are cheaper. Correlation shows only straight-line relationships, so we still let the models decide.

Step 3: Train and Compare Two Models

Example
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error, r2_score

X = df.drop(columns="price_lakh")
y = df["price_lakh"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

for name, model in [("Linear Regression", LinearRegression()),
                    ("Random Forest", RandomForestRegressor(n_estimators=200, random_state=42))]:
    model.fit(X_train, y_train)
    pred = model.predict(X_test)
    print(f"{name:18s} MAE={mean_absolute_error(y_test, pred):.2f} lakh  R2={r2_score(y_test, pred):.3f}")
Output
Linear Regression  MAE=4.88 lakh  R2=0.966
Random Forest      MAE=6.21 lakh  R2=0.944

Explanation: MAE is the average error in lakh; R² is the share of price variation the model explains (1 = perfect). Linear Regression wins here because the true relationship is linear. On messy real data with non-linear effects, Random Forest or XGBoost often wins – always compare.

Step 4: Explain the Model

Example
lr = LinearRegression().fit(X_train, y_train)
for col, coef in zip(X.columns, lr.coef_):
    print(f"{col:12s} {coef:+.3f}")
print("intercept", round(lr.intercept_, 2))
Output
area_sqft    +0.035
bedrooms     +4.013
age_years    -0.433
distance_km  -1.217
intercept 11.43

Explanation: Each extra square foot adds about ₹3,500 (0.035 lakh), each bedroom about ₹4 lakh, each year of age removes about ₹0.43 lakh, and each km from the centre about ₹1.2 lakh. The model recovered the pattern hidden in the data.

Step 5: Predict a New House

Example
new = pd.DataFrame([{"area_sqft": 1500, "bedrooms": 3, "age_years": 5, "distance_km": 8.0}])
print("Predicted price:", round(lr.predict(new)[0], 1), "lakh")
Output
Predicted price: 63.8 lakh

Ideas to Extend

  • Add location (city or locality) with one-hot encoding.
  • Use cross-validation and tune the Random Forest with Grid Search.
  • Deploy it as an API with FastAPI and a simple web form.

All Projects

Projects: Beginner: House Price Prediction · Intermediate: Customer Segmentation · Advanced: PDF Question-Answering Assistant · End-to-End: Churn Prediction App · Industry Project Ideas · GitHub Portfolio Guide

Interview Questions

Q: MAE vs RMSE?
MAE is the average absolute error; RMSE squares errors first, so it punishes large errors more.

Q: Why compare with a simple model?
A simple model is a baseline; a complex model is only worth it if it clearly beats it.

Practice Exercises

  1. Add a “parking” (0/1) feature and see how the coefficients change.
  2. Try a real housing dataset and report MAE and R².

Summary

You created data, explored correlations, trained and compared two regressors, explained the coefficients and predicted a new house – the full beginner ML workflow.

Next: Customer Segmentation Project

About Machine Learning

Check Also

PDF Question Answering Assistant with RAG (Advanced AI Project)

Advanced project: build a PDF Q&A assistant with pypdf, ChromaDB, an LLM and Streamlit, with page citations.