求助:TensorFlow 2.2.0不使用compat.v1的GPU调用代码语法
TensorFlow 2.2.0 无compat.v1的GPU调用配置方法
没问题!在TensorFlow 2.2.0里,不用compat.v1的话,GPU显存控制的写法和v1版本完全不同,我给你对应替代方案:
1. 替代per_process_gpu_memory_fraction的固定显存分配写法
如果你想和之前一样,固定占用GPU总显存的30%,可以用虚拟设备配置的方式实现:
import tensorflow as tf # 获取系统中的物理GPU设备 gpus = tf.config.list_physical_devices('GPU') if gpus: # 对目标GPU设置显存限制(这里以第一个GPU为例) # memory_limit的单位是MB,比如你的GPU总显存是10GB,30%就是3072MB tf.config.experimental.set_virtual_device_configuration( gpus[0], [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=3072)] ) print("GPU显存限制已设置为30%")
2. 更推荐的动态显存分配方式
TF2.x更推荐让框架按需分配显存(用多少占多少),这种方式不会浪费显存资源,写法更简单:
import tensorflow as tf gpus = tf.config.list_physical_devices('GPU') if gpus: for gpu in gpus: # 开启动态显存增长 tf.config.experimental.set_memory_growth(gpu, True) print("已开启GPU动态显存分配")
注意事项
- 这些配置代码必须放在所有TensorFlow操作的最开头,否则可能不生效
- TF2.x默认启用Eager Execution,不需要再手动创建
tf.Session来管理GPU资源
你之前使用compat.v1的代码:
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
内容的提问来源于stack exchange,提问作者max2p
相关产品推荐
相关产品推荐

