Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access to numbers in classification_report - sklearn

This is a simple example of classification_report in sklearn

from sklearn.metrics import classification_report
y_true = [0, 1, 2, 2, 2]
y_pred = [0, 0, 2, 2, 1]
target_names = ['class 0', 'class 1', 'class 2']
print(classification_report(y_true, y_pred, target_names=target_names))
#             precision    recall  f1-score   support
#
#    class 0       0.50      1.00      0.67         1
#    class 1       0.00      0.00      0.00         1
#    class 2       1.00      0.67      0.80         3
#
#avg / total       0.70      0.60      0.61         5

I want to have access to avg/total row. For instance, I want to extract f1-score from the report, which is 0.61.

How can I have access to the number in classification_report?

like image 782
Hadij Avatar asked Jan 24 '18 08:01

Hadij


People also ask

What is Classification_report in Sklearn?

A Classification report is used to measure the quality of predictions from a classification algorithm. How many predictions are True and how many are False. More specifically, True Positives, False Positives, True negatives and False Negatives are used to predict the metrics of a classification report as shown below.

What is support in metrics Classification_report?

support. Support is the number of actual occurrences of the class in the specified dataset. Imbalanced support in the training data may indicate structural weaknesses in the reported scores of the classifier and could indicate the need for stratified sampling or rebalancing.


2 Answers

you can use precision_recall_fscore_support for getting all at once

from sklearn.metrics import precision_recall_fscore_support as score
y_true = [0, 1, 2, 2, 2]
y_pred = [0, 0, 2, 2, 1]
precision,recall,fscore,support=score(y_true,y_pred,average='macro')
print 'Precision : {}'.format(precision)
print 'Recall    : {}'.format(recall)
print 'F-score   : {}'.format(fscore)
print 'Support   : {}'.format(support)

here is the link to the module

like image 148
Pratik Kumar Avatar answered Sep 19 '22 17:09

Pratik Kumar


You can output the classification report as dict with:

report = classification_report(y_true, y_pred, **output_dict=True** )

And then access its single values as in a normal python dictionary.

For example, the macro metrics:

macro_precision =  report['macro avg']['precision'] 
macro_recall = report['macro avg']['recall']    
macro_f1 = report['macro avg']['f1-score']

or Accuracy:

accuracy = report['accuracy']
like image 31
Rmobdick Avatar answered Sep 19 '22 17:09

Rmobdick