Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

python - How to write a for loop for multiple machine learning metrics if one metric requires a parameter specification?

I created a for loop for generating metrics on my train and test set. However, in order to calculated Root Mean Square Error (RMSE), I need to either 1) take the sqrt of Mean Square Error or 2) set the parameter mean_squared_error(squared = False). However, I only want a parameter for the RMSE, not for the MAE or the R2.

If I try the below I, understandably, get an error TypeError: mean_squared_error() missing 2 required positional arguments: 'y_true' and 'y_pred' because the parentheses should only come in the for loop.

from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error

#Metrics on train and test
metrics = {
    'RMSE' : mean_squared_error,
    'MAE' : mean_absolute_error,
    'R2' : r2_score
}
    #Train and Test
for key in metrics:
    i = metrics[key]
    train_score = i(y_train, train_predictions)
    test_score = i(y_test, y_pred)
    print(f'Train set {key}: {train_score:.4f}')
    print(f'Test set {key}: {test_score:.4f}')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It works fine for me both in Python 2.7.16 and python 3.7.4 and sklearn version 0.20.3 (does not have the "squared" argument but for that issue it can be solved in a various number of ways in the for loop, the most straightforward is a condition on the key:

for key in metrics:
   i = metrics[key]
   if key == "RMSE":
      train_score = i(y_train, train_predictions, squared=False)
      test_score = i(y_test, y_pred, squared=False)
   else:
      train_score = i(y_train, train_predictions)
      test_score = i(y_test, y_pred)

You can try with those versions, i do not see why your code should not work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...