可以参考 tf.config.set_visible_devices | TensorFlow v2.14.0 ,相关内容在 https://tf.wiki/zh/basic/tools.html#tf-config-gpu 也有介绍。一个简单的示例程序如下:
import tensorflow as tf
tf.debugging.set_log_device_placement (True) # 设置输出运算所在的设备
cpus = tf.config.list_physical_devices ('CPU') # 获取当前设备的 CPU 列表
tf.config.set_visible_devices (cpus) # 设置 TensorFlow 的可见设备范围为 cpu
A = tf.constant ([[1, 2], [3, 4]])
B = tf.constant ([[5, 6], [7, 8]])
C = tf.matmul (A, B)
print (C)
输出
2020-04-21 11:37:29.007897: I tensorflow/core/common_runtime/eager/execute.cc:573] Executing op MatMul in device /job:localhost/replica:0/task:0/device:CPU:0
tf.Tensor (
[[19 22]
[43 50]], shape=(2, 2), dtype=int32)
当然最保险的办法是新开一个 conda 虚拟环境并且
pip install tensorflow-cpu
,安装仅支持 CPU 的 TensorFlow 版本。