TensorBoard入门指南:30秒快速上手

本文介绍了机器学习工具TensorBoard,它可提供机器学习工作流所需的测量和可视化。文中以mnist为例,讲解了如何快速开始使用TensorBoard,包括建立模型、在model.fit中使用、页面展现、仪表板作用等内容,还说明了如何继续用仪表盘查看算法调动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何快速开始使用TensorBoard

安装TensorBoard

确保已安装TensorFlow或PyTorch(两者均支持TensorBoard)。使用pip安装TensorBoard:

pip install tensorboard

若使用PyTorch,需额外安装torch.utils.tensorboard

pip install torch-tb-profiler

集成到代码中

TensorFlow示例

import tensorflow as tf
# 定义模型和日志目录
log_dir = "logs/fit"
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
# 在model.fit中调用
model.fit(x_train, y_train, epochs=5, callbacks=[tensorboard_callback])

PyTorch示例

from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter("runs/experiment_1")
# 记录标量数据(如损失)
writer.add_scalar("Loss/train", loss.item(), epoch)
writer.close()

启动TensorBoard

在终端运行以下命令,指定日志目录:

tensorboard --logdir=logs/fit  # TensorFlow示例路径
# 或
tensorboard --logdir=runs      # PyTorch示例路径

默认访问地址为 http://localhost:6006

查看可视化数据

  • 标量图表:监控损失、准确率等指标。
  • 计算图:展示模型结构(需在代码中显式保存)。
  • 直方图:显示权重/梯度分布(需设置histogram_freq)。
  • 投影器:可视化高维数据(如嵌入向量)。

高级功能

  • 超参数调优:使用hparams插件记录超参数组合。
  • 性能分析:PyTorch需配合torch.profiler生成性能报告。
  • 自定义仪表盘:通过标签分组指标,筛选关键结果。

注意:若无法访问6006端口,可通过--port参数修改(如--port 6007)。

使用mnist的例子进行TensorBoard例子

建立模型

mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

def create_model():
  return tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation='softmax')
  ])

项目的目录需要建立一个logs/fit目录,手工建立即可。model训练时候,会有回调callBacks=[tensortboard_callback]将日志按照时间搓的写入到文件夹中的文件中。

model = create_model()
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)

model.fit(x=x_train, 
          y=y_train, 
          epochs=5, 
          validation_data=(x_test, y_test), 
          callbacks=[tensorboard_callback])

运行记录截取部分。生成的目录文件夹截取

boston_housing module: Boston housing price regression dataset. cifar10 module: CIFAR10 small images classification dataset. cifar100 module: CIFAR100 small images classification dataset. fashion_mnist module: Fashion-MNIST dataset. imdb module: IMDB sentiment classification dataset. mnist module: MNIST handwritten digits dataset. reuters module: Reuters topic classification dataset. import tensorflow as tf from tensorflow import keras fashion_mnist = keras.datasets.fashion_mnist (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() mnist = keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() cifar100 = keras.datasets.cifar100 (x_train, y_train), (x_test, y_test) = cifar100.load_data() cifar10 = keras.datasets.cifar10 (x_train, y_train), (x_test, y_test) = cifar10.load_data() imdb = keras.datasets.imdb (x_train, y_train), (x_test, y_test) = imdb.load_data() # word_index is a dictionary mapping words to an integer index word_index = imdb.get_word_index() # We reverse it, mapping integer indices to words reverse_word_index = dict([(value, key) for (key, value) in word_index.items()]) # We decode the review; note that our indices were offset by 3 # because 0, 1 and 2 are reserved indices for "padding", "start of sequence", and "unknown". decoded_review = ' '.join([reverse_word_index.get(i - 3, '?') for i in x_train[0]]) print(decoded_review) boston_housing = keras.datasets.boston_housing (x_train, y_train), (x_test, y_test) = boston_housing.load_data() reuters= keras.datasets.reuters (x_train, y_train), (x_test, y_test) = reuters.load_data() tf.keras.datasets.reuters.get_word_index( path='reuters_word_index.json' )
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KENYCHEN奉孝

您的鼓励是我的进步源泉

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值