安装与测试
TensorFlow2.0安装:
pip install tensorflow-gpu==2.2.0 -i https://pypi.douban.com/simple/
conda install cudnn=7.6.0
# conda install cudatoolkit=10.0.130 # (可选)
TensorFlow2.0的GPU版本测试代码如下:
import tensorflow as tf
print('GPU', tf.test.is_gpu_available())
a = tf.constant(2.0)
b = tf.constant(4.0)
print(a + b)
注意:如果是第一次使用 tensorflow2.0,会在输出 Adding visible gpu devices: 0 之后卡住一阵子,等几分钟就好了,下次运行就正常了。
结果如下就证明 tensorflow-gpu 安装成功了
GPU True
tf.Tensor(6.0, shape=(), dtype=float32)
1.X 和 2.X 版本的差异
Eager Execution
细心的你会发现,在 tensorflow2.0 版本中,居然可以直接输出张量的计算结果,如果是以前的1.x 版本,执行同样的代码,你得到的输出是:
GPU True
Tensor(“add:0”, shape=(), dtype=float32)
在1.x 版本中,如果你想要得到真实的计算结果,需要初始化全局变量 → 建立会话 → 执行计算,最终才能打印出张量的运算结果:
import tensorflow as tf
sess = tf.Session()
a = tf