I would like to compute the recall, precision and f-measure of a cross validation test for different classifiers. scikit-learn comes with cross_val_score but unfortunately such method does not return multiple values.
I could compute such measures by calling three times cross_val_score but that is not efficient. Is there any better solution?
By now I wrote this function:
from sklearn import metrics
def mean_scores(X, y, clf, skf):
cm = np.zeros(len(np.unique(y)) ** 2)
for i, (train, test) in enumerate(skf):
clf.fit(X[train], y[train])
y_pred = clf.predict(X[test])
cm += metrics.confusion_matrix(y[test], y_pred).flatten()
return compute_measures(*cm / skf.n_folds)
def compute_measures(tp, fp, fn, tn):
"""Computes effectiveness measures given a confusion matrix."""
specificity = tn / (tn + fp)
sensitivity = tp / (tp + fn)
fmeasure = 2 * (specificity * sensitivity) / (specificity + sensitivity)
return sensitivity, specificity, fmeasure
It basically sums up the confusion matrix values and once you have false positive, false negative etc you can easily compute the recall, precision etc... But still I don't like this solution :)
classification_report? See scikit-learn.org/stable/modules/generated/… - EdChumcross_val_scoreand adapted it to your case. This seems like a perfectly viable option, I don't see how to do it better. Please see my answer on an explanation of the problem and a workaround, in case you feel like modifying sklearn code. - eickenbergcross_val_score3 times won't be very good idea. You have to be careful to use the same test/train sets. - Dror