在Pytorch和Keras等框架上自由使用tensorboard

前言

在這篇博文中,將向你展示如何自由的在任何Python代碼中使用Tensorboard。

最近身邊的一些朋友們都開始從tensorflow轉(zhuǎn)戰(zhàn)Pytorch等,Tensorflow使用靜態(tài)編譯的計(jì)算圖并在單獨(dú)的運(yùn)行時(shí)環(huán)境中運(yùn)行大部分應(yīng)用程序,與Tensorflow相比,PyTorch允許你完全使用Python創(chuàng)建動(dòng)態(tài)計(jì)算圖,單單動(dòng)態(tài)調(diào)試這一點(diǎn)就欲罷不能(真香警告)。

但是tensorflow的孿生兄弟tensorboard實(shí)在是有點(diǎn)讓人難以舍棄。對(duì)于那些不了解Tensorboard的人來(lái)說(shuō),它是一個(gè)可視化工具,用于計(jì)算圖形,學(xué)習(xí)進(jìn)度,神經(jīng)網(wǎng)絡(luò)權(quán)重或您可能需要在一個(gè)漂亮的基于Web的環(huán)境中繪制的任何內(nèi)容。 Tensorboard從命令行作為(基于Python)Web服務(wù)器運(yùn)行。它讀取外部代碼生成的.event文件(如Tensorflow或本文中顯示的代碼),并在瀏覽器中顯示它們。事實(shí)上,在任何其他深度學(xué)習(xí)框架中,還沒(méi)有Tensorboard的任何替代方案。

tensorboard類的實(shí)現(xiàn)

Tensorboard提供以下基本功能:

  • 可視化Tensorflow圖
  • 繪制一個(gè)簡(jiǎn)單的值(如學(xué)習(xí)率)
  • 繪制圖像(例如激活圖)
  • 繪制直方圖。

第一個(gè)功能在實(shí)現(xiàn)上較為麻煩,但是我們可以很簡(jiǎn)單的實(shí)現(xiàn)后三個(gè)功能。直接上代碼,后文列出詳細(xì)解釋:

import io
import numpy as np
from PIL import Image
import tensorflow as tf
import skimage
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt

class Tensorboard:
    def __init__(self, logdir):
        self.writer = tf.summary.FileWriter(logdir)

    def close(self):
        self.writer.close()

    def log_scalar(self, tag, value, global_step):
        summary = tf.Summary()
        summary.value.add(tag=tag, simple_value=value)
        self.writer.add_summary(summary, global_step=global_step)
        self.writer.flush()

    def log_histogram(self, tag, values, global_step, bins):
        counts, bin_edges = np.histogram(values, bins=bins)

        hist = tf.HistogramProto()
        hist.min = float(np.min(values))
        hist.max = float(np.max(values))
        hist.num = int(np.prod(values.shape))
        hist.sum = float(np.sum(values))
        hist.sum_squares = float(np.sum(values ** 2))

        bin_edges = bin_edges[1:]

        for edge in bin_edges:
            hist.bucket_limit.append(edge)
        for c in counts:
            hist.bucket.append(c)

        summary = tf.Summary()
        summary.value.add(tag=tag, histo=hist)
        self.writer.add_summary(summary, global_step=global_step)
        self.writer.flush()

    def log_image(self, tag, img, global_step):
        s = io.BytesIO()
        Image.fromarray(img).save(s, format='png')

        img_summary = tf.Summary.Image(encoded_image_string=s.getvalue(),
                                       height=img.shape[0],
                                       width=img.shape[1])

        summary = tf.Summary()
        summary.value.add(tag=tag, image=img_summary)
        self.writer.add_summary(summary, global_step=global_step)
        self.writer.flush()

    def log_plot(self, tag, figure, global_step):
        plot_buf = io.BytesIO()
        figure.savefig(plot_buf, format='png')
        plot_buf.seek(0)
        img = Image.open(plot_buf)
        img_ar = np.array(img)

        img_summary = tf.Summary.Image(encoded_image_string=plot_buf.getvalue(),
                                       height=img_ar.shape[0],
                                       width=img_ar.shape[1])

        summary = tf.Summary()
        summary.value.add(tag=tag, image=img_summary)
        self.writer.add_summary(summary, global_step=global_step)
        self.writer.flush()


