Machine Learning Linear Regression on Housing Data Project

Machine Learning project 01

Machine Learning Linear Regression on Housing Data Project

Build and evaluate a complete linear regression on housing data workflow with reproducible Python code, explicit metrics, and honest limitations.

Explore Machine Learning training in VizagView all project ideas

Dataset and objective

A reproducible synthetic housing table with area, bedrooms, age, distance, and a price target measured in INR lakh.

Skills practised

  • Regression targets
  • Train/test splitting
  • Scaling pipelines
  • MAE, RMSE, and R-squared

Requirements

  • Python 3.10 or later
  • A terminal or command prompt
  • python -m pip install numpy pandas scikit-learn
  • About 45-60 minutes to build and review

Machine Learning workflow

  1. Data: A reproducible synthetic housing table with area, bedrooms, age, distance, and a price target measured in INR lakh.
  2. Preprocessing: A fixed random seed creates repeatable rows. The data is split into training and holdout sets, and StandardScaler is fitted only inside the training pipeline.
  3. Model: LinearRegression provides an interpretable baseline for approximately linear relationships.
  4. Evaluation: MAE, RMSE, and R-squared on an untouched 20% holdout set.

Complete Python code

Save the code as ml_linear_regression_housing.py. The random state and data handling are included so the result can be reproduced and reviewed.

"""Evaluate linear regression on the California housing dataset."""

from __future__ import annotations

from math import sqrt

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler


def make_demo_housing(rows: int = 3000, random_state: int = 42):
    rng = np.random.default_rng(random_state)
    area_sqft = rng.uniform(450, 3200, rows)
    bedrooms = rng.integers(1, 6, rows)
    age_years = rng.integers(0, 41, rows)
    distance_km = rng.uniform(0.5, 35, rows)
    price_lakh = (
        9
        + 0.038 * area_sqft
        + 3.0 * bedrooms
        - 0.32 * age_years
        - 0.85 * distance_km
        + rng.normal(0, 8, rows)
    )
    features = pd.DataFrame({
        "area_sqft": area_sqft,
        "bedrooms": bedrooms,
        "age_years": age_years,
        "distance_km": distance_km,
    })
    return features, pd.Series(price_lakh, name="price_lakh")


def train_model(random_state: int = 42):
    features, target = make_demo_housing(random_state=random_state)
    x_train, x_test, y_train, y_test = train_test_split(
        features, target, test_size=0.2, random_state=random_state
    )
    model = make_pipeline(StandardScaler(), LinearRegression())
    model.fit(x_train, y_train)
    predictions = model.predict(x_test)
    metrics = {
        "mae": mean_absolute_error(y_test, predictions),
        "rmse": sqrt(mean_squared_error(y_test, predictions)),
        "r2": r2_score(y_test, predictions),
    }
    return model, metrics, features


def main() -> None:
    _, metrics, features = train_model()
    print("Synthetic Housing Linear Regression")
    print(f"Rows: {len(features):,} | Features: {features.shape[1]}")
    print("Target unit: synthetic INR lakh")
    print(f"MAE:  {metrics['mae']:.2f} lakh")
    print(f"RMSE: {metrics['rmse']:.2f} lakh")
    print(f"R-squared: {metrics['r2']:.3f}")
    print("Reproducible education only; synthetic results are not a property valuation.")


if __name__ == "__main__":
    main()

How the pipeline works

A fixed random seed creates repeatable rows. The data is split into training and holdout sets, and StandardScaler is fitted only inside the training pipeline.

LinearRegression provides an interpretable baseline for approximately linear relationships. MAE, RMSE, and R-squared on an untouched 20% holdout set.

Run the project

  1. Create and activate a virtual environment.
  2. Install the dependencies with python -m pip install numpy pandas scikit-learn.
  3. Run python ml_linear_regression_housing.py.
  4. Review every printed metric together with the limitation below; a single score never proves deployment readiness.

How to interpret the evaluation

Classification projects report class-aware metrics so majority classes do not hide weak performance. Regression projects report errors in target units and include R-squared or a simple baseline where appropriate. Always verify the split strategy matches how new data will arrive.

Accuracy, ethics, and safety limits

The data and prices are synthetic. The result is a modelling demonstration, not a property valuation or statement about a real neighbourhood.

Ways to extend the project

Inspect coefficients, add cross-validation, compare Ridge and Lasso, introduce nonlinear features, or replace the generator with a licensed local housing dataset.

Continue learning Machine Learning

Try the next project, return to the Softenant project library, or explore the Machine Learning course in Vizag for guided data preparation, model evaluation, and portfolio feedback.