Machine Learning project 08
Machine Learning House Price Prediction Project
Build and evaluate a complete house price prediction 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 dataset with numeric property attributes and a generated neighbourhood-value feature.
Skills practised
- Nonlinear regression
- Gradient boosting
- Median baselines
- Holdout metrics
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
- Data: A reproducible synthetic housing dataset with numeric property attributes and a generated neighbourhood-value feature.
- Preprocessing: A fixed seed creates repeatable data, followed by a random training/holdout split for this non-temporal demonstration.
- Model: HistGradientBoostingRegressor captures nonlinear area and location effects without requiring feature scaling.
- Evaluation: Holdout MAE and R-squared, compared with a median-training-price baseline.
Complete Python code
Save the code as ml_house_price_prediction.py. The random state and data handling are included so the result can be reproduced and reviewed.
"""Predict California district house values with gradient boosting."""
from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
def make_demo_housing(rows: int = 4000, random_state: int = 42):
rng = np.random.default_rng(random_state)
area_sqft = rng.uniform(450, 3500, rows)
bedrooms = rng.integers(1, 7, rows)
age_years = rng.integers(0, 51, rows)
distance_km = rng.uniform(0.5, 40, rows)
neighbourhood = rng.choice(["central", "suburban", "outer"], rows, p=[0.25, 0.5, 0.25])
location_value = pd.Series(neighbourhood).map({"central": 38, "suburban": 16, "outer": 0}).to_numpy()
price_lakh = (
10
+ 0.032 * area_sqft
+ 2.5 * bedrooms
- 0.25 * age_years
- 0.55 * distance_km
+ location_value
+ 0.000004 * area_sqft**2
+ rng.normal(0, 9, rows)
)
features = pd.DataFrame({
"area_sqft": area_sqft,
"bedrooms": bedrooms,
"age_years": age_years,
"distance_km": distance_km,
"neighbourhood_value": location_value,
})
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 = HistGradientBoostingRegressor(
learning_rate=0.08,
max_iter=250,
max_leaf_nodes=31,
l2_regularization=0.1,
random_state=random_state,
)
model.fit(x_train, y_train)
predictions = model.predict(x_test)
baseline = [y_train.median()] * len(y_test)
metrics = {
"mae": mean_absolute_error(y_test, predictions),
"r2": r2_score(y_test, predictions),
"baseline_mae": mean_absolute_error(y_test, baseline),
}
return model, features, metrics
def main() -> None:
_, features, metrics = train_model()
print("Synthetic Housing Gradient-Boosting Model")
print(f"Rows: {len(features):,}")
print(f"Model MAE: {metrics['mae']:.2f} lakh")
print(f"Median baseline MAE: {metrics['baseline_mae']:.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 seed creates repeatable data, followed by a random training/holdout split for this non-temporal demonstration.
HistGradientBoostingRegressor captures nonlinear area and location effects without requiring feature scaling. Holdout MAE and R-squared, compared with a median-training-price baseline.
Run the project
- Create and activate a virtual environment.
- Install the dependencies with
python -m pip install numpy pandas scikit-learn. - Run
python ml_house_price_prediction.py. - 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
Synthetic prices do not represent any real property, locality, currency market, legal valuation, appraisal, or lending decision.
Ways to extend the project
Add cross-validation, tune tree complexity, analyse residuals, use time-aware local transactions, and document geographic coverage and data age.
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.