简体   繁体   中英

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. 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:
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. 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,

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; 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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