학습 스크립트 구성

텐서보드 로그를 작성하도록 학습 스크립트를 구성해야 합니다. 기존 텐서보드 사용자의 경우 모델 학습 코드를 변경할 필요가 없습니다.

TensorFlow 2.x에서 학습 스크립트를 구성하려면 텐서보드 콜백을 만들고 log_dir 변수를 Google Cloud에 연결할 수 있는 위치로 설정합니다.

그러면 텐서보드 콜백이 TensorFlow model.fit 콜백 목록에 포함됩니다.

import tensorflow as tf

def train_tensorflow_model_with_tensorboard(log_dir):
    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
    x_train, x_test = x_train / 255.0, x_test / 255.0

    def create_model():
        return tf.keras.models.Sequential(
            [
                tf.keras.layers.Flatten(input_shape=(28, 28)),
                tf.keras.layers.Dense(512, activation="relu"),
            ]
        )

    model = create_model()
    model.compile(
        optimizer="adam",
        loss="sparse_categorical_crossentropy",
        metrics=["accuracy"]
    )

    tensorboard_callback = tf.keras.callbacks.TensorBoard(
        log_dir=log_dir,
        histogram_freq=1
    )

    model.fit(
        x=x_train,
        y=y_train,
        epochs=5,
        validation_data=(x_test, y_test),
        callbacks=[tensorboard_callback],
    )

텐서보드 로그는 지정된 디렉터리에 생성되며 텐서보드 로그 업로드 업로드 안내에 따라 Vertex AI 텐서보드 실험에 업로드할 수 있습니다.

더 많은 예시는 텐서보드 오픈소스 문서를 참조하세요.

다음 단계