环境变量解决方案不适用于我运行 tensorflow 2.3.1。我假设 github 线程中的 cmets 以下解决方案适用于 >=2.1.0 的版本。
来自tensorflow github:
import tensorflow as tf
# Hide GPU from visible devices
tf.config.set_visible_devices([], 'GPU')
确保在导入新的 tensorflow 实例后立即执行此操作(如果您正在运行 jupyter notebook,请重新启动内核)。
并检查您是否确实在 CPU 上运行:
# To find out which devices your operations and tensors are assigned to
tf.debugging.set_log_device_placement(True)
# Create some tensors and perform an operation
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
print(c)
预期输出:
2.3.1
Executing op MatMul in device /job:localhost/replica:0/task:0/device:CPU:0
tf.Tensor(
[[22. 28.]
[49. 64.]], shape=(2, 2), dtype=float32)