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

用 Keras 训练时,怎么让 TensorBoard 看到模型图?

先说出你的答案

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

查看完整题解

参考回答

直接回答

用 tf.keras.callbacks.TensorBoard(log_dir=..., write_graph=True) 并传给 model.fit,同时核对当前版本实际产生的文件。对于用 eager 执行或需要精确选择的路径,可以用显式追踪。

讲清原理

图结构是否出现取决于模型执行形态和写入内容。用一次代表性输入跑 forward,比较符合要看的分支。子类模型若无法直接取得结构,优先追踪一段定义明确的 tf.function。

例子与易错点

下面用 Keras 回调跑一轮,再显式记录模型前向函数图,检查日志目录和图事件。

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")
values = np.array([[1.0], [2.0]], dtype="float32")
logger = tf.keras.callbacks.TensorBoard(log_dir=str(root / "fit"), write_graph=True)
model.fit(values, values * 2, epochs=1, verbose=0, callbacks=[logger])
train_log = EventAccumulator(str(root / "fit" / "train")).Reload()
assert "epoch_loss" in train_log.Tags()["tensors"]

forward = tf.function(lambda x: model(x, training=False), autograph=False)
graph = forward.get_concrete_function(tf.TensorSpec([None, 1], tf.float32)).graph
writer = tf.summary.create_file_writer(str(root / "graph"))
with writer.as_default():
    tf.summary.graph(graph)
writer.close()
assert EventAccumulator(str(root / "graph")).Reload().Graph().node
print("Keras event files and an explicit forward graph are readable")

相关题:第 16 题、第 18 题、第 19 题、第 21 题。

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

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