C.W.K.
Stream
Lesson 02 of 04 · published

tf.summary API — 커스텀 로깅

~11 min · tf-summary, scalars, images, histograms

Level 0Level 0
0 XP0/78 lessons0/17 achievements
0/100 XP to next level100 XP to go0% complete

model.fit이 자동 로깅하는 것 너머

Keras TensorBoard callback은 표준 metric 처리. Custom metric, 샘플 이미지, attention map, embedding projection, model.fit이 안 다루는 거엔 tf.summary API 직접 써.

패턴: writer 만들고, context로 열고, tf.summary.scalar / image / histogram / text에 이름, 값, step 넘겨. Train과 validation log에 별도 writer 써서 dashboard에서 다른 series로 보이게 해.

Code

Custom logging — scalar / image / histogram·python
import tensorflow as tf
import datetime

log_dir = "logs/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
train_writer = tf.summary.create_file_writer(log_dir + "/train")
val_writer   = tf.summary.create_file_writer(log_dir + "/val")

# Scalars (run inside the training loop, per epoch)
with train_writer.as_default():
    tf.summary.scalar("loss",           train_loss,    step=epoch)
    tf.summary.scalar("accuracy",       train_accuracy, step=epoch)
    tf.summary.scalar("learning_rate",  lr_schedule(epoch), step=epoch)

with val_writer.as_default():
    tf.summary.scalar("loss",     val_loss,     step=epoch)
    tf.summary.scalar("accuracy", val_accuracy, step=epoch)

# Images (shape: batch, h, w, channels; values [0,1] or [0,255])
with train_writer.as_default():
    tf.summary.image("training_samples", images, step=epoch, max_outputs=5)

# Histograms — watch weights evolve
with train_writer.as_default():
    for layer in model.layers:
        for weight in layer.weights:
            tf.summary.histogram(weight.name, weight, step=epoch)

# Text — log sample predictions, hparams, anything string-shaped
with train_writer.as_default():
    tf.summary.text("sample", "Predicted: cat, Actual: cat", step=epoch)

train_writer.flush()
val_writer.flush()
Custom training loop + summaries·python
import tensorflow as tf

train_loss_metric = tf.keras.metrics.Mean(name='train_loss')
train_acc_metric  = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
train_writer = tf.summary.create_file_writer("logs/custom_training")

@tf.function
def train_step(x, y):
    with tf.GradientTape() as tape:
        predictions = model(x, training=True)
        loss = loss_fn(y, predictions)
    grads = tape.gradient(loss, model.trainable_weights)
    optimizer.apply_gradients(zip(grads, model.trainable_weights))
    train_loss_metric.update_state(loss)
    train_acc_metric.update_state(y, predictions)

for epoch in range(NUM_EPOCHS):
    train_loss_metric.reset_state()
    train_acc_metric.reset_state()

    for x_batch, y_batch in train_dataset:
        train_step(x_batch, y_batch)

    with train_writer.as_default():
        tf.summary.scalar("loss",     train_loss_metric.result(), step=epoch)
        tf.summary.scalar("accuracy", train_acc_metric.result(),  step=epoch)

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.