Certainly! Below are two Python scripts that fulfill your requirements:
ml_compare_models.py: Loads the ml.xlsx file, preprocesses the data, compares various regression algorithms, and outputs the best performers based on evaluation metrics.
ml_compare_models_with_augmentation.py: Extends the first script by incorporating data augmentation techniques to enhance the limited dataset before model comparison.
Prerequisites
Ensure you have the necessary Python packages installed. You can install them using pip:
pip install pandas numpy scikit-learn openpyxl imblearn
Note: The second script uses imblearn for data augmentation. If you encounter any issues installing it, refer to the imbalanced-learn documentation.
1. Script Without Data Augmentation: ml_compare_models.py
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')
from sklearn.model_selection import train_test_split, cross_val_score, KFold
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor, GradientBoostingRegressor, AdaBoostRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.svm import SVR
from sklearn.neural_network import MLPRegressor
from xgboost import XGBRegressor
from lightgbm import LGBMRegressor
from catboost import CatBoostRegressor
# Load the data
def load_data(file_path):
df = pd.read_excel(file_path, decimal=',')
return df
# Preprocess the data
def preprocess_data(df):
# Encode 'Synthesis' if it's a categorical variable
if df['Synthesis'].dtype == 'object' or df['Synthesis'].dtype.name == 'category':
le = LabelEncoder()
df['Synthesis'] = le.fit_transform(df['Synthesis'])
# Separate features and target
X = df.drop('Output_Recovery_Li', axis=1)
y = df['Output_Recovery_Li']
return X, y
# Define models to evaluate
def get_models():
models = {
'Linear Regression': LinearRegression(),
'Ridge Regression': Ridge(),
'Lasso Regression': Lasso(),
'ElasticNet': ElasticNet(),
'Decision Tree': DecisionTreeRegressor(),
'Random Forest': RandomForestRegressor(),
'Extra Trees': ExtraTreesRegressor(),
'Gradient Boosting': GradientBoostingRegressor(),
'AdaBoost': AdaBoostRegressor(),
'K-Nearest Neighbors': KNeighborsRegressor(),
'Support Vector Regressor': SVR(),
'MLP Regressor': MLPRegressor(max_iter=1000),
'XGBoost': XGBRegressor(objective='reg:squarederror'),
'LightGBM': LGBMRegressor(),
'CatBoost': CatBoostRegressor(verbose=0)
}
return models
# Evaluate models using cross-validation
def evaluate_models(models, X, y):
results = {}
kf = KFold(n_splits=5, shuffle=True, random_state=42)
for name, model in models.items():
pipeline = Pipeline([
('scaler', StandardScaler()),
('regressor', model)
])
# Using negative Mean Absolute Error and R-squared
mae = -cross_val_score(pipeline, X, y, cv=kf, scoring='neg_mean_absolute_error').mean()
r2 = cross_val_score(pipeline, X, y, cv=kf, scoring='r2').mean()
results[name] = {'MAE': mae, 'R2': r2}
print(f"{name}: MAE = {mae:.4f}, R2 = {r2:.4f}")
# Convert to DataFrame for better visualization
results_df = pd.DataFrame(results).T
results_df = results_df.sort_values(by='R2', ascending=False)
return results_df
def main():
file_path = 'ml.xlsx'
print("Loading data...")
df = load_data(file_path)
print("Preprocessing data...")
X, y = preprocess_data(df)
print("Initializing models...")
models = get_models()
print("Evaluating models...")
results_df = evaluate_models(models, X, y)
print("\nModel Performance:")
print(results_df)
# Save the results to a CSV file
results_df.to_csv('model_performance.csv')
print("\nResults saved to 'model_performance.csv'.")
if __name__ == "__main__":
main()
Explanation:
-
Data Loading and Preprocessing:
- The script reads the
ml.xlsx file, handling decimal commas by specifying decimal=','.
- Encodes the
'Synthesis' column using LabelEncoder if it's categorical.
- Separates the features (
X) from the target variable (y).
-
Model Definition:
- A variety of regression models are defined, including linear models, tree-based models, ensemble methods, support vector machines, neural networks, and gradient boosting algorithms like XGBoost, LightGBM, and CatBoost.
-
Model Evaluation:
- Uses 5-fold cross-validation to evaluate each model.
- Calculates the Mean Absolute Error (MAE) and R-squared (R²) for each model.
- Results are printed and saved to a
model_performance.csv file for easy reference.
-
Execution:
2. Script With Data Augmentation: ml_compare_models_with_augmentation.py
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')
from sklearn.model_selection import train_test_split, cross_val_score, KFold
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor, GradientBoostingRegressor, AdaBoostRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.svm import SVR
from sklearn.neural_network import MLPRegressor
from xgboost import XGBRegressor
from lightgbm import LGBMRegressor
from catboost import CatBoostRegressor
from imblearn.over_sampling import SMOTE
# Load the data
def load_data(file_path):
df = pd.read_excel(file_path, decimal=',')
return df
# Preprocess the data
def preprocess_data(df):
# Encode 'Synthesis' if it's a categorical variable
if df['Synthesis'].dtype == 'object' or df['Synthesis'].dtype.name == 'category':
le = LabelEncoder()
df['Synthesis'] = le.fit_transform(df['Synthesis'])
# Separate features and target
X = df.drop('Output_Recovery_Li', axis=1)
y = df['Output_Recovery_Li']
return X, y
# Data Augmentation using SMOTE (Note: SMOTE is traditionally for classification. For regression, use SMOTENC or other techniques)
def augment_data(X, y, random_state=42):
# Since SMOTE is for classification, we'll discretize the target for augmentation
y_discrete = pd.qcut(y, q=4, labels=False)
smote = SMOTE(random_state=random_state)
X_res, y_res = smote.fit_resample(X, y_discrete)
# To get back continuous targets, we'll map the discrete back to original y using nearest neighbors
df_res = pd.DataFrame(X_res)
df_res['y_discrete'] = y_res
df_original = pd.concat([X, y_discrete], axis=1)
# Merge to get approximate continuous y
df_augmented = df_res.merge(df_original, on='y_discrete', how='left')
y_augmented = df_augmented['y']
X_augmented = df_augmented.drop(['y_discrete', 'y'], axis=1)
return X_augmented, y_augmented
# Define models to evaluate
def get_models():
models = {
'Linear Regression': LinearRegression(),
'Ridge Regression': Ridge(),
'Lasso Regression': Lasso(),
'ElasticNet': ElasticNet(),
'Decision Tree': DecisionTreeRegressor(),
'Random Forest': RandomForestRegressor(),
'Extra Trees': ExtraTreesRegressor(),
'Gradient Boosting': GradientBoostingRegressor(),
'AdaBoost': AdaBoostRegressor(),
'K-Nearest Neighbors': KNeighborsRegressor(),
'Support Vector Regressor': SVR(),
'MLP Regressor': MLPRegressor(max_iter=1000),
'XGBoost': XGBRegressor(objective='reg:squarederror'),
'LightGBM': LGBMRegressor(),
'CatBoost': CatBoostRegressor(verbose=0)
}
return models
# Evaluate models using cross-validation
def evaluate_models(models, X, y):
results = {}
kf = KFold(n_splits=5, shuffle=True, random_state=42)
for name, model in models.items():
pipeline = Pipeline([
('scaler', StandardScaler()),
('regressor', model)
])
# Using negative Mean Absolute Error and R-squared
mae = -cross_val_score(pipeline, X, y, cv=kf, scoring='neg_mean_absolute_error').mean()
r2 = cross_val_score(pipeline, X, y, cv=kf, scoring='r2').mean()
results[name] = {'MAE': mae, 'R2': r2}
print(f"{name}: MAE = {mae:.4f}, R2 = {r2:.4f}")
# Convert to DataFrame for better visualization
results_df = pd.DataFrame(results).T
results_df = results_df.sort_values(by='R2', ascending=False)
return results_df
def main():
file_path = 'ml.xlsx'
print("Loading data...")
df = load_data(file_path)
print("Preprocessing data...")
X, y = preprocess_data(df)
print("Augmenting data...")
X_aug, y_aug = augment_data(X, y)
print(f"Original data size: {X.shape[0]} samples")
print(f"Augmented data size: {X_aug.shape[0]} samples")
print("Initializing models...")
models = get_models()
print("Evaluating models on augmented data...")
results_df = evaluate_models(models, X_aug, y_aug)
print("\nModel Performance After Augmentation:")
print(results_df)
# Save the results to a CSV file
results_df.to_csv('model_performance_with_augmentation.csv')
print("\nResults saved to 'model_performance_with_augmentation.csv'.")
if __name__ == "__main__":
main()
Explanation:
-
Data Loading and Preprocessing:
- Similar to the first script, it reads and preprocesses the data.
-
Data Augmentation:
- Challenge: SMOTE is primarily designed for classification tasks. To adapt it for regression:
- The continuous target variable (
y) is discretized into categories using pd.qcut.
- SMOTE is applied to balance these categories.
- The augmented discrete targets are then mapped back to continuous values by merging with the original data.
- Note: This is a heuristic approach. For more sophisticated regression augmentation, consider advanced techniques or domain-specific methods.
-
Model Definition and Evaluation:
- Same as the first script, but models are trained and evaluated on the augmented dataset.
-
Execution:
Additional Notes
-
Handling Categorical Variables: If the 'Synthesis' column contains meaningful categorical information, consider using more advanced encoding techniques like One-Hot Encoding or Target Encoding instead of LabelEncoder, especially if there is no ordinal relationship.
-
Data Augmentation Alternatives: The method used in the second script is a workaround. Depending on the nature of your data, you might explore other augmentation techniques such as:
- Adding Noise: Slightly perturb continuous features.
- Synthetic Minority Over-sampling Technique for Regression (SMOGN): Designed specifically for regression tasks.
- Generative Models: Use models like GANs to generate synthetic data.
-
Hyperparameter Tuning: For optimal performance, consider integrating hyperparameter tuning (e.g., using GridSearchCV or RandomizedSearchCV) for each model.
-
Performance Metrics: While MAE and R² are informative, depending on your specific needs, you might also consider other metrics like Root Mean Squared Error (RMSE) or Mean Absolute Percentage Error (MAPE).
-
Feature Importance: After identifying the best-performing models, analyze feature importance to gain insights into which features significantly influence the target variable.
Feel free to customize the scripts further based on your specific requirements and the characteristics of your dataset.