aledraa commited on
Commit
2a353d8
·
verified ·
1 Parent(s): 9703fef

Create random_forest.py

Browse files
Files changed (1) hide show
  1. random_forest.py +39 -0
random_forest.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import pandas as pd
3
+ from sklearn.model_selection import train_test_split
4
+ from sklearn.ensemble import RandomForestRegressor
5
+ from sklearn.metrics import r2_score
6
+ import joblib # Import joblib for saving the model
7
+
8
+ try:
9
+ with open('./data.json', 'r') as f:
10
+ data = json.load(f)
11
+ except FileNotFoundError:
12
+ print("Error: 'data.json' not found. Please ensure the file is in the same directory as this script.")
13
+ exit()
14
+
15
+ df = pd.DataFrame.from_dict(data, orient='index')
16
+ df[['latitude', 'longitude']] = pd.DataFrame(df['middle_point'].tolist(), index=df.index)
17
+ df.drop('middle_point', axis=1, inplace=True)
18
+ df = df[df['price'] > 1.0]
19
+
20
+ features = ['area', 'dis', 'type', 'latitude', 'longitude']
21
+ target = 'price'
22
+ X = df[features]
23
+ y = df[target]
24
+
25
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
26
+ print(f"Data loaded. Training model on {len(X_train)} samples...")
27
+
28
+ model = RandomForestRegressor(n_estimators=100, random_state=42)
29
+ model.fit(X_train, y_train)
30
+ print("Model training complete.")
31
+
32
+ y_pred = model.predict(X_test)
33
+ r2 = r2_score(y_test, y_pred)
34
+ print(f"Model R-squared on test data: {r2:.4f}")
35
+
36
+
37
+ model_filename = 'random_forest_model.joblib'
38
+ joblib.dump(model, model_filename)
39
+ print(f"\nModel saved successfully as '{model_filename}'")