Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/ko/tensorboard/graphs.ipynb
25115 views
Kernel: Python 3
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.

개요

TensorBoard의 Graphs 대시보드는 TensorFlow 모델을 검사하기 위한 강력한 도구입니다. 모델 구조의 개념적 그래프를 빠르게 확인하고 설계 의도와 일치하는지 확인할 수 있습니다. 또한 op 수준의 그래프를 보고 TensorFlow가 프로그램을 어떻게 이해하는지 파악할 수 있습니다. Op 수준의 그래프를 검토하면 모델을 어떻게 변경해야 할 것인지에 대한 방향을 잡을 수 있습니다. 예를 들어, 훈련이 예상보다 느리게 진행된다면 모델을 다시 설계할 수 있습니다.

이 튜토리얼에서는 그래프 진단 데이터를 생성하고 TensorBoard의 Graphs 대시보드에서 시각화하는 방법을 간략하게 소개합니다. Fashion-MNIST 데이터세트에 대한 간단한 Keras 순차 모델을 정의 및 훈련하고 모델 그래프를 로깅 및 검사하는 방법을 배울 것입니다. 또한 추적 API를 사용하여, 새로운 tf.function 주석을 사용하여 생성된 함수의 그래프 데이터를 생성합니다.

설정

# Load the TensorBoard notebook extension. %load_ext tensorboard
from datetime import datetime from packaging import version import tensorflow as tf from tensorflow import keras print("TensorFlow version: ", tf.__version__) assert version.parse(tf.__version__).release[0] >= 2, \ "This notebook requires TensorFlow 2.0 or above."
TensorFlow version: 2.2.0
import tensorboard tensorboard.__version__
'2.2.1'
# Clear any logs from previous runs !rm -rf ./logs/

Keras 모델 정의하기

이 예에서 분류자는 단순한 4개 레이어 순차 모델입니다.

# Define the model. model = keras.models.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(32, activation='relu'), keras.layers.Dropout(0.2), keras.layers.Dense(10, activation='softmax') ]) model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

훈련 데이터를 다운로드하고 준비합니다.

(train_images, train_labels), _ = keras.datasets.fashion_mnist.load_data() train_images = train_images / 255.0

모델 훈련 및 데이터 로깅하기

훈련 전에 Keras TensorBoard 콜백을 정의하여 로그 디렉토리를 지정합니다. 이 콜백을 Model.fit()에 전달하면 TensorBoard에서 시각화할 그래프 데이터가 로깅됩니다.

# Define the Keras TensorBoard callback. logdir="logs/fit/" + datetime.now().strftime("%Y%m%d-%H%M%S") tensorboard_callback = keras.callbacks.TensorBoard(log_dir=logdir) # Train the model. model.fit( train_images, train_labels, batch_size=64, epochs=5, callbacks=[tensorboard_callback])
Epoch 1/5 938/938 [==============================] - 2s 2ms/step - loss: 0.6955 - accuracy: 0.7618 Epoch 2/5 938/938 [==============================] - 2s 2ms/step - loss: 0.4877 - accuracy: 0.8296 Epoch 3/5 938/938 [==============================] - 2s 2ms/step - loss: 0.4458 - accuracy: 0.8414 Epoch 4/5 938/938 [==============================] - 2s 2ms/step - loss: 0.4246 - accuracy: 0.8476 Epoch 5/5 938/938 [==============================] - 2s 2ms/step - loss: 0.4117 - accuracy: 0.8508
<tensorflow.python.keras.callbacks.History at 0x7f656ecc3fd0>

Op 수준의 그래프

TensorBoard를 시작하고 UI가 로드될 때까지 몇 초 정도 기다립니다. 상단의 "Graphs"를 탭하여 Graphs 대시보드를 선택합니다.

%tensorboard --logdir logs

선택적으로, TensorBoard.dev를 사용하여 호스팅되고 공유 가능한 실험을 만들 수도 있습니다.

!tensorboard dev upload \ --logdir logs \ --name "Sample op-level graph" \ --one_shot

기본적으로, TensorBoard는 op 수준의 그래프를 표시합니다. 왼쪽에서 "Default" 태그가 선택된 것을 볼 수 있습니다. 그래프가 반전되어 있다는 점에 유의하세요. 데이터는 아래에서 위로 흐르기 때문에 코드와 비교하면 거꾸로 되어 있습니다. 그러나, 그래프가 Keras 모델 정의와 거의 일치하고 다른 계산 노드에 대한 추가 에지를 볼 수 있습니다.

그래프의 크기가 매우 클 수 있기 때문에 그래프 시각화를 조정할 수 있습니다.

  • 스크롤하여 확대 및 축소

  • 끌어서 이동

  • 두 번 클릭하여 노드 확장 전환(노드는 다른 노드의 컨테이너일 수 있음)

노드를 클릭하여 메타데이터를 볼 수도 있습니다. 이를 통해 입력, 출력, 형상 및 기타 세부 정보를 볼 수 있습니다.

개념적 그래프

실행 그래프 외에도 TensorBoard는 개념적 그래프도 표시합니다. 이 그래프는 단순히 Keras 모델의 뷰입니다. 저장된 모델을 재사용하고 해당 구조를 검사하거나 검증하려는 경우에 유용할 수 있습니다.

개념적 그래프를 보려면 "keras" 태그를 선택합니다. 이 예에서는 축소된 순차 노드가 표시됩니다. 모델의 구조를 보려면 노드를 두 번 클릭합니다.


tf.functions의 그래프

지금까지 예제에서는 Keras 레이어를 정의하고 Model.fit()을 호출하여 생성된 Keras 모델의 그래프를 설명했습니다.

Python 계산 함수를 고성능 TensorFlow 그래프로 변환하는 경우와 같이 "autograph"tf.function 주석을 사용해야 하는 상황이 생길 수 있습니다. 이러한 상황에서는 TensorFlow Summary Trace API를 사용하여 TensorBoard에서 시각화하기 위한 서명된 함수를 로깅합니다.

Summary Trace API를 사용하려면 다음을 수행합니다.

  • tf.function으로 함수를 정의하고 주석 달기

  • 함수 호출 위치 바로 앞에서 tf.summary.trace_on() 사용

  • profiler=True를 전달하여 그래프에 프로필 정보(메모리, CPU 시간) 추가

  • 요약 파일 작성기로tf.summary.trace_export()를 호출하여 로그 데이터 저장

그런 다음 TensorBoard를 사용하여 함수가 어떻게 동작하는지 확인할 수 있습니다.

# The function to be traced. @tf.function def my_func(x, y): # A simple hand-rolled layer. return tf.nn.relu(tf.matmul(x, y)) # Set up logging. stamp = datetime.now().strftime("%Y%m%d-%H%M%S") logdir = 'logs/func/%s' % stamp writer = tf.summary.create_file_writer(logdir) # Sample data for your function. x = tf.random.uniform((3, 3)) y = tf.random.uniform((3, 3)) # Bracket the function call with # tf.summary.trace_on() and tf.summary.trace_export(). tf.summary.trace_on(graph=True, profiler=True) # Call only one tf.function when tracing. z = my_func(x, y) with writer.as_default(): tf.summary.trace_export( name="my_func_trace", step=0, profiler_outdir=logdir)
%tensorboard --logdir logs/func

이제 TensorBoard에서 이해하는 방식으로 함수의 구조를 볼 수 있습니다. CPU 및 메모리 통계를 보려면 "Profile" 라디오 버튼을 클릭합니다.