Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

Keras 的 histogram_freq 会记录梯度吗?

先说出你的答案

定义边界、关键机制、一个反例;P8题再补容量、失败与验证。

查看完整题解

参考回答

直接回答

当前 Keras 的 TensorBoard 回调按 epoch 间隔记录权重分布。频率为 0 时关闭,梯度直方图需要自行在反向完成后采样和写入。

讲清原理

固定版本的实现按 0 起始的 epoch 下标判断。因此频率设为 2 时,回调在下标 0、2 等结束处记录。查看结果时要分清回调内部步号与界面习惯的“第几轮”。

例子与易错点

下面在 Keras 3.15.1 中只提供训练样本,仍能读回权重和偏置的直方图。官方参数说明提到验证集,实际行为以版本和写出的摘要为准。要一并比较验证指标,再给 fit 提供验证数据。

from pathlib import Path
from tempfile import TemporaryDirectory

directory = TemporaryDirectory()
root = Path(directory.name)
import tensorflow as tf
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator

import numpy as np

model = tf.keras.Sequential([tf.keras.Input(shape=(1,)), tf.keras.layers.Dense(1)])
model.compile(optimizer="sgd", loss="mse")
data = np.array([[1.0], [2.0]], dtype="float32")
callback = tf.keras.callbacks.TensorBoard(log_dir=str(root), histogram_freq=2,
                                          write_graph=False)
model.fit(data, data, epochs=1, verbose=0, callbacks=[callback])
log = EventAccumulator(str(root / "train")).Reload()
histograms = [tag for tag in log.Tags()["tensors"] if tag.endswith("/histogram")]
assert len(histograms) == 2
assert all(log.Tensors(tag)[0].step == 0 for tag in histograms)
print("weight and bias histograms were recorded at epoch index 0")

相关题:第 47 题、第 48 题、第 50 题、第 59 题、第 60 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。