CSDN原文参考:点击这里进入
参考文献:完美解决tensorflow 2.1.0 下执行sess =Session ()出错的情况
方法一:
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
方法二:
进入python, tensorflow 环境
Mac OS terminal, type:
python
import tensorflow as tf
tf. __ version__ (注意:是两个下划线),这个命令查看当前已安装tensorflow的版本
tf. __ path__ (注意:是两个下划线),这个命令查看当前已安装tensorflow的安装目录
import tensorflow as tf
print(tf.__version__)
方法三:
直接使用代码生成:
主要是在session里添加:config=tf.compat.v1.ConfigProto(log_device_placement=True)就可以打印出是CPU还是GPU了。
import tensorflow as tf
tf.compat.v1.disable_eager_execution()#保证sess.run()能够正常运行
hello = tf.constant('hello,tensorflow')
sess= tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))#版本2.0的函数
print(sess.run(hello))
执行结果出现Your CPU supports instructions说明是CPU,否则是GPU
2020-11-15 12:16:24.624807: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
2020-11-15 12:16:24.627359: I tensorflow/core/common_runtime/direct_session.cc:359] Device mapping:
b'hello,tensorflow'
2020-11-15 12:16:24.650728: I tensorflow/core/common_runtime/placer.cc:54] Const: (Const): /job:localhost/replica:0/task:0/device:CPU:0
Process finished with exit code 0
或者计算几个例子:
import numpy
import tensorflow.compat.v1 as tf
tf.disable_eager_execution()#保证sess.run()能够正常运行
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print(sess.run(c))
执行结果:
Device mapping: no known devices.
MatMul: (MatMul): /job:localhost/replica:0/task:0/device:CPU:0
a: (Const): /job:localhost/replica:0/task:0/device:CPU:0
b: (Const): /job:localhost/replica:0/task:0/device:CPU:0
[[22. 28.]
[49. 64.]]
Process finished with exit code 0