keras train_on_batch中合理使用callback进行tensorboard可视化

本文介绍了如何在Keras的train_on_batch方法中利用TensorBoard回调进行训练过程的可视化。通过设置TensorBoard回调参数,如log_dir和histogram_freq,可以观察损失(loss)和其他指标。注意,在使用train_on_batch时,为了生成激活和权重直方图,需要提供实际的验证数据而非数据生成器。

train_on_batch

returns

Scalar training loss
(if the model has a single output and no metrics)
or list of scalars (if the model has multiple outputs
and/or metrics). The attribute model.metrics_names will give you
the display labels for the scalar outputs.

如果模型的输出是单一的并且没有指定指标,那么返回这段训练的损失;
如果模型有多种输出或者多个指标,返回列表
属性model.metrics_names将为您提供标量输出的标签。(可视化时使用)

keras metrics

https://keras.io/metrics/
在这里插入图片描述
metrics[0]是loss,如果metrics中指定的指标与loss函数相同,打印:
在这里插入图片描述

from keras.callbacks import TensorBoard

部分参数:

log_dir: the path of the directory where to save the log
files to be parsed by TensorBoard.
histogram_freq: frequency (in epochs) at which to compute activation
and weight histograms for the layers of the model. If set to 0,
histograms won’t be computed. Validation data (or split) must be
specified for histogram visualizations.
write_graph: whether to visualize the graph in TensorBoard.
The log file can become quite large when
write_graph is set to True.
write_grads: whether to visualize gradient histograms in TensorBoard.
histogram_freq must be greater than 0.
batch_size: size of batch of inputs to feed to the network
for histograms computation.
write_images: whether to write model weights to visualize as
image in TensorBoard.

use

    board = TensorBoard(log_dir=tb_log, histogram_freq=2, batch_size=batch_size, write_images=True)
    board.set_model(model)

实践

def named_logs(metrics_names, logs):
    result = {
   
   }
    for log in zip(metrics_names, logs):
        result[log[0]] = log[1]
    return result

    loss_file = open(os.path.join(workspace, "loss_file.txt"), 'w+'
使用 **TensorBoard** 可以非常直观地可视化深度学习模型的训练过程,包括损失(loss)、准确率(accuracy)、模型结构、权重分布等信息。下面我们将在使用 **TensorFlow/Keras** 构建的神经网络基础上,加入 TensorBoard 的日志记录功能,并展示如何启动 TensorBoard 查看训练过程。 --- ## ✅ 使用 TensorBoard 可视化训练过程 --- ### ✅ 1. 修改模型训练代码以记录 TensorBoard 日志 我们使用 `TensorBoard` 回调函数来记录训练日志。 ```python import numpy as np import pandas as pd import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.callbacks import TensorBoard from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import os from datetime import datetime # 1. 模拟数据(同上) np.random.seed(42) num_samples = 1000 exercise_minutes = np.random.randint(0, 120, num_samples) exercise_type = np.random.choice([0, 1, 2], num_samples, p=[0.5, 0.3, 0.2]) weight = np.random.normal(70, 10, num_samples) bmr = 10 * weight + 6.25 * np.random.normal(170, 10, num_samples) - 5 * np.random.normal(30, 10, num_samples) + np.random.normal(5, 2, num_samples) calories_intake = np.random.normal(2000, 300, num_samples) calories_burned = bmr * 1.2 + exercise_minutes * (2 + exercise_type * 1.5) calorie_deficit = (calories_intake < calories_burned).astype(int) # 转为0/1 # 构建DataFrame data = pd.DataFrame({ 'ExerciseMinutes': exercise_minutes, 'ExerciseType': exercise_type, 'Weight': weight, 'BMR': bmr, 'CaloriesIntake': calories_intake, 'CalorieDeficit': calorie_deficit }) # 2. 特征与标签 X = data[['ExerciseMinutes', 'ExerciseType', 'Weight', 'BMR', 'CaloriesIntake']] y = data['CalorieDeficit'] # 3. 数据标准化 scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # 4. 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42) # 5. 构建Keras模型 model = Sequential([ Dense(64, activation='relu', input_shape=(X_train.shape[1],)), Dense(64, activation='relu'), Dense(1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # 6. 创建 TensorBoard 回调 log_dir = "logs/fit/" + datetime.now().strftime("%Y%m%d-%H%M%S") tensorboard_callback = TensorBoard(log_dir=log_dir, histogram_freq=1) # 7. 训练模型并记录日志 history = model.fit(X_train, y_train, epochs=50, batch_size=32, validation_split=0.2, callbacks=[tensorboard_callback], verbose=0) # 8. 评估模型 test_loss, test_acc = model.evaluate(X_test, y_test, verbose=0) print(f"\n测试集准确率: {test_acc:.2f}") ``` --- ### ✅ 2. 启动 TensorBoard 查看日志 在终端(Terminal)中运行以下命令启动 TensorBoard: ```bash tensorboard --logdir=logs/fit ``` 然后打开浏览器访问: ``` http://localhost:6006 ``` 你将看到 TensorBoard 的界面,包含以下标签: - **Scalars**:显示训练过程中的 loss、accuracy 曲线,包括训练集和验证集。 - **Graphs**:显示模型的网络结构。 - **Histograms**:显示每一层的权重分布变化。 - **Distributions**:显示权重的分布情况。 --- ## 📊 示例 TensorBoard 效果说明: | 标签 | 内容 | |------|------| | **Scalars** | 显示训练和验证的 loss 和 accuracy 曲线,可用于分析是否过拟合或欠拟合 | | **Graphs** | 显示模型结构,帮助确认网络是否按预期构建 | | **Histograms** | 显示各层权重的分布,有助于调试模型训练过程 | | **Images / Distributions** | 可视化数据分布,帮助理解输入数据 | --- ## 💡 小技巧 - 你可以为每次训练创建不同的日志目录,方便对比不同模型的训练效果。 - 结合 `EarlyStopping` 和 `ModelCheckpoint` 可以更高效地训练模型。 - 使用 `tf.keras.callbacks.TensorBoard` 的 `write_images=True` 参数可以可视化权重图像。 --- ## ✅ 示例输出(终端): ```bash Serving TensorBoard on localhost; press CTRL+C to quit. Open your browser and navigate to http://localhost:6006 ``` --- ##
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值