File size: 3,113 Bytes
0fa6542
a24f96a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fa6542
a24f96a
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score

# URL to the Excel dataset on Hugging Face
data_url = "https://huggingface.co/datasets/leadingbridge/flat/resolve/main/NorthPoint30.xlsx"

@st.cache_resource
def load_and_train_model():
    df = pd.read_excel(data_url, engine="openpyxl")

    # Drop columns that are not needed for prediction
    cols_to_drop = ['Usage', 'Address', 'PricePerSquareFeet', 'InstrumentDate', 'Floor', 'Unit']
    df.drop(columns=cols_to_drop, inplace=True, errors='ignore')

    # Rename useful columns for consistency
    df.rename(columns={"Floor.1": "Floor", "Unit.1": "Unit"}, inplace=True)

    required_columns = [
        'District', 'PriceInMillion', 'Longitude', 'Latitude',
        'Floor', 'Unit', 'Area', 'Year', 'WeekNumber'
    ]
    if not all(col in df.columns for col in required_columns):
        raise ValueError("Dataset is missing one or more required columns.")

    feature_names = ['District', 'Longitude', 'Latitude', 'Floor', 'Unit', 'Area', 'Year', 'WeekNumber']
    X = df[feature_names]
    y = df['PriceInMillion']

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

    rf_param_grid = {
        'n_estimators': [50, 100, 150],
        'max_depth': [4, 6, 8],
        'max_features': ['sqrt', 'log2', 3],
        'random_state': [42]
    }

    rf_grid = GridSearchCV(RandomForestRegressor(), rf_param_grid, refit=True, verbose=1, cv=5, error_score='raise')
    rf_grid.fit(X_train, y_train)

    model = rf_grid.best_estimator_
    return model, feature_names

@st.cache_data
def predict_price(model, feature_names, new_data):
    new_data_df = pd.DataFrame([new_data], columns=feature_names)
    prediction = model.predict(new_data_df)
    return prediction[0]

def main():
    st.title("PROPERTY PRICE PREDICTION TOOL (Streamlit Version)")
    st.markdown("Predict the price of a new property based on District, Longitude, Latitude, Floor, Unit, Area, Year, and Week Number.")

    model, feature_names = load_and_train_model()

    district = st.selectbox("District (1 = Taikoo Shing, 2 = Mei Foo Sun Chuen, 3 = South Horizons, 4 = Whampoa Garden)", list(range(1, 9)))
    longitude = st.number_input("Longitude", value=114.200)
    latitude = st.number_input("Latitude", value=22.300)
    floor = st.selectbox("Floor", list(range(1, 71)))
    unit = st.selectbox("Unit (e.g., A=1, B=2, C=3, ...)", list(range(1, 31)))
    area = st.slider("Area (in sq. feet)", min_value=137, max_value=5000, value=300)
    year = st.selectbox("Year", [2024, 2025])
    weeknumber = st.selectbox("Week Number", list(range(1, 53)))

    if st.button("Predict"):
        new_data = [district, longitude, latitude, floor, unit, area, year, weeknumber]
        prediction = predict_price(model, feature_names, new_data)
        st.success(f"๐Ÿ  Estimated Price: **${prediction:,.2f} Million**")

if __name__ == "__main__":
    main()