-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_model.py
More file actions
57 lines (42 loc) · 1.22 KB
/
train_model.py
File metadata and controls
57 lines (42 loc) · 1.22 KB
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
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error,r2_score
from sklearn.preprocessing import LabelEncoder
import joblib
# load datasets
X = pd.read_csv("delhi_traffic_features.csv")
categorical_cols = [
"time_of_day","traffic_density_level"
]
encoder = LabelEncoder()
for col in categorical_cols:
X[col] = encoder.fit_transform(X[col])
X = X[
[
"distance_km","average_speed_kmph","time_of_day","traffic_density_level"
]
]
# Keep only numeric features
X = X.select_dtypes(include=["number"])
y_df = pd.read_csv("delhi_traffic_target.csv")
# convert tar to 1D
y = y_df.select_dtypes(include=["number"]).iloc[:,0]
# split data
X_train, X_test, y_train, y_test= train_test_split(X,y,test_size=0.2,random_state=42)
# model
model = RandomForestRegressor(
n_estimators=100,
random_state=42,
n_jobs=-1
)
# train model
model.fit(X_train,y_train)
# test model
y_pred = model.predict(X_test)
# evaluation
print("MAE:",mean_absolute_error(y_test,y_pred))
print("R2 Score:",r2_score(y_test,y_pred))
# model save
joblib.dump(model,"travel_time_model.pkl")
print("Model trained and saved")