터미널 로그 등을 이용해서 학습 과정을 모니터링 할 경우, 한눈에 학습 과정의 문제점을 파악하기 쉽지 않다.
따라서 TensorFlow 에서는 학습과정 시각화를 위해 TensorBoard 기능을 제공한다.
TensorBoard는 크게 3가지의 API를 제공한다.
① tf.summary.scalar : scalar값 형태의 로그 저장
② tf.summary.histogram : histogram 형태의 로그 저장
③ tf.summary.image : 이미지 형태의 로그 저장
[텐서보드 로그 저장법]
① 인자값으로 텐서보드 로그 파일을 저장할 경로르 지정해서 File Writer 생성
summary_writer = tf.summary.create_file_writer('./tensorboard_log')
② 요약 정보를 남기고 싶은 값을 Writer scope 내에서 tf.summary.* API로 추가
with summary_writer.as_default():
tf.summary.scalar('loss function', loss, step=optimizer.iterations)
="summary_writer를 as_default()로 열어준 다음, 현재 손실함수 값을 loss function이라는 이름으로 저장하고, 현재 iterations 횟수를 step 인자에 넣겠다"
--> epoch 별 손실함수 값이 파일에 저장되며, 이를 불러와 시각화 된 형태로 볼 수 있게 된다.
[텐서보드 실행방법]
터미널에서 명령어 실행
tensorboard --logdir=로그가 저장된 경로
그 후 웹 브라우저에서 실행
URL 창에 localhost:6006 을 입력
이전에 진행했던 'CNN을 이용한 MNIST 숫자 분류기 구현'에 TensorBoard 기능을 추가한 예제이다.
https://these-dayss.tistory.com/139
TensorFlow 2.0을 이용한 MNIST 숫자분류를 위한 CNN 구현
# -*- coding: utf-8 -*- # Convolutional Neural Networks(CNN)을 이용한 MNIST 분류기(Classifier) - Keras API를 이용한 구현 import tensorflow as tf # MNIST 데이터를 다운로드 (x_train, y_train), (x_test..
these-dayss.tistory.com
위의 예제에서 추가 및 수정된 부분만 따로 정리해두었다.
# 텐서보드 summary 정보들을 저장할 폴더 경로를 설정하고 FileWriter를 선언
# trainig 과정에서 발생되는 log를 저장하기 위한 것과 test 과정에서의 log를 저장하기 위한 것을 따로 지정
train_summary_writer = tf.summary.create_file_writer('./tensorboard_log/train')
test_summary_writer = tf.summary.create_file_writer('./tensorboard_log/test')
# 최적화를 위한 function을 정의
@tf.function
def train_step(model, x, y):
with tf.GradientTape() as tape:
y_pred, logits = model(x)
loss = cross_entropy_loss(logits, y)
# 매 step마다 tf.summary.scalar, tf.summary.image 텐서보드 로그를 기록
with train_summary_writer.as_default():
tf.summary.scalar('loss', loss, step=optimizer.iterations) # loss라는 이름으로 현재 iteration time step의 loss값 저장
x_image = tf.reshape(x, [-1, 28, 28, 1]) # flattening된 상태 (784차원)를 다시 28x28 gray scale 이미지로 저장
tf.summary.image('training image', x_image, max_outputs=10, step=optimizer.iterations) # training image라는 이름으로 그 시점에서 뽑힌 랜덤 배치의 mnist 트레이닝 이미지 저장. 저장 크기는 최대 10개로 지정
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
# 모델의 정확도를 출력하는 함수를 정의
@tf.function
def compute_accuracy(y_pred, y, summary_writer): # 정확도 측정함수 인자값에 summary_writer 추가
correct_prediction = tf.equal(tf.argmax(y_pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with summary_writer.as_default():
tf.summary.scalar('accuracy', accuracy, step=optimizer.iterations)
return accuracy
# Convolutional Neural Networks(CNN) 모델을 선언
CNN_model = CNN()
# 10000 Step만큼 최적화를 수행
for i in range(10000):
# 50개씩 MNIST 데이터를 불러옴
batch_x, batch_y = next(train_data_iter)
# 100 Step마다 training 데이터셋에 대한 정확도를 출력
if i % 100 == 0: # 100번의 학습마다 정확도 측정
train_accuracy = compute_accuracy(CNN_model(batch_x)[0], batch_y, train_summary_writer)
print("반복(Epoch): %d, 트레이닝 데이터 정확도: %f" % (i, train_accuracy))
# 옵티마이저를 실행해 파라미터를 한스텝 업데이트
train_step(CNN_model, batch_x, batch_y)
# 학습이 끝나면 학습된 모델의 정확도를 출력. test 데이터셋에 대한 정확도
print("정확도(Accuracy): %f" % compute_accuracy(CNN_model(x_test)[0], y_test, test_summary_writer))
'Study > Deep Learning' 카테고리의 다른 글
Pre-Trained CNN 모델을 이용한 Image Classification (0) | 2021.10.18 |
---|---|
Fine-Tuning(Transfer Learning) (0) | 2021.10.18 |
tf.train.CheckpointManager API (0) | 2021.10.18 |
드롭아웃(Dropout) (0) | 2021.10.17 |
TensorFlow 2.0을 이용한 MNIST 숫자분류를 위한 CNN 구현 (0) | 2021.10.17 |