Spaces:
No application file
No application file
Upload 7 files
Browse files- app.py +223 -0
- charts.py +18 -0
- data_utils.py +93 -0
- llm_chat.py +91 -0
- ml_price_prediction.py +375 -0
- plan_executor.py +59 -0
- predictor.py +50 -0
app.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Dashboard entry — UK Housing + Falcon Chat (Python ≤3.9)
|
| 3 |
+
Run: python dashboard.py
|
| 4 |
+
|
| 5 |
+
ENV (optional):
|
| 6 |
+
FALCON_MODEL=tiiuae/falcon-1b-instruct # default; swap to 7B on GPU
|
| 7 |
+
DEVICE_MAP=cpu # set to "auto" on Spaces GPU
|
| 8 |
+
MAX_NEW_TOKENS=320
|
| 9 |
+
PORT=8050
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import os
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
|
| 15 |
+
import dash
|
| 16 |
+
from dash import dcc, html, Input, Output, State
|
| 17 |
+
import dash_bootstrap_components as dbc
|
| 18 |
+
from dash import dash_table
|
| 19 |
+
import plotly.express as px
|
| 20 |
+
|
| 21 |
+
import pandas as pd
|
| 22 |
+
|
| 23 |
+
from data_utils import load_raw_data, enrich_data
|
| 24 |
+
from predictor import predict_price
|
| 25 |
+
from charts import build_trend, build_distribution, build_city_bar, build_type_pie
|
| 26 |
+
from llm_chat import plan_from_question, explain_answer
|
| 27 |
+
from plan_executor import execute_plan
|
| 28 |
+
|
| 29 |
+
# ---------- Data ----------
|
| 30 |
+
RAW = load_raw_data()
|
| 31 |
+
df = enrich_data(RAW)
|
| 32 |
+
|
| 33 |
+
# ---------- Dash ----------
|
| 34 |
+
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
|
| 35 |
+
server = app.server
|
| 36 |
+
|
| 37 |
+
# ===== Top: LLM Chat =====
|
| 38 |
+
chat_card = dbc.Card([
|
| 39 |
+
dbc.CardHeader(html.H4("💬 Ask the Data (Falcon)")),
|
| 40 |
+
dbc.CardBody([
|
| 41 |
+
dbc.Row([
|
| 42 |
+
dbc.Col(dcc.Textarea(
|
| 43 |
+
id="chat-question",
|
| 44 |
+
placeholder="Ask anything about the dataset (e.g., 'Aside from London, with a £500k budget what can I afford?')",
|
| 45 |
+
style={"width": "100%", "height": "90px"}
|
| 46 |
+
), md=9),
|
| 47 |
+
dbc.Col([
|
| 48 |
+
html.Label("Rows limit"),
|
| 49 |
+
dcc.Input(id="rows-limit", type="number", value=10, min=1, max=50, style={"width": "100%"}),
|
| 50 |
+
dbc.Button("Ask", id="ask-btn", color="primary", className="mt-3 w-100"),
|
| 51 |
+
], md=3),
|
| 52 |
+
], className="gy-2"),
|
| 53 |
+
html.Div(id="chat-answer", className="mt-3"),
|
| 54 |
+
dash_table.DataTable(id="chat-table", page_size=10, style_table={"overflowX": "auto"}),
|
| 55 |
+
])
|
| 56 |
+
], className="mb-4 shadow-sm")
|
| 57 |
+
|
| 58 |
+
# ===== Predictor =====
|
| 59 |
+
predictor_card = dbc.Card([
|
| 60 |
+
dbc.CardHeader(html.H4("🔮 Price Prediction Tool")),
|
| 61 |
+
dbc.CardBody([
|
| 62 |
+
dbc.Row([
|
| 63 |
+
dbc.Col([dbc.Label("Square Footage"), dbc.Input(id="sqft-in", type="number", value=1200)], width=3),
|
| 64 |
+
dbc.Col([dbc.Label("Bedrooms"), dbc.Input(id="beds-in", type="number", value=3)], width=3),
|
| 65 |
+
dbc.Col([dbc.Label("Bathrooms"), dbc.Input(id="baths-in", type="number", value=2)], width=3),
|
| 66 |
+
dbc.Col([dbc.Label("Year Built"), dbc.Input(id="year-in", type="number", value=2005)], width=3),
|
| 67 |
+
], className="gy-2"),
|
| 68 |
+
dbc.Row([
|
| 69 |
+
dbc.Col([dbc.Label("City"), dcc.Dropdown(
|
| 70 |
+
id="city-dd",
|
| 71 |
+
options=[{"label": c, "value": c} for c in sorted(df["Location_City"].dropna().unique())],
|
| 72 |
+
value="London")], width=3),
|
| 73 |
+
dbc.Col([dbc.Label("Property Type"), dcc.Dropdown(
|
| 74 |
+
id="type-dd",
|
| 75 |
+
options=[{"label": p, "value": p} for p in sorted(df["Property_Type"].dropna().unique())],
|
| 76 |
+
value="Detached House")], width=3),
|
| 77 |
+
dbc.Col([dbc.Label("Quality (1–10)"), dcc.Slider(
|
| 78 |
+
id="quality-in", min=1, max=10, step=1, value=7,
|
| 79 |
+
marks={i: str(i) for i in range(1, 11)})], width=6),
|
| 80 |
+
]),
|
| 81 |
+
dbc.Button("Predict Price", id="predict-btn", color="primary", className="mt-3"),
|
| 82 |
+
html.Div(id="prediction-output", className="h5 mt-3"),
|
| 83 |
+
])
|
| 84 |
+
], className="mb-4 shadow-sm")
|
| 85 |
+
|
| 86 |
+
# ===== Summary Cards =====
|
| 87 |
+
summary_cards = dbc.Row([
|
| 88 |
+
dbc.Col(dbc.Card(dbc.CardBody([html.H4(f"{len(df):,}", className="card-title text-primary"), html.P("Total Properties")])), width=3),
|
| 89 |
+
dbc.Col(dbc.Card(dbc.CardBody([html.H4(f"£{df['Sale_Price_GBP'].mean():,.0f}", className="card-title text-success"), html.P("Average Price")])), width=3),
|
| 90 |
+
dbc.Col(dbc.Card(dbc.CardBody([html.H4(f"{df['Location_City'].nunique()}", className="card-title text-info"), html.P("Cities")])), width=3),
|
| 91 |
+
dbc.Col(dbc.Card(dbc.CardBody([html.H4(f"{df['Property_Type'].nunique()}", className="card-title text-warning"), html.P("Property Types")])), width=3),
|
| 92 |
+
], className="mb-4")
|
| 93 |
+
|
| 94 |
+
# ===== Filters =====
|
| 95 |
+
filters_row = dbc.Row([
|
| 96 |
+
dbc.Col([html.Label("Select City:"), dcc.Dropdown(
|
| 97 |
+
id="city-filter",
|
| 98 |
+
options=[{"label": c, "value": c} for c in sorted(df["Location_City"].dropna().unique())],
|
| 99 |
+
multi=True)], width=3),
|
| 100 |
+
dbc.Col([html.Label("Property Type:"), dcc.Dropdown(
|
| 101 |
+
id="type-filter",
|
| 102 |
+
options=[{"label": p, "value": p} for p in sorted(df["Property_Type"].dropna().unique())],
|
| 103 |
+
multi=True)], width=3),
|
| 104 |
+
dbc.Col([html.Label("Year Range:"), dcc.RangeSlider(
|
| 105 |
+
id="year-range",
|
| 106 |
+
min=int(df["Year"].min()), max=int(df["Year"].max()),
|
| 107 |
+
value=[int(df["Year"].min()), int(df["Year"].max())],
|
| 108 |
+
marks={str(y): str(y) for y in range(int(df["Year"].min()), int(df["Year"].max()) + 1, 2)},
|
| 109 |
+
step=1)], width=6),
|
| 110 |
+
], className="mb-4")
|
| 111 |
+
|
| 112 |
+
# ===== Charts =====
|
| 113 |
+
charts_row_1 = dbc.Row([
|
| 114 |
+
dbc.Col(dcc.Graph(id="price-trend-chart"), width=6),
|
| 115 |
+
dbc.Col(dcc.Graph(id="price-distribution-chart"), width=6),
|
| 116 |
+
], className="mb-4")
|
| 117 |
+
|
| 118 |
+
charts_row_2 = dbc.Row([
|
| 119 |
+
dbc.Col(dcc.Graph(id="city-comparison-chart"), width=6),
|
| 120 |
+
dbc.Col(dcc.Graph(id="property-type-chart"), width=6),
|
| 121 |
+
], className="mb-4")
|
| 122 |
+
|
| 123 |
+
# ===== Layout =====
|
| 124 |
+
app.layout = dbc.Container([
|
| 125 |
+
html.H2("🏠 UK Housing Market Analysis", className="mt-3 mb-2 text-center"),
|
| 126 |
+
chat_card,
|
| 127 |
+
predictor_card,
|
| 128 |
+
summary_cards,
|
| 129 |
+
filters_row,
|
| 130 |
+
charts_row_1,
|
| 131 |
+
charts_row_2,
|
| 132 |
+
], fluid=True)
|
| 133 |
+
|
| 134 |
+
# ---------- Callbacks: Charts ----------
|
| 135 |
+
@app.callback(
|
| 136 |
+
[Output("price-trend-chart", "figure"),
|
| 137 |
+
Output("price-distribution-chart", "figure"),
|
| 138 |
+
Output("city-comparison-chart", "figure"),
|
| 139 |
+
Output("property-type-chart", "figure")],
|
| 140 |
+
[Input("city-filter", "value"),
|
| 141 |
+
Input("type-filter", "value"),
|
| 142 |
+
Input("year-range", "value")]
|
| 143 |
+
)
|
| 144 |
+
def update_charts(city_filter, type_filter, year_range):
|
| 145 |
+
filtered = df.copy()
|
| 146 |
+
if city_filter:
|
| 147 |
+
filtered = filtered[filtered["Location_City"].isin(city_filter)]
|
| 148 |
+
if type_filter:
|
| 149 |
+
filtered = filtered[filtered["Property_Type"].isin(type_filter)]
|
| 150 |
+
if year_range:
|
| 151 |
+
filtered = filtered[(filtered["Year"] >= year_range[0]) & (filtered["Year"] <= year_range[1])]
|
| 152 |
+
|
| 153 |
+
return (
|
| 154 |
+
build_trend(filtered),
|
| 155 |
+
build_distribution(filtered),
|
| 156 |
+
build_city_bar(filtered),
|
| 157 |
+
build_type_pie(filtered),
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# ---------- Callback: Predictor ----------
|
| 161 |
+
@app.callback(
|
| 162 |
+
Output("prediction-output", "children"),
|
| 163 |
+
Input("predict-btn", "n_clicks"),
|
| 164 |
+
State("sqft-in", "value"),
|
| 165 |
+
State("beds-in", "value"),
|
| 166 |
+
State("baths-in", "value"),
|
| 167 |
+
State("year-in", "value"),
|
| 168 |
+
State("quality-in", "value"),
|
| 169 |
+
State("city-dd", "value"),
|
| 170 |
+
State("type-dd", "value"),
|
| 171 |
+
prevent_initial_call=True
|
| 172 |
+
)
|
| 173 |
+
def on_predict(n, sqft, beds, baths, year_built, quality, city, prop_type):
|
| 174 |
+
price, used_model = predict_price(
|
| 175 |
+
float(sqft or 0), int(beds or 0), int(baths or 0),
|
| 176 |
+
int(year_built or datetime.now().year), int(quality or 6),
|
| 177 |
+
city or "London", prop_type or "Townhouse"
|
| 178 |
+
)
|
| 179 |
+
note = "Predicted using trained model." if used_model else "Estimated using fallback."
|
| 180 |
+
return f"£{price:,.0f} ({note})"
|
| 181 |
+
|
| 182 |
+
# ---------- Callback: LLM Chat ----------
|
| 183 |
+
@app.callback(
|
| 184 |
+
[Output("chat-answer", "children"),
|
| 185 |
+
Output("chat-table", "data"),
|
| 186 |
+
Output("chat-table", "columns")],
|
| 187 |
+
Input("ask-btn", "n_clicks"),
|
| 188 |
+
State("chat-question", "value"),
|
| 189 |
+
State("rows-limit", "value"),
|
| 190 |
+
prevent_initial_call=True
|
| 191 |
+
)
|
| 192 |
+
def on_ask(n_clicks, question, limit):
|
| 193 |
+
if not question or not str(question).strip():
|
| 194 |
+
return "Please enter a question.", [], []
|
| 195 |
+
|
| 196 |
+
plan = plan_from_question(question, df)
|
| 197 |
+
if limit:
|
| 198 |
+
try:
|
| 199 |
+
plan["limit"] = int(limit)
|
| 200 |
+
except Exception:
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
try:
|
| 204 |
+
result = execute_plan(df, plan)
|
| 205 |
+
except Exception as e:
|
| 206 |
+
return f"Sorry, I couldn't compute that: {e}", [], []
|
| 207 |
+
|
| 208 |
+
try:
|
| 209 |
+
answer = explain_answer(question, result)
|
| 210 |
+
except Exception:
|
| 211 |
+
answer = "Here are the results based on your query."
|
| 212 |
+
|
| 213 |
+
cols = [{"name": c, "id": c} for c in result.columns]
|
| 214 |
+
data = result.to_dict("records")
|
| 215 |
+
return answer, data, cols
|
| 216 |
+
|
| 217 |
+
# ---------- Main ----------
|
| 218 |
+
if __name__ == "__main__":
|
| 219 |
+
port = int(os.environ.get("PORT", 8050))
|
| 220 |
+
app.run(host="0.0.0.0", port=port, debug=False)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
|
charts.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import plotly.express as px
|
| 2 |
+
import pandas as pd
|
| 3 |
+
|
| 4 |
+
def build_trend(filtered: pd.DataFrame):
|
| 5 |
+
yearly = filtered.groupby("Year")["Sale_Price_GBP"].mean().reset_index()
|
| 6 |
+
return px.line(yearly, x="Year", y="Sale_Price_GBP", title="Average Prices Over Time")
|
| 7 |
+
|
| 8 |
+
def build_distribution(filtered: pd.DataFrame):
|
| 9 |
+
return px.histogram(filtered, x="Sale_Price_GBP", nbins=50, title="Price Distribution")
|
| 10 |
+
|
| 11 |
+
def build_city_bar(filtered: pd.DataFrame):
|
| 12 |
+
city_stats = filtered.groupby("Location_City")["Sale_Price_GBP"].mean().reset_index()
|
| 13 |
+
return px.bar(city_stats, x="Location_City", y="Sale_Price_GBP", title="Average Price by City")
|
| 14 |
+
|
| 15 |
+
def build_type_pie(filtered: pd.DataFrame):
|
| 16 |
+
type_stats = filtered["Property_Type"].value_counts().reset_index()
|
| 17 |
+
type_stats.columns = ["Property_Type", "count"]
|
| 18 |
+
return px.pie(type_stats, values="count", names="Property_Type", title="Property Type Distribution")
|
data_utils.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from typing import Optional
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
DATA_CANDIDATES = [
|
| 8 |
+
"data/uk_real_estate_dataset_with_revenue (1).csv",
|
| 9 |
+
"data/uk_real_estate_dataset_with_revenue.csv",
|
| 10 |
+
"data/uk_real_estate_dataset.csv",
|
| 11 |
+
"uk_real_estate_dataset_with_revenue (1).csv",
|
| 12 |
+
"uk_real_estate_dataset.csv",
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
CENTRAL_DISTRICTS = {
|
| 16 |
+
"Kensington","Chelsea","Islington","Camden","Hackney","Westminster",
|
| 17 |
+
"Southwark","Lambeth","Hammersmith","Fulham","Tower Hamlets","Brixton","Shoreditch"
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
def _find_data_file() -> Optional[Path]:
|
| 21 |
+
for p in DATA_CANDIDATES:
|
| 22 |
+
path = Path(p)
|
| 23 |
+
if path.exists():
|
| 24 |
+
return path
|
| 25 |
+
return None
|
| 26 |
+
|
| 27 |
+
def load_raw_data() -> pd.DataFrame:
|
| 28 |
+
path = _find_data_file()
|
| 29 |
+
if path is None:
|
| 30 |
+
now_year = datetime.now().year
|
| 31 |
+
return pd.DataFrame({
|
| 32 |
+
"Property_ID": list(range(1, 6)),
|
| 33 |
+
"Sale_Price_GBP": [500000, 650000, 825000, 1200000, 430000],
|
| 34 |
+
"Square_Footage": [950, 1200, 1600, 2200, 800],
|
| 35 |
+
"Bedrooms": [2, 3, 3, 4, 2],
|
| 36 |
+
"Bathrooms": [1, 2, 2, 3, 1],
|
| 37 |
+
"Year_Built": [1998, 2005, 2012, 1980, 2018],
|
| 38 |
+
"Quality_Score": [6, 7, 8, 7, 6],
|
| 39 |
+
"Location_City": ["London","London","Manchester","London","Bristol"],
|
| 40 |
+
"Location_District": ["Islington","Camden","Didsbury","Kensington","Clifton"],
|
| 41 |
+
"Property_Type": ["Townhouse","Detached House","Detached House","Townhouse","Townhouse"],
|
| 42 |
+
"Sale_Date": pd.date_range(str(now_year-1) + "-01-01", periods=5, freq="90D"),
|
| 43 |
+
})
|
| 44 |
+
|
| 45 |
+
df = pd.read_csv(path)
|
| 46 |
+
if "Sale_Date" in df.columns:
|
| 47 |
+
df["Sale_Date"] = pd.to_datetime(df["Sale_Date"], errors="coerce")
|
| 48 |
+
dt = df["Sale_Date"]
|
| 49 |
+
elif "Listing_Date" in df.columns:
|
| 50 |
+
df["Listing_Date"] = pd.to_datetime(df["Listing_Date"], errors="coerce")
|
| 51 |
+
dt = df["Listing_Date"]
|
| 52 |
+
else:
|
| 53 |
+
dt = None
|
| 54 |
+
|
| 55 |
+
if dt is not None:
|
| 56 |
+
df["Year"] = dt.dt.year
|
| 57 |
+
else:
|
| 58 |
+
df["Year"] = datetime.now().year
|
| 59 |
+
|
| 60 |
+
return df
|
| 61 |
+
|
| 62 |
+
def enrich_data(df: pd.DataFrame) -> pd.DataFrame:
|
| 63 |
+
df = df.copy()
|
| 64 |
+
now_year = datetime.now().year
|
| 65 |
+
|
| 66 |
+
for col, default in [
|
| 67 |
+
("Square_Footage", np.nan),
|
| 68 |
+
("Bedrooms", 0),
|
| 69 |
+
("Bathrooms", 0),
|
| 70 |
+
("Year_Built", now_year),
|
| 71 |
+
("Quality_Score", 6),
|
| 72 |
+
("Location_City", "London"),
|
| 73 |
+
("Location_District", "Westminster"),
|
| 74 |
+
("Property_Type", "Townhouse"),
|
| 75 |
+
("Sale_Price_GBP", np.nan),
|
| 76 |
+
]:
|
| 77 |
+
if col not in df.columns:
|
| 78 |
+
df[col] = default
|
| 79 |
+
|
| 80 |
+
df["Price_Per_Sqft"] = df["Sale_Price_GBP"] / df["Square_Footage"].replace(0, np.nan)
|
| 81 |
+
df["Price_Per_Sqft"] = df["Price_Per_Sqft"].fillna(df["Price_Per_Sqft"].median())
|
| 82 |
+
|
| 83 |
+
df["Property_Age"] = (df["Year"] - df["Year_Built"]).clip(lower=0)
|
| 84 |
+
df["Total_Rooms"] = (df["Bedrooms"] + df["Bathrooms"]).replace(0, np.nan).fillna(1)
|
| 85 |
+
df["Size_Per_Room"] = df["Square_Footage"] / df["Total_Rooms"]
|
| 86 |
+
|
| 87 |
+
df["Is_London"] = (df["Location_City"].astype(str) == "London").astype(int)
|
| 88 |
+
df["Is_Central_London"] = df["Location_District"].isin(CENTRAL_DISTRICTS).astype(int)
|
| 89 |
+
|
| 90 |
+
df["Is_Detached"] = (df["Property_Type"] == "Detached House").astype(int)
|
| 91 |
+
df["Is_Townhouse"] = (df["Property_Type"] == "Townhouse").astype(int)
|
| 92 |
+
|
| 93 |
+
return df
|
llm_chat.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, re, json
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 4 |
+
|
| 5 |
+
MODEL_ID = os.environ.get("FALCON_MODEL", "tiiuae/Falcon-H1-0.5B-Instruct")
|
| 6 |
+
DEVICE_MAP = os.environ.get("DEVICE_MAP", "cpu") # set "auto" on GPU Spaces
|
| 7 |
+
MAX_NEW_TOKENS = int(os.environ.get("MAX_NEW_TOKENS", "320"))
|
| 8 |
+
|
| 9 |
+
_tok = None
|
| 10 |
+
_model = None
|
| 11 |
+
_llm = None
|
| 12 |
+
|
| 13 |
+
def _get_llm():
|
| 14 |
+
"""Lazy-load Falcon on first use so the Dash UI can start immediately."""
|
| 15 |
+
global _tok, _model, _llm
|
| 16 |
+
if _llm is None:
|
| 17 |
+
print(f">>> Loading Falcon model: {MODEL_ID} (device_map={DEVICE_MAP})")
|
| 18 |
+
_tok = AutoTokenizer.from_pretrained(MODEL_ID, use_fast=True)
|
| 19 |
+
_model = AutoModelForCausalLM.from_pretrained(MODEL_ID, torch_dtype=None, device_map=DEVICE_MAP)
|
| 20 |
+
_llm = pipeline(
|
| 21 |
+
"text-generation",
|
| 22 |
+
model=_model,
|
| 23 |
+
tokenizer=_tok,
|
| 24 |
+
do_sample=False,
|
| 25 |
+
temperature=0.0,
|
| 26 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
| 27 |
+
pad_token_id=_tok.eos_token_id,
|
| 28 |
+
return_full_text=False,
|
| 29 |
+
)
|
| 30 |
+
print(">>> Falcon ready.")
|
| 31 |
+
return _llm
|
| 32 |
+
|
| 33 |
+
SYSTEM_PLANNER = (
|
| 34 |
+
"You translate user questions about a housing CSV into a STRICT JSON plan.\n"
|
| 35 |
+
"Allowed keys: task, filters, groupby, metrics, sort_by, limit.\n"
|
| 36 |
+
"Filters support eq, in, not_in, gte, lte. Metrics: mean, median, count.\n"
|
| 37 |
+
"Only use known columns and metrics. No code. Respond with JSON only."
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
def _schema_from_df(df: pd.DataFrame):
|
| 41 |
+
cols = list(df.columns)
|
| 42 |
+
categoricals = [c for c in ["Location_City", "Property_Type", "Location_District"] if c in df.columns]
|
| 43 |
+
numerics = [c for c in ["Sale_Price_GBP", "Square_Footage", "Bedrooms", "Bathrooms", "Year", "Price_Per_Sqft"] if c in df.columns]
|
| 44 |
+
return cols, categoricals, numerics
|
| 45 |
+
|
| 46 |
+
def plan_from_question(question: str, df: pd.DataFrame) -> dict:
|
| 47 |
+
llm = _get_llm()
|
| 48 |
+
cols, cats, nums = _schema_from_df(df)
|
| 49 |
+
fewshot = (
|
| 50 |
+
"Columns: %s\nCategoricals: %s\nNumerics: %s\nAllowed metrics: ['mean','median','count']\n"
|
| 51 |
+
"Example Q: Aside from London, with a budget of £500,000, which place and property can I afford?\n"
|
| 52 |
+
"Example JSON: {\"task\":\"affordability\",\"filters\":{\"Sale_Price_GBP\":{\"lte\":500000},"
|
| 53 |
+
"\"Location_City\":{\"not_in\":[\"London\"]}},\"groupby\":[\"Location_City\",\"Property_Type\"],"
|
| 54 |
+
"\"metrics\":[{\"col\":\"Sale_Price_GBP\",\"op\":\"mean\",\"label\":\"avg_price\"}],"
|
| 55 |
+
"\"sort_by\":[{\"col\":\"avg_price\",\"asc\":true}],\"limit\":10}"
|
| 56 |
+
) % (cols, cats, nums)
|
| 57 |
+
|
| 58 |
+
prompt = SYSTEM_PLANNER + "\n\n" + fewshot + "\n\nUser question: " + question + "\nJSON:"
|
| 59 |
+
out = llm(prompt)[0]["generated_text"].strip()
|
| 60 |
+
m = re.search(r"\{[\s\S]*\}$", out)
|
| 61 |
+
if not m:
|
| 62 |
+
return {
|
| 63 |
+
"task": "fallback_top_cities",
|
| 64 |
+
"groupby": ["Location_City"],
|
| 65 |
+
"metrics": [{"col": "Sale_Price_GBP", "op": "mean", "label": "avg_price"}],
|
| 66 |
+
"sort_by": [{"col": "avg_price", "asc": False}],
|
| 67 |
+
"limit": 10,
|
| 68 |
+
}
|
| 69 |
+
try:
|
| 70 |
+
return json.loads(m.group(0))
|
| 71 |
+
except Exception:
|
| 72 |
+
return {
|
| 73 |
+
"task": "fallback_top_cities",
|
| 74 |
+
"groupby": ["Location_City"],
|
| 75 |
+
"metrics": [{"col": "Sale_Price_GBP", "op": "mean", "label": "avg_price"}],
|
| 76 |
+
"sort_by": [{"col": "avg_price", "asc": False}],
|
| 77 |
+
"limit": 10,
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
EXPLAIN_SYS = (
|
| 81 |
+
"You are a concise analyst. Given a small results table and the user's question, "
|
| 82 |
+
"write 2–5 short sentences with the main takeaway. Mention key filters (e.g., budget, city)."
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
def explain_answer(question: str, table: pd.DataFrame) -> str:
|
| 86 |
+
llm = _get_llm()
|
| 87 |
+
preview = table.to_csv(index=False)
|
| 88 |
+
prompt = EXPLAIN_SYS + "\n\nQuestion: " + question + "\nTable:\n" + preview + "\n\nAnswer:"
|
| 89 |
+
out = llm(prompt)[0]["generated_text"].strip()
|
| 90 |
+
return out
|
| 91 |
+
|
ml_price_prediction.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Machine Learning Models for UK Housing Price Prediction
|
| 3 |
+
Multiple algorithms comparison and optimization
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import numpy as np
|
| 8 |
+
import matplotlib.pyplot as plt
|
| 9 |
+
import seaborn as sns
|
| 10 |
+
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
|
| 11 |
+
from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder
|
| 12 |
+
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
|
| 13 |
+
from sklearn.linear_model import LinearRegression, Ridge, Lasso
|
| 14 |
+
from sklearn.svm import SVR
|
| 15 |
+
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
|
| 16 |
+
from sklearn.compose import ColumnTransformer
|
| 17 |
+
from sklearn.pipeline import Pipeline
|
| 18 |
+
import warnings
|
| 19 |
+
warnings.filterwarnings('ignore')
|
| 20 |
+
|
| 21 |
+
class HousingPricePredictor:
|
| 22 |
+
def __init__(self, data_path):
|
| 23 |
+
"""Initialize the predictor with the dataset"""
|
| 24 |
+
self.data = pd.read_csv(data_path)
|
| 25 |
+
self.prepare_data()
|
| 26 |
+
self.models = {}
|
| 27 |
+
self.results = {}
|
| 28 |
+
|
| 29 |
+
def prepare_data(self):
|
| 30 |
+
"""Clean and prepare the data for machine learning"""
|
| 31 |
+
print("Preparing data for machine learning...")
|
| 32 |
+
|
| 33 |
+
# Convert date column
|
| 34 |
+
self.data['Listing_Date'] = pd.to_datetime(self.data['Listing_Date'])
|
| 35 |
+
self.data['Year'] = self.data['Listing_Date'].dt.year
|
| 36 |
+
self.data['Month'] = self.data['Listing_Date'].dt.month
|
| 37 |
+
self.data['Quarter'] = self.data['Listing_Date'].dt.quarter
|
| 38 |
+
|
| 39 |
+
# Create derived features
|
| 40 |
+
self.data['Price_Per_Sqft'] = self.data['Sale_Price_GBP'] / self.data['Square_Footage']
|
| 41 |
+
self.data['Property_Age'] = self.data['Year'] - self.data['Year_Built']
|
| 42 |
+
self.data['Total_Rooms'] = self.data['Bedrooms'] + self.data['Bathrooms']
|
| 43 |
+
self.data['Size_Per_Room'] = self.data['Square_Footage'] / self.data['Total_Rooms']
|
| 44 |
+
|
| 45 |
+
# Handle missing values
|
| 46 |
+
self.data['Nearby_Amenities_Score'] = self.data['Nearby_Amenities_Score'].fillna(
|
| 47 |
+
self.data['Nearby_Amenities_Score'].median()
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# Create location-based features
|
| 51 |
+
self.data['Is_London'] = (self.data['Location_City'] == 'London').astype(int)
|
| 52 |
+
self.data['Is_Central_London'] = self.data['Location_District'].isin([
|
| 53 |
+
'Kensington', 'Chelsea', 'Islington', 'Camden', 'Hackney', 'Brixton', 'Shoreditch'
|
| 54 |
+
]).astype(int)
|
| 55 |
+
|
| 56 |
+
# Create property type dummies
|
| 57 |
+
self.data['Is_Detached'] = (self.data['Property_Type'] == 'Detached House').astype(int)
|
| 58 |
+
self.data['Is_Townhouse'] = (self.data['Property_Type'] == 'Townhouse').astype(int)
|
| 59 |
+
|
| 60 |
+
print(f"Dataset prepared: {self.data.shape}")
|
| 61 |
+
|
| 62 |
+
def prepare_features(self):
|
| 63 |
+
"""Prepare features for machine learning"""
|
| 64 |
+
# Select features for modeling
|
| 65 |
+
feature_columns = [
|
| 66 |
+
'Square_Footage', 'Bedrooms', 'Bathrooms', 'Year_Built', 'Property_Age',
|
| 67 |
+
'Build_Quality_Rating', 'Nearby_Amenities_Score', 'Market_Trend_Index',
|
| 68 |
+
'Days_On_Market', 'Agent_Commission_Percentage', 'Year', 'Month', 'Quarter',
|
| 69 |
+
'Total_Rooms', 'Size_Per_Room', 'Is_London', 'Is_Central_London',
|
| 70 |
+
'Is_Detached', 'Is_Townhouse'
|
| 71 |
+
]
|
| 72 |
+
|
| 73 |
+
# Categorical features for encoding
|
| 74 |
+
categorical_features = ['Location_City', 'Location_District', 'Property_Type']
|
| 75 |
+
|
| 76 |
+
# Prepare X and y
|
| 77 |
+
X_numeric = self.data[feature_columns]
|
| 78 |
+
X_categorical = self.data[categorical_features]
|
| 79 |
+
y = self.data['Sale_Price_GBP']
|
| 80 |
+
|
| 81 |
+
# Encode categorical variables
|
| 82 |
+
le_city = LabelEncoder()
|
| 83 |
+
le_district = LabelEncoder()
|
| 84 |
+
le_type = LabelEncoder()
|
| 85 |
+
|
| 86 |
+
X_categorical_encoded = pd.DataFrame({
|
| 87 |
+
'Location_City': le_city.fit_transform(X_categorical['Location_City']),
|
| 88 |
+
'Location_District': le_district.fit_transform(X_categorical['Location_District']),
|
| 89 |
+
'Property_Type': le_type.fit_transform(X_categorical['Property_Type'])
|
| 90 |
+
})
|
| 91 |
+
|
| 92 |
+
# Combine all features
|
| 93 |
+
X = pd.concat([X_numeric, X_categorical_encoded], axis=1)
|
| 94 |
+
|
| 95 |
+
# Store encoders for later use
|
| 96 |
+
self.encoders = {
|
| 97 |
+
'city': le_city,
|
| 98 |
+
'district': le_district,
|
| 99 |
+
'type': le_type
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
return X, y
|
| 103 |
+
|
| 104 |
+
def train_models(self):
|
| 105 |
+
"""Train multiple machine learning models"""
|
| 106 |
+
print("\nTraining machine learning models...")
|
| 107 |
+
|
| 108 |
+
X, y = self.prepare_features()
|
| 109 |
+
|
| 110 |
+
# Split the data
|
| 111 |
+
X_train, X_test, y_train, y_test = train_test_split(
|
| 112 |
+
X, y, test_size=0.2, random_state=42
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# Store split data
|
| 116 |
+
self.X_train, self.X_test = X_train, X_test
|
| 117 |
+
self.y_train, self.y_test = y_train, y_test
|
| 118 |
+
|
| 119 |
+
# Scale the features
|
| 120 |
+
scaler = StandardScaler()
|
| 121 |
+
X_train_scaled = scaler.fit_transform(X_train)
|
| 122 |
+
X_test_scaled = scaler.transform(X_test)
|
| 123 |
+
|
| 124 |
+
self.scaler = scaler
|
| 125 |
+
|
| 126 |
+
# Define models
|
| 127 |
+
models = {
|
| 128 |
+
'Linear Regression': LinearRegression(),
|
| 129 |
+
'Ridge Regression': Ridge(alpha=1.0),
|
| 130 |
+
'Lasso Regression': Lasso(alpha=0.1),
|
| 131 |
+
'Random Forest': RandomForestRegressor(n_estimators=100, random_state=42),
|
| 132 |
+
'Gradient Boosting': GradientBoostingRegressor(n_estimators=100, random_state=42),
|
| 133 |
+
'SVR': SVR(kernel='rbf', C=1.0, gamma='scale')
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
# Train and evaluate models
|
| 137 |
+
for name, model in models.items():
|
| 138 |
+
print(f"Training {name}...")
|
| 139 |
+
|
| 140 |
+
# Use scaled data for models that benefit from it
|
| 141 |
+
if name in ['Linear Regression', 'Ridge Regression', 'Lasso Regression', 'SVR']:
|
| 142 |
+
model.fit(X_train_scaled, y_train)
|
| 143 |
+
y_pred = model.predict(X_test_scaled)
|
| 144 |
+
else:
|
| 145 |
+
model.fit(X_train, y_train)
|
| 146 |
+
y_pred = model.predict(X_test)
|
| 147 |
+
|
| 148 |
+
# Calculate metrics
|
| 149 |
+
mae = mean_absolute_error(y_test, y_pred)
|
| 150 |
+
mse = mean_squared_error(y_test, y_pred)
|
| 151 |
+
rmse = np.sqrt(mse)
|
| 152 |
+
r2 = r2_score(y_test, y_pred)
|
| 153 |
+
|
| 154 |
+
# Store results
|
| 155 |
+
self.models[name] = model
|
| 156 |
+
self.results[name] = {
|
| 157 |
+
'MAE': mae,
|
| 158 |
+
'MSE': mse,
|
| 159 |
+
'RMSE': rmse,
|
| 160 |
+
'R2': r2,
|
| 161 |
+
'predictions': y_pred
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
print(f" MAE: £{mae:,.2f}")
|
| 165 |
+
print(f" RMSE: £{rmse:,.2f}")
|
| 166 |
+
print(f" R²: {r2:.4f}")
|
| 167 |
+
print()
|
| 168 |
+
|
| 169 |
+
def optimize_best_model(self):
|
| 170 |
+
"""Optimize the best performing model using GridSearchCV"""
|
| 171 |
+
print("Optimizing the best model...")
|
| 172 |
+
|
| 173 |
+
# Find best model based on R² score
|
| 174 |
+
best_model_name = max(self.results.keys(), key=lambda x: self.results[x]['R2'])
|
| 175 |
+
print(f"Best model: {best_model_name} (R² = {self.results[best_model_name]['R2']:.4f})")
|
| 176 |
+
|
| 177 |
+
if best_model_name == 'Random Forest':
|
| 178 |
+
# Optimize Random Forest
|
| 179 |
+
param_grid = {
|
| 180 |
+
'n_estimators': [100, 200, 300],
|
| 181 |
+
'max_depth': [10, 20, None],
|
| 182 |
+
'min_samples_split': [2, 5, 10],
|
| 183 |
+
'min_samples_leaf': [1, 2, 4]
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
rf = RandomForestRegressor(random_state=42)
|
| 187 |
+
grid_search = GridSearchCV(
|
| 188 |
+
rf, param_grid, cv=5, scoring='r2', n_jobs=-1
|
| 189 |
+
)
|
| 190 |
+
grid_search.fit(self.X_train, self.y_train)
|
| 191 |
+
|
| 192 |
+
# Update best model
|
| 193 |
+
self.models['Random Forest Optimized'] = grid_search.best_estimator_
|
| 194 |
+
y_pred_opt = grid_search.best_estimator_.predict(self.X_test)
|
| 195 |
+
|
| 196 |
+
# Calculate optimized metrics
|
| 197 |
+
mae_opt = mean_absolute_error(self.y_test, y_pred_opt)
|
| 198 |
+
mse_opt = mean_squared_error(self.y_test, y_pred_opt)
|
| 199 |
+
rmse_opt = np.sqrt(mse_opt)
|
| 200 |
+
r2_opt = r2_score(self.y_test, y_pred_opt)
|
| 201 |
+
|
| 202 |
+
self.results['Random Forest Optimized'] = {
|
| 203 |
+
'MAE': mae_opt,
|
| 204 |
+
'MSE': mse_opt,
|
| 205 |
+
'RMSE': rmse_opt,
|
| 206 |
+
'R2': r2_opt,
|
| 207 |
+
'predictions': y_pred_opt
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
print(f"Optimized Random Forest:")
|
| 211 |
+
print(f" MAE: £{mae_opt:,.2f}")
|
| 212 |
+
print(f" RMSE: £{rmse_opt:,.2f}")
|
| 213 |
+
print(f" R²: {r2_opt:.4f}")
|
| 214 |
+
print(f" Best parameters: {grid_search.best_params_}")
|
| 215 |
+
|
| 216 |
+
def feature_importance_analysis(self):
|
| 217 |
+
"""Analyze feature importance for the best model"""
|
| 218 |
+
print("\nAnalyzing feature importance...")
|
| 219 |
+
|
| 220 |
+
# Get the best model
|
| 221 |
+
best_model_name = max(self.results.keys(), key=lambda x: self.results[x]['R2'])
|
| 222 |
+
best_model = self.models[best_model_name]
|
| 223 |
+
|
| 224 |
+
if hasattr(best_model, 'feature_importances_'):
|
| 225 |
+
# Get feature names
|
| 226 |
+
feature_names = self.X_train.columns
|
| 227 |
+
|
| 228 |
+
# Get feature importances
|
| 229 |
+
importances = best_model.feature_importances_
|
| 230 |
+
|
| 231 |
+
# Create importance dataframe
|
| 232 |
+
importance_df = pd.DataFrame({
|
| 233 |
+
'feature': feature_names,
|
| 234 |
+
'importance': importances
|
| 235 |
+
}).sort_values('importance', ascending=False)
|
| 236 |
+
|
| 237 |
+
print(f"\nTop 10 Most Important Features ({best_model_name}):")
|
| 238 |
+
print(importance_df.head(10))
|
| 239 |
+
|
| 240 |
+
# Plot feature importance
|
| 241 |
+
plt.figure(figsize=(10, 8))
|
| 242 |
+
top_features = importance_df.head(15)
|
| 243 |
+
sns.barplot(data=top_features, x='importance', y='feature')
|
| 244 |
+
plt.title(f'Feature Importance - {best_model_name}')
|
| 245 |
+
plt.xlabel('Importance')
|
| 246 |
+
plt.tight_layout()
|
| 247 |
+
plt.savefig('feature_importance.png', dpi=300, bbox_inches='tight')
|
| 248 |
+
plt.show()
|
| 249 |
+
|
| 250 |
+
return importance_df
|
| 251 |
+
else:
|
| 252 |
+
print(f"Model {best_model_name} does not support feature importance analysis.")
|
| 253 |
+
return None
|
| 254 |
+
|
| 255 |
+
def create_predictions_visualization(self):
|
| 256 |
+
"""Create visualizations for model predictions"""
|
| 257 |
+
print("\nCreating prediction visualizations...")
|
| 258 |
+
|
| 259 |
+
# Create subplots
|
| 260 |
+
fig, axes = plt.subplots(2, 3, figsize=(18, 12))
|
| 261 |
+
axes = axes.ravel()
|
| 262 |
+
|
| 263 |
+
model_names = list(self.results.keys())
|
| 264 |
+
|
| 265 |
+
for i, (name, results) in enumerate(self.results.items()):
|
| 266 |
+
if i >= 6: # Limit to 6 plots
|
| 267 |
+
break
|
| 268 |
+
|
| 269 |
+
ax = axes[i]
|
| 270 |
+
y_pred = results['predictions']
|
| 271 |
+
|
| 272 |
+
# Scatter plot: Actual vs Predicted
|
| 273 |
+
ax.scatter(self.y_test, y_pred, alpha=0.5)
|
| 274 |
+
ax.plot([self.y_test.min(), self.y_test.max()],
|
| 275 |
+
[self.y_test.min(), self.y_test.max()], 'r--', lw=2)
|
| 276 |
+
ax.set_xlabel('Actual Price (GBP)')
|
| 277 |
+
ax.set_ylabel('Predicted Price (GBP)')
|
| 278 |
+
ax.set_title(f'{name}\nR² = {results["R2"]:.4f}')
|
| 279 |
+
ax.grid(True)
|
| 280 |
+
|
| 281 |
+
# Hide unused subplots
|
| 282 |
+
for i in range(len(model_names), 6):
|
| 283 |
+
axes[i].set_visible(False)
|
| 284 |
+
|
| 285 |
+
plt.tight_layout()
|
| 286 |
+
plt.savefig('model_predictions.png', dpi=300, bbox_inches='tight')
|
| 287 |
+
plt.show()
|
| 288 |
+
|
| 289 |
+
def model_comparison(self):
|
| 290 |
+
"""Compare all models and create summary"""
|
| 291 |
+
print("\n" + "="*60)
|
| 292 |
+
print("MODEL COMPARISON SUMMARY")
|
| 293 |
+
print("="*60)
|
| 294 |
+
|
| 295 |
+
# Create comparison dataframe
|
| 296 |
+
comparison_data = []
|
| 297 |
+
for name, results in self.results.items():
|
| 298 |
+
comparison_data.append({
|
| 299 |
+
'Model': name,
|
| 300 |
+
'MAE (GBP)': f"£{results['MAE']:,.2f}",
|
| 301 |
+
'RMSE (GBP)': f"£{results['RMSE']:,.2f}",
|
| 302 |
+
'R² Score': f"{results['R2']:.4f}",
|
| 303 |
+
'MAE %': f"{(results['MAE'] / self.y_test.mean()) * 100:.2f}%"
|
| 304 |
+
})
|
| 305 |
+
|
| 306 |
+
comparison_df = pd.DataFrame(comparison_data)
|
| 307 |
+
comparison_df = comparison_df.sort_values('R² Score', ascending=False)
|
| 308 |
+
|
| 309 |
+
print(comparison_df.to_string(index=False))
|
| 310 |
+
|
| 311 |
+
# Create comparison visualization
|
| 312 |
+
plt.figure(figsize=(15, 5))
|
| 313 |
+
|
| 314 |
+
# R² Score comparison
|
| 315 |
+
plt.subplot(1, 3, 1)
|
| 316 |
+
models = list(self.results.keys())
|
| 317 |
+
r2_scores = [self.results[model]['R2'] for model in models]
|
| 318 |
+
plt.bar(models, r2_scores)
|
| 319 |
+
plt.title('R² Score Comparison')
|
| 320 |
+
plt.ylabel('R² Score')
|
| 321 |
+
plt.xticks(rotation=45)
|
| 322 |
+
|
| 323 |
+
# MAE comparison
|
| 324 |
+
plt.subplot(1, 3, 2)
|
| 325 |
+
mae_scores = [self.results[model]['MAE'] for model in models]
|
| 326 |
+
plt.bar(models, mae_scores)
|
| 327 |
+
plt.title('Mean Absolute Error Comparison')
|
| 328 |
+
plt.ylabel('MAE (GBP)')
|
| 329 |
+
plt.xticks(rotation=45)
|
| 330 |
+
|
| 331 |
+
# RMSE comparison
|
| 332 |
+
plt.subplot(1, 3, 3)
|
| 333 |
+
rmse_scores = [self.results[model]['RMSE'] for model in models]
|
| 334 |
+
plt.bar(models, rmse_scores)
|
| 335 |
+
plt.title('Root Mean Square Error Comparison')
|
| 336 |
+
plt.ylabel('RMSE (GBP)')
|
| 337 |
+
plt.xticks(rotation=45)
|
| 338 |
+
|
| 339 |
+
plt.tight_layout()
|
| 340 |
+
plt.savefig('model_comparison.png', dpi=300, bbox_inches='tight')
|
| 341 |
+
plt.show()
|
| 342 |
+
|
| 343 |
+
def predict_price(self, property_data):
|
| 344 |
+
"""Predict price for a new property"""
|
| 345 |
+
# This would be used for making predictions on new data
|
| 346 |
+
# For now, just return the best model
|
| 347 |
+
best_model_name = max(self.results.keys(), key=lambda x: self.results[x]['R2'])
|
| 348 |
+
return self.models[best_model_name]
|
| 349 |
+
|
| 350 |
+
def run_complete_analysis(self):
|
| 351 |
+
"""Run the complete machine learning analysis"""
|
| 352 |
+
print("UK HOUSING PRICE PREDICTION - MACHINE LEARNING ANALYSIS")
|
| 353 |
+
print("="*60)
|
| 354 |
+
|
| 355 |
+
self.train_models()
|
| 356 |
+
self.optimize_best_model()
|
| 357 |
+
self.feature_importance_analysis()
|
| 358 |
+
self.create_predictions_visualization()
|
| 359 |
+
self.model_comparison()
|
| 360 |
+
|
| 361 |
+
print("\n" + "="*60)
|
| 362 |
+
print("MACHINE LEARNING ANALYSIS COMPLETE")
|
| 363 |
+
print("="*60)
|
| 364 |
+
print("Visualizations saved:")
|
| 365 |
+
print("- feature_importance.png")
|
| 366 |
+
print("- model_predictions.png")
|
| 367 |
+
print("- model_comparison.png")
|
| 368 |
+
|
| 369 |
+
if __name__ == "__main__":
|
| 370 |
+
# Initialize predictor
|
| 371 |
+
predictor = HousingPricePredictor('data/uk_real_estate_dataset_with_revenue (1).csv')
|
| 372 |
+
|
| 373 |
+
# Run complete analysis
|
| 374 |
+
predictor.run_complete_analysis()
|
| 375 |
+
|
plan_executor.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
|
| 3 |
+
ALLOWED_OPS = {"mean", "median", "count"}
|
| 4 |
+
|
| 5 |
+
def execute_plan(df: pd.DataFrame, plan: dict) -> pd.DataFrame:
|
| 6 |
+
q = df.copy()
|
| 7 |
+
|
| 8 |
+
# filters
|
| 9 |
+
for col, rule in (plan.get("filters") or {}).items():
|
| 10 |
+
if col not in q.columns:
|
| 11 |
+
raise ValueError("Unknown column: %s" % col)
|
| 12 |
+
if not isinstance(rule, dict):
|
| 13 |
+
raise ValueError("Bad filter rule for %s" % col)
|
| 14 |
+
if "eq" in rule:
|
| 15 |
+
q = q[q[col] == rule["eq"]]
|
| 16 |
+
if "in" in rule:
|
| 17 |
+
q = q[q[col].isin(rule["in"])]
|
| 18 |
+
if "not_in" in rule:
|
| 19 |
+
q = q[~q[col].isin(rule["not_in"])]
|
| 20 |
+
if "gte" in rule:
|
| 21 |
+
q = q[q[col] >= rule["gte"]]
|
| 22 |
+
if "lte" in rule:
|
| 23 |
+
q = q[q[col] <= rule["lte"]]
|
| 24 |
+
|
| 25 |
+
groupby = plan.get("groupby") or []
|
| 26 |
+
metrics = plan.get("metrics") or []
|
| 27 |
+
|
| 28 |
+
if groupby:
|
| 29 |
+
gb = q.groupby(groupby, dropna=False)
|
| 30 |
+
agg_dict = {}
|
| 31 |
+
for m in metrics:
|
| 32 |
+
col, op = m.get("col"), m.get("op")
|
| 33 |
+
label = m.get("label", "%s_%s" % (op, col))
|
| 34 |
+
if op not in ALLOWED_OPS:
|
| 35 |
+
raise ValueError("Unsupported op: %s" % op)
|
| 36 |
+
if op == "count":
|
| 37 |
+
agg_dict[label] = (col, "count")
|
| 38 |
+
else:
|
| 39 |
+
agg_dict[label] = (col, op)
|
| 40 |
+
res = gb.agg(**agg_dict).reset_index() if agg_dict else gb.size().reset_index(name="count")
|
| 41 |
+
else:
|
| 42 |
+
# global summary
|
| 43 |
+
rows = {}
|
| 44 |
+
for m in metrics:
|
| 45 |
+
col, op = m.get("col"), m.get("op")
|
| 46 |
+
label = m.get("label", "%s_%s" % (op, col))
|
| 47 |
+
if op not in ALLOWED_OPS:
|
| 48 |
+
raise ValueError("Unsupported op: %s" % op)
|
| 49 |
+
if op == "count":
|
| 50 |
+
rows[label] = int(q[col].count())
|
| 51 |
+
else:
|
| 52 |
+
rows[label] = float(getattr(q[col], op)())
|
| 53 |
+
res = pd.DataFrame([rows]) if rows else q.head(20)
|
| 54 |
+
|
| 55 |
+
for s in (plan.get("sort_by") or []):
|
| 56 |
+
res = res.sort_values(s.get("col"), ascending=bool(s.get("asc", True)))
|
| 57 |
+
|
| 58 |
+
limit = min(int(plan.get("limit", 20)), 50)
|
| 59 |
+
return res.head(limit)
|
predictor.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import joblib
|
| 4 |
+
import pandas as pd
|
| 5 |
+
|
| 6 |
+
from data_utils import enrich_data, load_raw_data
|
| 7 |
+
|
| 8 |
+
# Load once for fallback stats
|
| 9 |
+
_df = enrich_data(load_raw_data())
|
| 10 |
+
|
| 11 |
+
MODEL_DIR = Path("models")
|
| 12 |
+
_model = None
|
| 13 |
+
try:
|
| 14 |
+
if (MODEL_DIR / "gradient_boosting_model.pkl").exists():
|
| 15 |
+
_model = joblib.load(MODEL_DIR / "gradient_boosting_model.pkl")
|
| 16 |
+
except Exception as e:
|
| 17 |
+
print("Model artifact loading warning:", e)
|
| 18 |
+
|
| 19 |
+
def predict_price(sqft: float, bedrooms: int, bathrooms: int, year_built: int,
|
| 20 |
+
quality: int, city: str, prop_type: str):
|
| 21 |
+
if _model is None:
|
| 22 |
+
# fallback: price per sqft × sqft with quality tweak
|
| 23 |
+
city_pps = _df[_df["Location_City"] == city]["Price_Per_Sqft"].mean()
|
| 24 |
+
if pd.isna(city_pps):
|
| 25 |
+
city_pps = _df["Price_Per_Sqft"].mean()
|
| 26 |
+
price = sqft * float(city_pps) * (1 + (quality - 5) * 0.02)
|
| 27 |
+
return price, False
|
| 28 |
+
try:
|
| 29 |
+
age = datetime.now().year - year_built
|
| 30 |
+
total_rooms = bedrooms + bathrooms
|
| 31 |
+
size_per_room = sqft / total_rooms if total_rooms else sqft
|
| 32 |
+
row = pd.DataFrame([{
|
| 33 |
+
"Square_Footage": sqft,
|
| 34 |
+
"Bedrooms": bedrooms,
|
| 35 |
+
"Bathrooms": bathrooms,
|
| 36 |
+
"Year_Built": year_built,
|
| 37 |
+
"Property_Age": age,
|
| 38 |
+
"Quality_Score": quality,
|
| 39 |
+
"Total_Rooms": total_rooms,
|
| 40 |
+
"Size_Per_Room": size_per_room,
|
| 41 |
+
"Is_London": 1 if city == "London" else 0,
|
| 42 |
+
"Is_Central_London": 0,
|
| 43 |
+
"Is_Detached": 1 if prop_type == "Detached House" else 0,
|
| 44 |
+
"Is_Townhouse": 1 if prop_type == "Townhouse" else 0,
|
| 45 |
+
}])
|
| 46 |
+
y = _model.predict(row)[0]
|
| 47 |
+
return float(y), True
|
| 48 |
+
except Exception:
|
| 49 |
+
price = sqft * float(_df["Price_Per_Sqft"].mean())
|
| 50 |
+
return price, False
|