https://medium.com/@thongonary/how-to-compute-f1-score-for-each-epoch-in-keras-a1acd17715a2

https://datascience.stackexchange.com/questions/13746/how-to-define-a-custom-performance-metric-in-keras/20192

In training a neural network, f1 score is an important metric to evaluate the performance of classification models, especially for unbalanced classes where the binary accuracy is useless (see Accuracy Paradox).

Keras used to implement the f1 score in its metrics; however, the developers decided to remove it in Keras 2.0, since this quantity is evaluated for each batch, which is more misleading than helpful. Fortunately, Keras allows us to access the validation data during training via a Callback function, on which we can extend to compute the desired quantities.

Here is a sample code to compute and print out the f1 score, recall, and precision at the end of each epoch, using the whole validation data:

import numpy as np
from keras.callbacks import Callback
from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score
class Metrics(Callback):
def on_train_begin(self, logs={}):
self.val_f1s = []
self.val_recalls = []
self.val_precisions = [] def on_epoch_end(self, epoch, logs={}):
val_predict = (np.asarray(self.model.predict(self.model.validation_data[0]))).round()
val_targ = self.model.validation_data[1]
_val_f1 = f1_score(val_targ, val_predict)
_val_recall = recall_score(val_targ, val_predict)
_val_precision = precision_score(val_targ, val_predict)
self.val_f1s.append(_val_f1)
self.val_recalls.append(_val_recall)
self.val_precisions.append(_val_precision)
print “ — val_f1: %f — val_precision: %f — val_recall %f” %(_val_f1, _val_precision, _val_recall)
return metrics = Metrics()

on_train_begin is initialized at the beginning of the training. Here we initiate 3 lists to hold the values of the interested quantities, which are computed in on_epoch_end. Later on, we can access these lists as usual instance variables, for example:

print (metrics.val_f1s)

Define the model, and add the callback parameter in the fit function:

model.fit(training_data, training_target, 
validation_data=(validation_data, validation_target),
nb_epoch=10,
batch_size=64,
callbacks=[metrics])

The printout during training would look like this:

Epoch 1/10
32320/32374 [============================>.] - ETA: 0s - loss: 0.0414 - val_f1: 0.375000 - val_precision: 0.782609 - val_recall 0.246575
32374/32374 [==============================] - 23s - loss: 0.0414 - val_loss: 0.0430

That’s it. Have fun training!

How to compute f1 score for each epoch in Keras的更多相关文章

  1. 【tf.keras】实现 F1 score、precision、recall 等 metric

    tf.keras.metric 里面竟然没有实现 F1 score.recall.precision 等指标,一开始觉得真不可思议.但这是有原因的,这些指标在 batch-wise 上计算都没有意义, ...

  2. hihocoder 1522 : F1 Score

    题目链接   时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi和他的小伙伴们一起写了很多代码.时间一久有些代码究竟是不是自己写的,小Hi也分辨不出来了. 于是他实现 ...

  3. 机器学习中的 precision、recall、accuracy、F1 Score

    1. 四个概念定义:TP.FP.TN.FN 先看四个概念定义: - TP,True Positive - FP,False Positive - TN,True Negative - FN,False ...

  4. 机器学习:评价分类结果(F1 Score)

    一.基础 疑问1:具体使用算法时,怎么通过精准率和召回率判断算法优劣? 根据具体使用场景而定: 例1:股票预测,未来该股票是升还是降?业务要求更精准的找到能够上升的股票:此情况下,模型精准率越高越优. ...

  5. F1 score,micro F1score,macro F1score 的定义

    F1 score,micro F1score,macro F1score 的定义 2018年09月28日 19:30:08 wanglei_1996 阅读数 976   本篇博客可能会继续更新 最近在 ...

  6. 机器学习--如何理解Accuracy, Precision, Recall, F1 score

    当我们在谈论一个模型好坏的时候,我们常常会听到准确率(Accuracy)这个词,我们也会听到"如何才能使模型的Accurcy更高".那么是不是准确率最高的模型就一定是最好的模型? 这篇博文会向大家解释 ...

  7. 【笔记】F1 score

    F1 score 关于精准率和召回率 精准率和召回率可以很好的评价对于数据极度偏斜的二分类问题的算法,有个问题,毕竟是两个指标,有的时候这两个指标也会产生差异,对于不同的算法,精准率可能高一些,召回率 ...

  8. [LeetCode] Score of Parentheses 括号的分数

    Given a balanced parentheses string S, compute the score of the string based on the following rule: ...

  9. [Swift]LeetCode856. 括号的分数 | Score of Parentheses

    Given a balanced parentheses string S, compute the score of the string based on the following rule: ...

随机推荐

  1. java kafka 生产者消费者demo

    一.修改kafka   server.porperties的ip是你本机的ip listeners=PLAINTEXT://192.168.111.130:9092 二.生产者的例子 import o ...

  2. 第三方python 加密库 --- cryptography

    1,安装依赖 pip install cryptography 2,生成秘钥 from cryptography.fernet import Fernet #秘钥#随机生成秘钥 cipher_key ...

  3. http请求的基本介绍

    响应码 1xx:接收到请求并且继续处理  ,这个是一瞬间的状态,一般不关注 2xx:请求已被接收,理解,处理,表示正确 3xx:请求重定向 4xx:客户请求语法错误或者请求资源不存在,这个是客户端错误 ...

  4. Java+Selenium 常见问题QA

    一:日期控件二:上传控件三:页面隐藏元素四:弹出窗口的处理五:富文本框编辑器六:元素高亮 一:日期控件selenium不能直接对日期控件操作,可以通过js对日期控件做赋值操作 WebElement i ...

  5. 前端 HTML body标签相关内容 常用标签 标题标签 h1-h6

    标题标签 h1~h6 <h1> - <h6> 标签可定义标题.<h1> 定义最大的标题.<h6> 定义最小的标题. 由于 h 元素拥有确切的语义,因此请 ...

  6. SSIS--(1)

    目标:两组数据比对,A 来源Excel ,B 来源 Sql server DB ,比对合并,取值放入目标 C 中 首先使用工具SSIS包 一,以数据源 A 为准核对B 中是否有A 的数据和计算等动作 ...

  7. Python3学习之路~5.5 sys模块

    用于提供对解释器相关的操作 sys.argv 命令行参数List,第一个元素是程序本身路径 sys.exit(n) 退出程序,正常退出时exit(0) sys.version 获取Python解释程序 ...

  8. Python3学习之路~5.1 模块介绍

    1 定义 模块:用来从逻辑上组织Python代码(变量.函数.类.逻辑:实现一个功能),本质上就是.py结尾的Python文件(文件名:test.py对应的模块名:test). 2 导入方法 impo ...

  9. DevExpress换肤

    procedure TForm1.cxComboBox1PropertiesChange(Sender: TObject); begin // 这个地方必须是UserSkin,不然不会起作用 dxSk ...

  10. 006-UDP用户数据报文协议

    一.概述 用户数据报协议(英语:User Datagram Protocol,缩写为UDP),又称用户数据报文协议,是一个简单的面向数据报的传输层协议,正式规范为RFC 768. 在TCP/IP模型中 ...