1、安装conda环境
2、创建tf环境
conda create -n py368 python=3.6 anaconda
3、激活环境
conda activate py368
4、安装tf2.0
pip install tensorflow-gpu==2.0 -i https://pypi.douban.com/simple
使用conda安装cuda和cudnn环境
conda install cudatoolkit=X.X
conda install cudnn=X.X.X
5、测试运行代码
5.1 测试代码
测试代码1
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 不显示等级2以下的提示信息
print('GPU', tf.test.is_gpu_available())
a = tf.constant(2.0)
b = tf.constant(4.0)
print(a + b)
测试代码2
import tensorflow as tf
import timeit
with tf.device('/cpu:0'):
cpu_a = tf.random.normal([10000, 1000])
cpu_b = tf.random.normal([1000, 2000])
print(cpu_a.device, cpu_b.device)
with tf.device('/gpu:0'):
gpu_a = tf.random.normal([10000, 1000])
gpu_b = tf.random.normal([1000, 2000])
print(gpu_a.device, gpu_b.device)
def cpu_run():
with tf.device('/cpu:0'):
c = tf.matmul(cpu_a, cpu_b)
return c
def gpu_run():
with tf.device('/gpu:0'):
c = tf.matmul(gpu_a, gpu_b)
return c
# warm up
cpu_time = timeit.timeit(cpu_run, number=10)
gpu_time = timeit.timeit(gpu_run, number=10)
print('warmup:', cpu_time, gpu_time)
cpu_time = timeit.timeit(cpu_run, number=10)
gpu_time = timeit.timeit(gpu_run, number=10)
print('run time:', cpu_time, gpu_time)
5.2 后台检测GPU使用情况
watch -n 0.1 nvidia-smi
如下图,进行检测
Thu Aug 20 13:48:46 2020
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 440.33.01 Driver Version: 440.33.01 CUDA Version: 10.2 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
| 0 GeForce RTX 208... Off | 00000000:04:00.0 Off | N/A |
| 15% 33C P0 11W / 250W | 0MiB / 11019MiB | 0% Default |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes: GPU Memory |
| GPU PID Type Process name Usage |
|=============================================================================|
| No running processes found |
+-----------------------------------------------------------------------------+
运行代码,可看到第三列GPU计算单元利用百分比大于0,即可正常使用GPU。
若执行GPU返回False,那么就得看Cuda和Cudnn有没有安装对版本。