import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import RandomForestRegressor
from sklearn.svm import SVR
from sklearn.neighbors import KNeighborsRegressor
from sklearn.linear_model import ElasticNet
from lightgbm import LGBMRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import warnings
warnings.filterwarnings('ignore')
# Load your dataset
# Replace 'your_data.csv' with your actual data file
data = pd.read_csv('your_data.csv')
# Features and target variable
X = data.drop('target', axis=1) # Replace 'target' with your target column name
y = data['target']
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Define models and their hyperparameters for Grid Search with pipelines
models = {
'RandomForest': {
'pipeline': Pipeline([
('model', RandomForestRegressor(random_state=42))
]),
'params': {
'model__n_estimators': [100, 200],
'model__max_depth': [None, 10, 20],
'model__min_samples_split': [2, 5]
}
},
'SVR': {
'pipeline': Pipeline([
('scaler', StandardScaler()),
('model', SVR())
]),
'params': {
'model__C': [0.1, 1, 10],
'model__epsilon': [0.1, 0.2, 0.5],
'model__kernel': ['rbf', 'linear']
}
},
'KNN': {
'pipeline': Pipeline([
('scaler', StandardScaler()),
('model', KNeighborsRegressor())
]),
'params': {
'model__n_neighbors': [5, 10, 20],
'model__weights': ['uniform', 'distance'],
'model__p': [1, 2]
}
},
'ElasticNet': {
'pipeline': Pipeline([
('model', ElasticNet(random_state=42))
]),
'params': {
'model__alpha': [0.1, 1.0, 10.0],
'model__l1_ratio': [0.1, 0.5, 0.9]
}
},
'LightGBM': {
'pipeline': Pipeline([
('model', LGBMRegressor(random_state=42))
]),
'params': {
'model__num_leaves': [31, 50],
'model__learning_rate': [0.05, 0.1],
'model__n_estimators': [100, 200]
}
}
}
# To store the best models and their performance
best_models = {}
performance = {}
for name, config in models.items():
print(f"Training {name} with preprocessing..." if 'scaler' in config['pipeline'].named_steps else f"Training {name}...")
grid = GridSearchCV(config['pipeline'], config['params'], cv=5, scoring='neg_mean_squared_error', n_jobs=-1)
grid.fit(X_train, y_train)
best_models[name] = grid.best_estimator_
# Predictions
y_pred = grid.predict(X_test)
# Metrics
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)
performance[name] = {
'Best Parameters': grid.best_params_,
'MAE': mae,
'MSE': mse,
'RMSE': rmse,
'R2 Score': r2
}
# Display the performance of each model
performance_df = pd.DataFrame(performance).T
print("\nModel Performance with Preprocessing:")
print(performance_df)