Regression score with metric as an argument in sklearn

Question:

I am looking for sklearn solution to get regression score without knowing metric beforehand so I can do something like

score = regression_score(y_true, y_pred, metric="mean_squared_error")

right now I am using multiple if statements and calls to different functions that looks ugly, e.g

if metric == "mean_squared_error":
   score = sklearn.metrics.mean_squared_error(y_true, y_pred)
if metric == "neg_mean_squared_error:
   ...
Asked By: YohanRoth

||

Answers:

You can make use of getattr to load the required function. Please use the modified function below:

import sklearn.metrics

def regression_score(y_true, y_pred, metric):
    function = getattr(sklearn.metrics, metric)
    return function(y_true, y_pred)

SAMPLE OUTPUT

import numpy as np
y_true = np.array([2,3,4,1])
y_pred = np.array([1,3,1,2])

regression_score(y_true,y_pred,"mean_absolute_error")
1.25

regression_score(y_true,y_pred,"mean_squared_error")
2.75

So basically you just have one function without the if conditions which will do your job.

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.