如何在 tf.keras 中不使用 sklearn 计算宏 f1-score

问题描述 投票:0回答:0

我必须在 tf.keras 中计算宏 f1-score,条件是,不要使用 sklearn

我试过但没有得到输出

首先我尝试计算测试数据

class Metrics(tf.keras.callbacks.Callback):
  def __init__(self,train_data,val_data):
    self.train_data = train_data
    self.validation_data = val_data
  
  def on_train_begin(self,logs={}):
    self.f1_score_test = []
    #self.f1_score_train = []
  
  def on_epoch_end(self,epoch,logs={}):
    y_pred_test = (np.asarray(self.model.predict(self.validation_data[0]))).round()
    y_true_test = self.validation_data[1]
    def f1(y_true_test, y_pred_test):
      TP = np.sum(np.multiply([i==True for i in y_pred_test], y_true_test))
      TN = np.sum(np.multiply([i==False for i in y_pred_test], [not(j) for j in y_true_test]))
      FP = np.sum(np.multiply([i==True for i in y_pred_test], [not(j) for j in y_true_test]))
      FN = np.sum(np.multiply([i==False for i in y_pred_test], y_true_test))
      precision = TP/(TP+FP)
      recall = TP/(TP+FN)
      if precision != 0 and recall != 0:
        f1 = (2 * precision * recall) / (precision + recall)
      else:
        f1 = 0
      return f1

    def f1_macro(y_true_test, y_pred_test):  
      macro = []
      for i in np.unique(y_true_test):
        modified_true = [i==j for j in y_true_test]
        modified_pred = [i==j for j in y_pred_test]
        F1_score_test = f1(modified_true, modified_pred)

      self.f1_score_test.append(F1_score_test)
      #self.f1_score_train.append(F1_score_train) 

      print('f1_test = {}:'.format(F1_score_test))
new_metrics = Metrics((x_train,y_train),(x_test,y_test))
python function callback tf.keras
© www.soinside.com 2019 - 2024. All rights reserved.