Colab 에서는 런타임 유형을 TPU로 변환한다고 해서, Tensorflow 사용 시 자동으로 TPU를 사용하지 않습니다.
기본적으로 CPU를 사용하며, TPU를 사용하려면 아래와 같은 추가 설정이 필요합니다.
TPU 클러스터 연결과 초기화
import osimport tensorflow as tf
TPU_PATH = f"grpc://{os.environ['COLAB_TPU_ADDR']}"resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu=TPU_PATH)tf.config.experimental_connect_to_cluster(resolver)tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.experimental.TPUStrategy(resolver)
with strategy.scope():mlp = create_model()mlp.compile(loss='mse', optimizer=Adam(learning_rate=0.001), metrics=['accuracy'])hist = mlp.fit(x_train, y_train, batch_size=128, epochs=30, validation_data=(x_test, y_test), verbose=2)
def create_model():mlp = Sequential()mlp.add(Dense(units=n_hidden1, activation='tanh', input_shape=(n_input,)))mlp.add(Dense(units=n_hidden2, activation='tanh'))mlp.add(Dense(units=n_hidden3, activation='tanh'))mlp.add(Dense(units=n_hidden4, activation='tanh'))mlp.add(Dense(units=n_output, activation='tanh'))return mlp