如何优化回归算法R²值打印展示?转为DataFrame实现易读输出
Absolutely! Using a pandas DataFrame is a fantastic way to clean up this output and make the R² scores much easier to compare at a glance. Instead of scattered print statements that force you to scan lines of unstructured text, you’ll get a structured, table-like view that’s far more readable—especially if you plan to add more models later.
Here’s how to refactor your code for this:
First, make sure you have pandas installed (if not, run pip install pandas), then collect your model names and their corresponding R² scores into lists, then build a DataFrame from them:
import pandas as pd from sklearn import metrics # Collect model names and their R² scores model_names = [ "Random Forest", "Bagging Regressor", "Extra Trees Regressor" ] r2_scores = [ metrics.r2_score(y_test, Y_pred_random_forest), metrics.r2_score(y_test, Y_pred_Bagging_Regressor), metrics.r2_score(y_test, Y_pred_Extra_Trees_Regressor) ] # Create DataFrame performance_df = pd.DataFrame({ "Model": model_names, "R² Score": r2_scores }) # Optional: Format scores to 4 decimal places for clarity, and set model as index performance_df = performance_df.set_index("Model").round(4) # Print the result print(performance_df)
This will output a clean table like this:
R² Score Model Random Forest 0.8923 Bagging Regressor 0.8756 Extra Trees Regressor 0.9012
If you want to immediately see which model performs best, you can sort the DataFrame by R² score (descending order):
print(performance_df.sort_values(by="R² Score", ascending=False))
This approach scales seamlessly—if you add more regression models later, you just need to append their name and score to the respective lists, no extra print statements required. It also makes it easy to export the results to a CSV or Excel file if you need to share or analyze them further (using performance_df.to_csv("model_performance.csv")).
内容的提问来源于stack exchange,提问作者Pit_66

