chandrachurhghosh's picture
Upload folder using huggingface_hub
5f15cd4 verified
Raw
History Blame Contribute Delete
1.44 kB
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
import joblib
import os
# Define paths for data and model
DATA_DIR = 'tourism_project/data'
X_TRAIN_PATH = os.path.join(DATA_DIR, 'X_train.csv')
Y_TRAIN_PATH = os.path.join(DATA_DIR, 'y_train.csv')
MODEL_OUTPUT_PATH = 'tourism_project/best_random_forest_model.joblib'
def train_model():
print("Loading training data...")
X_train = pd.read_csv(X_TRAIN_PATH)
y_train = pd.read_csv(Y_TRAIN_PATH)
# Flatten y_train
y_train = y_train.values.ravel()
print("Initializing RandomForestClassifier...")
model = RandomForestClassifier(random_state=42)
param_grid = {
'n_estimators': [100, 200, 300],
'max_depth': [None, 10, 20],
'min_samples_split': [2, 5, 10]
}
print("Performing GridSearchCV for hyperparameter tuning...")
grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=5, scoring='accuracy', n_jobs=-1, verbose=1)
grid_search.fit(X_train, y_train)
print(f"Best parameters found: {grid_search.best_params_}")
print(f"Best cross-validation accuracy: {grid_search.best_score_}")
best_model = grid_search.best_estimator_
print(f"Saving best model to {MODEL_OUTPUT_PATH}")
joblib.dump(best_model, MODEL_OUTPUT_PATH)
print("Model training and saving complete.")
if __name__ == '__main__':
train_model()