leadingbridge commited on
Commit
a24f96a
·
verified ·
1 Parent(s): a88873a

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +73 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,75 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ from sklearn.model_selection import train_test_split, GridSearchCV
5
+ from sklearn.ensemble import RandomForestRegressor
6
+ from sklearn.metrics import mean_squared_error, r2_score
7
+
8
+ # URL to the Excel dataset on Hugging Face
9
+ data_url = "https://huggingface.co/datasets/leadingbridge/flat/resolve/main/NorthPoint30.xlsx"
10
+
11
+ @st.cache_resource
12
+ def load_and_train_model():
13
+ df = pd.read_excel(data_url, engine="openpyxl")
14
+
15
+ # Drop columns that are not needed for prediction
16
+ cols_to_drop = ['Usage', 'Address', 'PricePerSquareFeet', 'InstrumentDate', 'Floor', 'Unit']
17
+ df.drop(columns=cols_to_drop, inplace=True, errors='ignore')
18
+
19
+ # Rename useful columns for consistency
20
+ df.rename(columns={"Floor.1": "Floor", "Unit.1": "Unit"}, inplace=True)
21
+
22
+ required_columns = [
23
+ 'District', 'PriceInMillion', 'Longitude', 'Latitude',
24
+ 'Floor', 'Unit', 'Area', 'Year', 'WeekNumber'
25
+ ]
26
+ if not all(col in df.columns for col in required_columns):
27
+ raise ValueError("Dataset is missing one or more required columns.")
28
+
29
+ feature_names = ['District', 'Longitude', 'Latitude', 'Floor', 'Unit', 'Area', 'Year', 'WeekNumber']
30
+ X = df[feature_names]
31
+ y = df['PriceInMillion']
32
+
33
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
34
+
35
+ rf_param_grid = {
36
+ 'n_estimators': [50, 100, 150],
37
+ 'max_depth': [4, 6, 8],
38
+ 'max_features': ['sqrt', 'log2', 3],
39
+ 'random_state': [42]
40
+ }
41
+
42
+ rf_grid = GridSearchCV(RandomForestRegressor(), rf_param_grid, refit=True, verbose=1, cv=5, error_score='raise')
43
+ rf_grid.fit(X_train, y_train)
44
+
45
+ model = rf_grid.best_estimator_
46
+ return model, feature_names
47
+
48
+ @st.cache_data
49
+ def predict_price(model, feature_names, new_data):
50
+ new_data_df = pd.DataFrame([new_data], columns=feature_names)
51
+ prediction = model.predict(new_data_df)
52
+ return prediction[0]
53
+
54
+ def main():
55
+ st.title("PROPERTY PRICE PREDICTION TOOL (Streamlit Version)")
56
+ st.markdown("Predict the price of a new property based on District, Longitude, Latitude, Floor, Unit, Area, Year, and Week Number.")
57
+
58
+ model, feature_names = load_and_train_model()
59
+
60
+ district = st.selectbox("District (1 = Taikoo Shing, 2 = Mei Foo Sun Chuen, 3 = South Horizons, 4 = Whampoa Garden)", list(range(1, 9)))
61
+ longitude = st.number_input("Longitude", value=114.200)
62
+ latitude = st.number_input("Latitude", value=22.300)
63
+ floor = st.selectbox("Floor", list(range(1, 71)))
64
+ unit = st.selectbox("Unit (e.g., A=1, B=2, C=3, ...)", list(range(1, 31)))
65
+ area = st.slider("Area (in sq. feet)", min_value=137, max_value=5000, value=300)
66
+ year = st.selectbox("Year", [2024, 2025])
67
+ weeknumber = st.selectbox("Week Number", list(range(1, 53)))
68
+
69
+ if st.button("Predict"):
70
+ new_data = [district, longitude, latitude, floor, unit, area, year, weeknumber]
71
+ prediction = predict_price(model, feature_names, new_data)
72
+ st.success(f"🏠 Estimated Price: **${prediction:,.2f} Million**")
73
 
74
+ if __name__ == "__main__":
75
+ main()