当前位置 : 主页 > 编程语言 > python >

在keras里面实现计算f1-score的代码

来源:互联网 收集:自由互联 发布时间:2021-04-02
我就废话不多说了,大家还是直接看代码吧! ### 以下链接里面的codeimport numpy as npfrom keras.callbacks import Callbackfrom sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_scoreclass Metri

我就废话不多说了,大家还是直接看代码吧!

### 以下链接里面的code
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()
model.fit(
 train_instances.x,
 train_instances.y,
 batch_size,
 epochs,
 verbose=2,
 callbacks=[metrics],
 validation_data=(valid_instances.x, valid_instances.y),
)

补充知识:Keras可使用的评价函数

1:binary_accuracy(对二分类问题,计算在所有预测值上的平均正确率)

binary_accuracy(y_true, y_pred)

2:categorical_accuracy(对多分类问题,计算在所有预测值上的平均正确率)

categorical_accuracy(y_true, y_pred)

3:sparse_categorical_accuracy(与categorical_accuracy相同,在对稀疏的目标值预测时有用 )

sparse_categorical_accuracy(y_true, y_pred)

4:top_k_categorical_accuracy(计算top-k正确率,当预测值的前k个值中存在目标类别即认为预测正确 )

top_k_categorical_accuracy(y_true, y_pred, k=5)

5:sparse_top_k_categorical_accuracy(与top_k_categorical_accracy作用相同,但适用于稀疏情况)

sparse_top_k_categorical_accuracy(y_true, y_pred, k=5)

以上这篇在keras里面实现计算f1-score的代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。

网友评论