Skip to content

Commit 4d1281a

Browse files
michetonuybubnov
authored andcommitted
Add F1 score to metrics (#10)
Add F1 score to metrics.
1 parent aa945a9 commit 4d1281a

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

keras_metrics/metrics.py

+25-1
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ def __call__(self, y_true, y_pred):
191191

192192

193193
class precision(layer):
194-
"""Create a metric for mode's precision calculation.
194+
"""Create a metric for model's precision calculation.
195195
196196
Precision measures proportion of positives identifications that were
197197
actually correct.
@@ -215,3 +215,27 @@ def __call__(self, y_true, y_pred):
215215

216216
div = K.maximum((tp + fp), self.capping)
217217
return truediv(tp, div)
218+
219+
220+
class f1_score(layer):
221+
"""Create a metric for the model's F1 score calculation.
222+
223+
The F1 score is the harmonic mean of precision and recall.
224+
"""
225+
226+
def __init__(self, name="f1_score", **kwargs):
227+
super(f1_score, self).__init__(name=name, **kwargs)
228+
229+
self.pr = precision()
230+
self.rec = recall()
231+
232+
def reset_states(self):
233+
"""Reset the state of the metrics."""
234+
self.pr.reset_states()
235+
self.rec.reset_states()
236+
237+
def __call__(self, y_true, y_pred):
238+
pr = self.precision(y_true, y_pred)
239+
rec = self.recall(y_true, y_pred)
240+
241+
return 2 * truediv(pr * rec, pr + rec)

0 commit comments

Comments
 (0)