簡體   English   中英

Tensorboard 未顯示最后一個訓練模型的自定義指標

[英]Tensorboard not showing the custom metric for the last trained model

我正在 python-tensorflow 上訓練一系列模型並在 Tensorboard 上顯示結果。 這最初是在 jupyter notebook 上完成的,但問題顯然也存在於 Colab 上。

除了驗證結果之外,我還想在 Tensorboard 上顯示測試集的評估結果,為此我通過覆蓋on_train_end方法創建了一個自定義回調,該方法調用res = self.model.evalute(x=x_test, y=y_test, batch_size=1)然后tf.summary.scalar將評估結果存儲為標量。 結束所有訓練后,我啟動 tensorboard。 問題是 tensorboard 沒有顯示最后一個模型的度量:給定n模型(其架構在MODELS_ARCH中定義,tensorboard 僅顯示我的前n-1模型的自定義度量值。

這是代碼(在 jupyter notebook 中,有些行不能直接從 python 運行,例如!rm -rf NNlogs/*刪除以前的日志):

import tensorflow as tf
import numpy as np
import os
root_logdir = os.path.join(os.curdir , "NNlogs")

def get_run_logdir(): 
    import time
    run_id = time.strftime("%Y_%m_%d-%H_%M_%S") 
    return os.path.join(root_logdir , run_id)

def create_models():
    names = ['Dense5', 'Dense6', 'Dense7', 'Dense8']
    MODELS_ARCH = [
        [
            tf.keras.layers.Dense(5, activation='tanh')
        ], 
        [
            tf.keras.layers.Dense(6, activation='tanh')

        ],
        [
            tf.keras.layers.Dense(7, activation='tanh')
        ],
        [
            tf.keras.layers.Dense(8, activation='tanh')
        ]
    ]
    models = []
    for el in MODELS_ARCH:
        models.append(tf.keras.Sequential(el))
        models[-1]._name = names[len(models)-1]
    return models

x_train = np.array([[1., 2.,4., 5., 6.,],[1., 4.,0.5, 7., 9.,], [1., 2.6, 1., 5.6, 6.,]])
y_train = np.array([[ 5.5],[6.], [7.]])
x_val = np.array([[1.7, 5.2, 7.6, 5.2, 6.5,],[2.8, 4.2, 0.8, 7.3, 9.4,], [1.8, 8.4, 6.6, 6.6, 9.,]])
y_val = np.array([[ 5.5],[6.8], [7.1]])
x_test = np.array([[5.2, 7.7, 9.5, 10.8, 4.4,],[2.3, 16., 5.7, 8.8, 9.7,], [1.8, 8.4, 7.3, 6.4, 9.,]])
y_test = np.array([[ 5.5],[6.6], [8.1]])

!rm -rf NNlogs/*
lr = 1e-2
models = create_models()

EPOCHS = 10

class OnTrainEndCallback(tf.keras.callbacks.Callback):
    def __init__(self, epochs):
        super(OnTrainEndCallback, self).__init__()
        self.epochs = epochs
    def on_train_end(self, logs=None):
        res = self.model.evaluate(x=x_test, y=y_test, batch_size=1)
        tf.summary.scalar('Model evalutated on test', data=res, step=self.epochs)
        #return res
    
on_train_end_cb = OnTrainEndCallback(EPOCHS)

optimizer = tf.keras.optimizers.Adagrad(lr=1e-2)

histories = []
tests = []
for m in models:
    run_logdir = get_run_logdir() + "_" + m._name
    file_writer = tf.summary.create_file_writer(run_logdir + "/metrics")
    file_writer.set_as_default()
    
    tensorboard_cb = tf.keras.callbacks.TensorBoard(run_logdir, update_freq='epoch') #batch or epoch
    m.compile(loss='mse', optimizer=optimizer)
    history = m.fit(x=x_train, y=y_train, epochs=EPOCHS,
                    validation_data=(x_val, y_val),
                    callbacks=[tensorboard_cb, on_train_end_cb], batch_size=32)
    histories.append(history)
    tests.append(m.evaluate(x=x_test, y=y_test, batch_size=1))

如果我做:

for m in models:
    print(m.name, m.evaluate(x=x_test, y=y_test, batch_size=1, verbose=0))

它打印所有模型的評估結果:

Dense2 43.158206939697266
Dense3 44.55398941040039
Dense4 43.6148681640625
Dense5 48.75056457519531

但是當我啟動張量板時

%load_ext tensorboard
%tensorboard --logdir NNlogs --host localhost

並在左側菜單中選擇所有模型的metrics ,它沒有顯示Dense8模型之一,而顯示的是其他模型。 問題可以從這張圖片中看出,您可以在左下角看到模型的度量已被選擇,但上圖沒有顯示該模型的值(相信它不是縮放)。

此外,我檢查了該模型的文件夾NNlogs ,我可以看到與其他模型一樣,有一個擴展名為*.v2的文件,因此我認為該指標是正確安全的。

在此處輸入圖片說明

按照這個答案,只有當緩沖區已滿tf.summary.create_file_writer才會寫入磁盤。 顯然,當寫入多個模型評估時,緩沖區會被填滿。 因此,在第四次評估時,它將第三次寫入磁盤,並且緩沖區包含第四次,但未滿,這不會寫入磁盤。 要強制刷新緩沖區並將內容寫入磁盤,在for循環之后(在循環之外file_writer.close()調用file_writer.close()就足夠了。

這可能不是您問題的直接答案,但您是否考慮過使用 Aim? 它在可視化指標和分析指標方面更加復雜,但也易於使用/入門: https : //github.com/aimhubio

  • pythonic 快速搜索超過 100 次實驗
  • 按參數對您的指標進行分組和聚合
  • 無縫切換到平行坐標視圖

免責聲明:我是貢獻者。 希望這會有所幫助。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM