Skip to content

Repository files navigation

Linear Regression House Price Predictor

Tests

A small full-stack demo that predicts house prices from size, bedroom count, and distance from the city center, using a scikit-learn linear regression model served through a FastAPI backend and a plain HTML/JS frontend.

image

Features

  • FastAPI backend with a single /predict endpoint
  • Linear regression model (scikit-learn) trained on a small sample housing dataset
  • Static frontend (HTML + vanilla JS) served directly by FastAPI
  • Basic test coverage with pytest / FastAPI's TestClient
  • CORS enabled for all origins (useful for local development)

Project Structure

.
├── main.py            # FastAPI app: serves the frontend and the /predict endpoint
├── train_model.py      # Trains the linear regression model and saves model.pkl
├── test_model.py       # Tests for the model and the API
├── model.pkl           # Trained model (generated by train_model.py)
├── index.html           # Frontend UI
└── static/
    └── index.css         # Frontend styling

Requirements

  • Python 3.9+
  • fastapi
  • uvicorn
  • scikit-learn
  • joblib
  • pydantic
  • pytest (for running tests)

Install dependencies:

pip install fastapi uvicorn scikit-learn joblib pytest

Setup

  1. Train the model (generates model.pkl):

    python train_model.py
  2. Run the API server:

    uvicorn main:app --reload
  3. Open the app in your browser:

    http://localhost:8000
    

API Usage

POST /predict

Predicts a house price given size, bedrooms, and distance from the city.

Request body:

{
  "size": 100,
  "bedrooms": 3,
  "distance": 5
}

Response:

{
  "prediction": 320000.0
}

GET /

Serves the frontend (index.html).

Testing

Run the test suite with:

pytest

Tests cover:

  • That the model produces a positive price prediction for valid input
  • That the API returns a 422 Unprocessable Entity for invalid input

Model Details

The model is a LinearRegression from scikit-learn, trained on a small hardcoded dataset of six houses with three features:

Feature Description
size Property size in m²
bedrooms Number of bedrooms
distance Distance from city center (km)

This is a toy dataset for demonstration purposes only — with just six training examples, the model is not suitable for real-world price predictions. Replace X and y in train_model.py with a larger, real dataset before using this for anything meaningful.

Known Limitations / Ideas for Improvement

  • CORS is wide open (allow_origins=["*"]) — restrict this before deploying anywhere public
  • No input validation beyond basic type checking (e.g. negative sizes/bedrooms are accepted)
  • Training dataset is tiny and hardcoded — consider loading from a CSV or database
  • No persistence/versioning of trained models beyond overwriting model.pkl

License

MIT

About

FastAPI & Linear Regression example with Front end

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages