DEV Community

Mate Technologies
Mate Technologies

Posted on

🏠 Building an AI House Price Predictor with Python (Step‑by‑Step)

In this beginner‑friendly tutorial, we’ll build HousePrice Sentinel, a desktop application that predicts house prices using Machine Learning and a modern Python UI.

By the end, you will:

Understand how ML fits into a real project

Load and train a model from a CSV file

Build a clean desktop interface with Tkinter + ttkbootstrap

Make real‑time predictions

🧰 Tech Stack

Python 3.9+

Pandas & NumPy – data handling

Scikit‑Learn – machine learning

Tkinter – desktop UI

ttkbootstrap – modern styling

📁 Project Structure
HousePrice-Sentinel/
│── main.py
│── dataset.csv # sample dataset
│── logo.ico # optional app icon
1️⃣ Import Required Libraries

We start by importing everything we need. Don’t worry if this looks long — we’ll use each part step by step.

import os, sys, threading
import tkinter as tk
from tkinter import filedialog, messagebox


import pandas as pd
import numpy as np


import ttkbootstrap as tb
from ttkbootstrap.constants import *


from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
Enter fullscreen mode Exit fullscreen mode

Why these libraries?

tkinter → creates the desktop app

ttkbootstrap → makes the UI modern

pandas → loads CSV files

scikit‑learn → trains the ML model

2️⃣ Helper Function (Resource Loader)

This function helps your app find files correctly, even after packaging.

def resource_path(file_name):
    base_path = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, file_name)
Enter fullscreen mode Exit fullscreen mode

3️⃣ Creating the Machine Learning Worker

We isolate ML logic in its own class to keep the UI responsive.

class PriceModelWorker:
    def __init__(self, csv_path, callbacks):
        self.csv_path = csv_path
        self.callbacks = callbacks
        self.model = LinearRegression()
Enter fullscreen mode Exit fullscreen mode

Loading & Training the Model

    def run(self):
        df = pd.read_csv(self.csv_path)


        X = df[["Area", "Bedrooms", "Bathrooms"]]
        y = df["Price"]


        X_train, X_test, y_train, y_test = train_test_split(
            X, y, test_size=0.2, random_state=42
        )


        self.model.fit(X_train, y_train)
        score = self.model.score(X_test, y_test)


        self.callbacks["trained"](score, self.model)
Enter fullscreen mode Exit fullscreen mode

What’s happening here?

Load CSV data

Split into training & testing sets

Train a Linear Regression model

Send results back to the UI

4️⃣ Creating the Main Application Window

class HousePriceApp:
    APP_NAME = "HousePrice Sentinel"
    APP_VERSION = "1.0"


    def __init__(self):
        self.root = tb.Window(themename="darkly")
        self.root.title(f"{self.APP_NAME} v{self.APP_VERSION}")
        self.root.minsize(1100, 650)
        self.model = None
        self._build_ui()
Enter fullscreen mode Exit fullscreen mode

We use ttkbootstrap’s dark theme for a professional look.

5️⃣ Building the User Interface
App Title

tb.Label(
    main,
    text="🏠 HousePrice Sentinel",
    font=("Segoe UI", 22, "bold")
).pack()
Enter fullscreen mode Exit fullscreen mode

Dataset Loader

self.dataset_entry = tb.Entry(row1, width=90)
self.dataset_entry.pack(side=LEFT, fill=X, expand=True)


tb.Button(
    row1,
    text="📂 Load Dataset",
    bootstyle=INFO,
    command=self.load_dataset
).pack(side=LEFT)

Enter fullscreen mode Exit fullscreen mode

This lets users browse and select a CSV file.

6️⃣ Training the Model (Background Thread)

def train_model(self):
    threading.Thread(
        target=self._train_worker,
        daemon=True
    ).start()
Enter fullscreen mode Exit fullscreen mode

Why threading?

Training can take time. Threads prevent the UI from freezing.

7️⃣ Prediction Input Form

self.area_var = tk.DoubleVar()
self.bed_var = tk.IntVar()
self.bath_var = tk.IntVar()
tb.Entry(form, textvariable=self.area_var).grid(row=0, column=1)
tb.Entry(form, textvariable=self.bed_var).grid(row=0, column=3)
tb.Entry(form, textvariable=self.bath_var).grid(row=0, column=5)
Enter fullscreen mode Exit fullscreen mode

Users enter house details here.

8️⃣ Predicting the House Price

def predict_price(self):
    X = pd.DataFrame([{
        "Area": self.area_var.get(),
        "Bedrooms": self.bed_var.get(),
        "Bathrooms": self.bath_var.get()
    }])


    price = self.model.predict(X)[0]
    self.result_label.config(text=f"Predicted Price: ${price:,.2f}")
Enter fullscreen mode Exit fullscreen mode

The trained model instantly returns a price.

9️⃣ About Dialog

messagebox.showinfo(
    "About",
    "AI-powered house price prediction tool built with Python"
)
Enter fullscreen mode Exit fullscreen mode

🔟 Running the App

if __name__ == "__main__":
    app = HousePriceApp()
    app.run()
Enter fullscreen mode Exit fullscreen mode

🎉 Final Result

You now have:

A working ML desktop app

CSV‑based training

Real‑time predictions

Clean enterprise UI

🔗 Source Code

GitHub Repository: https://github.com/rogers-cyber/python-tiny-tools/tree/main/HousePrice-Sentinel

🚀 What to Build Next?

Add more features (location, year built)

Save trained models

Export predictions

Convert to an EXE

Happy coding! 🧠🐍

Top comments (0)