rewrite this code so that it outputs and does the same, but in a different way: from sklearn.metrics import confusion_matrix, accuracy_score, f1_score, precision_score, recall_score, classification_report, balanced_accuracy_score
Here's a rewritten version of the code that achieves the same functionality but with a slightly different approach:
python
from sklearn.metrics import balanced_accuracy_score, f1_score, precision_score, recall_score
import pandas as pd
import numpy as np
def compute_model_metrics(models, X, y, set_name=''):
"""
Compute various performance metrics for a list of models
Parameters:
- models: List of trained models
- X: Feature matrix
- y: Target vector
- set_name: Optional string to identify the dataset (train/validation)
Returns:
- DataFrame with performance metrics
"""
# Initialize dictionaries to store metrics
metrics = {
'Model': [],
'F1 Score': [],
'Balanced Accuracy': [],
'Precision': [],
'Recall': []
}
# Compute metrics for each model
for model in models:
# Make predictions
predictions = model.predict(X)
# Compute metrics
metrics['Model'].append(str(model.__class__.__name__))
metrics['F1 Score'].append(f1_score(y, predictions, average='weighted'))
metrics['Balanced Accuracy'].append(balanced_accuracy_score(y, predictions))
metrics['Precision'].append(precision_score(y, predictions, average='weighted'))
metrics['Recall'].append(recall_score(y, predictions, average='weighted'))
# Create DataFrame
results_df = pd.DataFrame(metrics)
# Set index to model names if needed
results_df.set_index('Model', inplace=True)
# Optional: Add set name to display
if set_name:
print(f"Performance Metrics for {set_name} Set:")
return results_df
# Compute and display metrics
def evaluate_models(model_list, X_train_scaled, y_train, X_val_scaled, y_val):
"""
Evaluate models on both training and validation sets
Parameters:
- model_list: List of trained models
- X_train_scaled: Scaled training features
- y_train: Training target
- X_val_scaled: Scaled validation features
- y_val: Validation target
"""
# Compute metrics for training set
train_results = compute_model_metrics(
model_list,
X_train_scaled,
y_train,
set_name='Training'
)
print("\nTraining Set Metrics:")
print(train_results)
# Compute metrics for validation set
val_results = compute_model_metrics(
model_list,
X_val_scaled,
y_val,
set_name='Validation'
)
print("\nValidation Set Metrics:")
print(val_results)
return train_results, val_results
# Call the evaluation function
train_metrics, val_metrics = evaluate_models(
model_list,
X_train_scaled,
y_train,
X_val_scaled,
y_val
)
User
i dont want to use classes
Assistant
Here's a version without using classes, focusing on function-based approach:
python
from sklearn.metrics import balanced_accuracy_score, f1_score, precision_score, recall_score
import pandas as pd
import numpy as np
def compute_model_metrics(predict_func, X, y, model_name=''):
"""
Compute performance metrics for a prediction function
Parameters:
- predict_func: Function that returns predictions
- X: Feature matrix
- y: Target vector
- model_name: Name of the model/method
Returns:
- Dictionary of performance metrics
"""
# Make predictions
predictions = predict_func(X)
# Compute metrics
return {
'F1 Score': f1_score(y, predictions, average='weighted'),
'Balanced Accuracy': balanced_accuracy_score(y, predictions),
'Precision': precision_score(y, predictions, average='weighted'),
'Recall': recall_score(y, predictions, average='weighted')
}
def evaluate_models(model_predictions, X_train, y_train, X_val, y_val, model_names):
"""
Evaluate multiple models' performance
Parameters:
- model_predictions: List of prediction functions
- X_train: Training features
- y_train: Training targets
- X_val: Validation features
- y_val: Validation targets
- model_names: List of model names
Returns:
- DataFrames with training and validation metrics
"""
# Compute training metrics
train_metrics = {}
for predict_func, name in zip(model_predictions, model_names):
train_metrics[name] = compute_model_metrics(predict_func, X_train, y_train)
# Compute validation metrics
val_metrics = {}
for predict_func, name in zip(model_predictions, model_names):
val_metrics[name] = compute_model_metrics(predict_func, X_val, y_val)
# Convert to DataFrames
train_df = pd.DataFrame.from_dict(train_metrics, orient='index')
val_df = pd.DataFrame.from_dict(val_metrics, orient='index')
# Print results
print("Training Set Metrics:")
print(train_df)
print("\nValidation Set Metrics:")
print(val_df)
return train_df, val_df
# Example usage (adjust to match your specific implementation)
def knn_predict(X):
return Best_KNN_Classifier.predict(X)
def log_reg_predict(X):
return Best_Log_Reg_Classifier.predict(X)
def decision_tree_predict(X):
return Best_Decision_Tree_Classifier.predict(X)
def random_forest_predict(X):
return Best_Random_Forest_Classifier.predict(X)
# List of prediction functions
model_predictions = [
lambda X: knn_predict(X),
lambda X: log_reg_predict(X),
lambda X: decision_tree_predict(X),
lambda X: random_forest_predict(X)
]
# List of model names
model_names = [
'KNN',
'Logistic Regression',
'Decision Tree',
'Random Forest'
]
# Evaluate models on scaled data
train_metrics, val_metrics = evaluate_models(
model_predictions,
X_train_scaled,
y_train,
X_val_scaled,
y_val,
model_names
)
Created a more flexible compute_model_metrics() function that can work with both training and validation sets.
Added average='weighted' to scoring metrics to handle multi-class classification more robustly.
Used model.__class__.__name__ to get model names dynamically.
Simplified the metric computation process by using a single function.
Added more descriptive print statements to clarify which set's metrics are being displayed.
Returns both train and validation metrics as DataFrames for potential further analysis.
Removed the manual set_axis() method and instead used set_index().
Added docstrings to explain the function's purpose and parameters.
The output will be similar to the original code but with a more structured and flexible approach. The function will print out metrics for both training and validation sets, showing F1 Score, Balanced Accuracy, Precision, and Recall for each model.
Note: Make sure you have the necessary variables (model_list, X_train_scaled, y_train, X_val_scaled, y_val) defined before running this code.
Key differences from the previous version:
Removed class-based approach entirely.
Used function-based prediction methods.
Created a more flexible compute_model_metrics() function that takes a prediction function as an argument.
Added lambda functions to create prediction functions for each model.
Included model names as a separate parameter for better readability.
Maintained the core functionality of computing and displaying metrics for both training and validation sets.
How to use:
Replace the knn_predict, log_reg_predict, etc. functions with your actual prediction methods.
Ensure X_train_scaled, y_train, X_val_scaled, y_val are defined.
The model names can be customized in the model_names list.
This approach provides a more functional programming style while maintaining the same core functionality as the original code. It's more flexible and allows for easy addition or modification of models.