简体   繁体   English

如何将自定义指标的值从自定义回调附加到我需要在张量板中使用的“日志”?

[英]How do I append values of a custom metric from a custom Callback to “logs” which I need to use in tensorboard?

I need to implement a custom callback to calculate AUC after every epoch, which I need to use as a metric in LSTM based neural network.我需要实现一个自定义回调来计算每个时期后的 AUC,我需要将其用作基于 LSTM 的神经网络中的指标。 This is the custom callback:这是自定义回调:

from tensorflow.keras.callbacks import Callback
class RocCallback(Callback):
    def __init__(self,training_data,validation_data):
        self.x = training_data[0]
        self.y = training_data[1]
        self.x_val = validation_data[0]
        self.y_val = validation_data[1]

        

    def on_train_begin(self, logs={}):
        self.roc_train_list = []
        self.roc_val_list = []
        self.roc_train=0
        self.roc_val=0
        logs["roc_train"] = []
        logs["roc_val"] = []
        return 


    def on_epoch_end(self, epoch, logs):
        y_pred_train = self.model.predict(self.x)
        roc_train = roc_auc_score(self.y, y_pred_train)
        y_pred_val = self.model.predict(self.x_val)
        roc_val = roc_auc_score(self.y_val, y_pred_val)
        #print('\rroc-auc_train: %s - roc-auc_val: %s' % (str(round(roc_train,4)),str(round(roc_val,4))),end=100*' '+'\n')
        
        # self.history['roc_auc_train'].append(round(roc_train,4))

        # self.history['roc_auc_val'].append(round(roc_val,4))
        self.roc_train = round(roc_train,4)
        self.roc_val = round(roc_val,4) 
        self.roc_train_list.append(self.roc_train)
        self.roc_val_list.append(self.roc_val)
        print("\rroc_train: %f — roc_val: %f" %(self.roc_train, self.roc_val))
        
        logs["roc_train"]= self.roc_train
        logs["roc_val"] = self.roc_val

        return logs

There are two things which aren't working properly:有两件事不能正常工作:

  1. The print("\\rroc_train: %f — roc_val: %f" %(self.roc_train, self.roc_val)) prints just before the epoch progress bar but it needs to print just after eg: print("\\rroc_train: %f — roc_val: %f" %(self.roc_train, self.roc_val))在纪元进度条之前打印但需要在之后打印例如:
Epoch 2/20
roc_train: 0.550000 — roc_val: 0.547800
2561/2561 [==============================] - 89s 35ms/step - loss: 0.5326 - val_loss: 0.4513
Epoch 3/20
roc_train: 0.559800 — roc_val: 0.558000
2561/2561 [==============================] - 88s 34ms/step - loss: 0.5049 - val_loss: 0.4406
  1. The logs in tensorboard only has epoch_loss as metric but no "roc_train" or "roc_val" values. tensorboard 中的日志只有 epoch_loss 作为度量,但没有“roc_train”或“roc_val”值。 I have tried我试过了
logs["roc_train"].append(self.roc_train)
logs["roc_val"].append(self.roc_val)

but it raises a Key Error.但它引发了一个关键错误。

As a quick alternative, have you tried using the built-in https://www.tensorflow.org/api_docs/python/tf/keras/metrics/AUC , metric,作为一种快速的替代方法,您是否尝试过使用内置的https://www.tensorflow.org/api_docs/python/tf/keras/metrics/AUC 、metric、

tf.keras.metrics.AUC(
    num_thresholds=200, curve='ROC', summation_method='interpolation', name=None,
    dtype=None, thresholds=None, multi_label=False, label_weights=None
)

it may solve for the moment your problem.它可以暂时解决您的问题。

Your code is indeed not wrong;你的代码确实没有错; in the callbacks list in model.fit(), could you please place your callback in the first position in the list;在model.fit()的回调列表中,能否请您将回调放在列表的第一个位置; in my case it happened that I wanted once to save to a .csv and the CustomMetric() callback was the last, therefore the .csv was saved only with loss and val_loss not with my custom metrics.就我而言,碰巧我想一次保存到 .csv 并且 CustomMetric() 回调是最后一次,因此 .csv 只保存了 loss 和 val_loss 而不是我的自定义指标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM