Reputation: 3233
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:
...
Upvotes: 1
Views: 311
Reputation: 4264
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.
Upvotes: 1