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

For tensorflow 2.x, how to switch between the CPU and GPU version?

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

本站问的类似问题都是1.x版的。我已经尝试了这些解决方案,但它似乎不适用于 2.x 版本。

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

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

这应该适用于没有会话的 TF2。

另一种方式是:

#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')