File size: 1,304 Bytes
2a353d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score
import joblib # Import joblib for saving the model

try:
    with open('./data.json', 'r') as f:
        data = json.load(f)
except FileNotFoundError:
    print("Error: 'data.json' not found. Please ensure the file is in the same directory as this script.")
    exit()

df = pd.DataFrame.from_dict(data, orient='index')
df[['latitude', 'longitude']] = pd.DataFrame(df['middle_point'].tolist(), index=df.index)
df.drop('middle_point', axis=1, inplace=True)
df = df[df['price'] > 1.0]

features = ['area', 'dis', 'type', 'latitude', 'longitude']
target = 'price'
X = df[features]
y = df[target]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(f"Data loaded. Training model on {len(X_train)} samples...")

model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
print("Model training complete.")

y_pred = model.predict(X_test)
r2 = r2_score(y_test, y_pred)
print(f"Model R-squared on test data: {r2:.4f}")


model_filename = 'random_forest_model.joblib'
joblib.dump(model, model_filename)
print(f"\nModel saved successfully as '{model_filename}'")