Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate precision and recall in Keras

I am building a multi-class classifier with Keras 2.02 (with Tensorflow backend),and I do not know how to calculate precision and recall in Keras. Please help me.

like image 468
Jimmy Du Avatar asked Mar 28 '17 17:03

Jimmy Du


People also ask

How precision and recall are calculated?

Consider a model that predicts 150 examples for the positive class, 95 are correct (true positives), meaning five were missed (false negatives) and 55 are incorrect (false positives). We can calculate the precision as follows: Precision = TruePositives / (TruePositives + FalsePositives) Precision = 95 / (95 + 55)

How do you calculate precision in Tensorflow?

If class_id is specified, we calculate precision by considering only the entries in the batch for which class_id is above the threshold and/or in the top-k highest predictions, and computing the fraction of them for which class_id is indeed a correct label.

How do you calculate precision and recall in Python?

The precision is intuitively the ability of the classifier not to label a negative sample as positive. The recall is the ratio tp / (tp + fn) where tp is the number of true positives and fn the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples.


2 Answers

Python package keras-metrics could be useful for this (I'm the package's author).

import keras import keras_metrics  model = models.Sequential() model.add(keras.layers.Dense(1, activation="sigmoid", input_dim=2)) model.add(keras.layers.Dense(1, activation="softmax"))  model.compile(optimizer="sgd",               loss="binary_crossentropy",               metrics=[keras_metrics.precision(), keras_metrics.recall()]) 

UPDATE: Starting with Keras version 2.3.0, such metrics as precision, recall, etc. are provided within library distribution package.

The usage is the following:

model.compile(optimizer="sgd",               loss="binary_crossentropy",               metrics=[keras.metrics.Precision(), keras.metrics.Recall()]) 
like image 147
Yasha Bubnov Avatar answered Sep 20 '22 15:09

Yasha Bubnov


As of Keras 2.0, precision and recall were removed from the master branch. You will have to implement them yourself. Follow this guide to create custom metrics : Here.

Precision and recall equation can be found Here

Or reuse the code from keras before it was removed Here.

There metrics were remove because they were batch-wise so the value may or may not be correct.

like image 35
Dref360 Avatar answered Sep 18 '22 15:09

Dref360