if __name__ == '__main__':
    tensorboard = Tensorboard('logs')
    x = np.arange(1, 101)
    y = 20 + 3 * x + np.random.random(100) * 100

    # Log simple values
    for i in range(0, 100):
        tensorboard.log_scalar('value', y[i], i)

    # Log images
    img = Image.open('/mnt/sda1/lvv/84504.jpg')
    img = np.asarray(img, dtype=np.uint8)
    # img = skimage.io.imread('/mnt/sda1/lvv/84504.jpg')
    tensorboard.log_image('example_image', img, 0)

    # Log plots
    fig = plt.figure()
    plt.plot(x, y, 'o')

    tensorboard.log_plot('example_plot', fig, 0)
    plt.close()
    # Log histograms
    rng = np.random.RandomState(10)
    a = np.hstack((rng.normal(size=1000), rng.normal(loc=5, scale=2, size=1000)))
    tensorboard.log_histogram('example_hist', a, 0, 'auto')

    tensorboard.close()

首先,建立一個(gè)tensorboard類,包含四個(gè)重要函數(shù):log_scalar,log_image,log_plot和log_histogram。 我們將關(guān)注的也是這四個(gè)函數(shù)。 這些函數(shù)可以實(shí)現(xiàn)上文敘述的功能。

在程序的main部分,簡(jiǎn)單的演示了這些函數(shù)的用法。 其余的代碼非常簡(jiǎn)單:Tensorboard類通過(guò)調(diào)用其構(gòu)造函數(shù)來(lái)初始化,其中包含日志目錄的路徑。 構(gòu)造函數(shù)依次初始化FileWriter對(duì)象。 在程序結(jié)束時(shí),我們必須再次關(guān)閉FileWriter。

log_scalar,log_image,log_plot和log_histogram函數(shù)都將tag和global_step作為參數(shù)。 tag是要繪制的值的任意名稱。 例如,你可以為loss函數(shù)設(shè)置tag ='loss'。 global_step指的是測(cè)量特定值的時(shí)間,例如時(shí)期計(jì)數(shù)或類似值。 此外,log_scalar接受數(shù)值作為其第二個(gè)參數(shù)。 這是log_scalar生成的示例標(biāo)量圖:

plot

log_image是一個(gè)類似的簡(jiǎn)單函數(shù),它將一個(gè)numpy數(shù)組作為img參數(shù)來(lái)繪制任意圖像(例如下面的例子):

在這里插入圖片描述

log_histogram稍微復(fù)雜一些:它使用bin的bin數(shù)來(lái)計(jì)算values參數(shù)中給出的值的直方圖。 計(jì)算本身就是numpy。 然后,它被送到Tensorboard:

在這里插入圖片描述

log_plot與log_image非常相似,只是提供的輸入不是image,它的figure參數(shù)需要是一個(gè)matplotlib圖。 使用此函數(shù),你可以直接在Tensorboard中顯示任意matplotlib figures :


在這里插入圖片描述

使用tensorboard

當(dāng)程序 運(yùn)行完成后,會(huì)在代碼所在的文件夾下創(chuàng)建一個(gè)/logs文件夾,里面有一個(gè)events格式的文件,

在這里插入圖片描述

在瀏覽器中打開tensorboard的正確姿勢(shì)如下:
在當(dāng)前目錄下打開終端,輸入命令:

$tensorboard  --logdir=logs   

如果出現(xiàn)錯(cuò)誤,端口不可用等情況,可以指定port參數(shù)或者h(yuǎn)ost參數(shù)等,參考示例:

$tensorboard --logdir=logs  --host=127.0.01  --port=8008

之后就會(huì)運(yùn)行出現(xiàn)一個(gè)網(wǎng)絡(luò)鏈接,復(fù)制粘貼到(google)瀏覽器中就可以。

注: 本文編譯自 https://becominghuman.ai/logging-in-tensorboard-with-pytorch-or-any-other-library-c549163dee9e 內(nèi)容和代碼有刪改。

原文作者希望通過(guò)這篇博文,幫助其他人在切換到另一個(gè)框架時(shí)可以同樣使用tensorboard,而不受任何限制。 作者的GitLab上也有其他有趣的代碼和項(xiàng)目,感興趣的可以查看以下鏈接:https://gitlab.com/branislav.hollander 其中就包括了作者寫的tensorboard使用代碼,但是原代碼中有一些錯(cuò)誤,運(yùn)行會(huì)出現(xiàn)錯(cuò)誤,筆者參考大佬的代碼做了一些修改,修復(fù)了這些bug,修改后的代碼詳見(jiàn)下述鏈接:https://github.com/LDOUBLEV/Tensorboard

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容