:: ai/tensorflow

tensorflow :: 텐서플로우 ConfigProto (v1 -> v2 코드 업그레이드 8)

토람이 2022. 6. 14. 22:14

ConfigProto

 

텐서플로우에서 configproto 는 연산 방식을 설정하는 기능의 함수다.

tf.session 으로 생성한 세션 내에서

연산을 진행할 때 cpu 를 사용할 것인지, 아니면 gpu 를 사용할 것인지 결정할 수 있다.

 

config = tf.ConfigProto()

# AttributeError: module 'tensorflow' has no attribute 'ConfigProto'

 

위와 같이 호출하며, 이 때 몇몇 인자값들을 지정하면 연산 방식을 설정할 수 있다.

그런데 v2.0 환경에서 ConfigProto 를 사용할 경우

위 주석 내용과 같이 에러가 발생한다.

 

tensorflow v2.0 부터는 더 이상 ConfigProto 를 제공하지 않기 때문이다.

 

 

1. tf.config.experimental 사용

2.x 버전부터는 tf.config.experimental 모듈을 사용하여 학습 방식을 설정할 수 있다.

 

# GPU 설정 방법
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"

physical_devices = tf.config.experimental.list_physical_devices(device_type='GPU')
tf.config.experimental.set_visible_devices(physical_devices[0], 'GPU')
tf.config.experimental.set_memory_growth(physical_devices[0], True) # 메모리 제한


# CPU 설정 방법 1
tf.config.set_visible_devices([], 'GPU')

# CPU 설정 방법 2
physical_devices = tf.config.experimental.list_physical_devices(device_type='CPU')
tf.config.experimental.set_visible_devices(devices= physical_devices, device_type='CPU')

 

위와 같이 CPU 또는 GPU 로 설정할 수 있다.

 

 

1) tf.config.experimental 모듈의 list_physical_devices 함수

Host 머신에 표시되는 CPU 또는 GPU 장치 목록을 불러온다.

 

2) set_visible_devices 함수

학습에 사용할 디바이스를 설정(set)한다.

이 때, 디바이스 타입(CPU or GPU)과 1)에서 불러온 디바이스 정보를 함께 지정한다.

 

 

2. compat 모듈 사용: v1.0 코드 그대로 사용하기

이전 포스팅들에도 언급했듯 compat 모듈을 사용하여 v2.0 기능을 끄도록 설정,

기존 v1.0 코드를 그대로 사용할 수 있다.

 

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

tf.train.Saver().save(session, checkpoint)

 

위처럼 코드 상단에 compat 모듈을 import 하여 v2 기능을 disable 한 후

기존 코드를 그대로 사용하면 된다.

300x250