有些场景下,比如GPU版本运行失败或其它原因,需要强制tensorflow使用CPU,这里提供两种方法,仅针对tensorflow2
1 方法一
import tensorflow as tf
cpu=tf.config.list_physical_devices("CPU")
tf.config.set_visible_devices(cpu)
print(tf.config.list_logical_devices())
[LogicalDevice(name='/device:CPU:0', device_type='CPU')]
2022-08-03 18:36:09.236880: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 AVX512F FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2 方法二
import os
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
import tensorflow as tf
print(tf.config.list_logical_devices())
[LogicalDevice(name='/device:CPU:0', device_type='CPU')]
2022-08-03 18:36:49.283111: E tensorflow/stream_executor/cuda/cuda_driver.cc:271] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected
2022-08-03 18:36:49.283162: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: ai-X785-G30
2022-08-03 18:36:49.283169: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: ai-X785-G30
2022-08-03 18:36:49.283260: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:200] libcuda reported version is: 470.57.2
2022-08-03 18:36:49.283283: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:204] kernel reported version is: 470.57.2
2022-08-03 18:36:49.283290: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:310] kernel version seems to match DSO: 470.57.2
2022-08-03 18:36:49.283639: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 AVX512F FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.