对于tensorflow 2.x,如何在CPU和GPU版本之间切换?

时间:2020-06-09 09:19:01

标签: tensorflow anaconda tensorflow2.0

我已经将anaconda更新为最新版本。它同时安装了tensorflow 2.2和tensorflow-gpu 2.2。但是,当我import tensorflow时,tensorflow-gpu是要使用的默认值。有没有办法在它们之间切换?

在此网站上询问的类似问题全部针对1.x版本。我已经尝试了解决方案,但似乎不适用于2.x版本。 Tensor flow toggle between CPU/GPU

2 个答案:

答案 0 :(得分:1)

这应该可以解决您的问题:

with tf.device('/gpu:0'):
    # YOUR def main() OR model.fit()
with tf.device('/cpu:0'):
    # YOUR def main() OR model.fit()

这应该适用于不带会话的TF2。

答案 1 :(得分:0)

另一种方法是:

#use gpu 0
physical_devices = tf.config.list_physical_devices('GPU')
tf.config.set_visible_devices(physical_devices[0], 'GPU')

#use cpu
tf.config.set_visible_devices([], 'GPU')
相关问题