1、卸载已安装的TensorFlow
pip uninstall tensorboard
pip uninstall tensorflow-gpu
(tensorflow-estimator、tensorboard、tensorflow、keras-applications、keras-preprocessing),不然后续安装了tensorflow-gpu可能会出现找不到cuda的问题
或者,重新建环境
(1)删除环境:
conda remove -n myenv_ten_new --all
(2)新建环境:
conda create -n tensor_gpu python=3.7
查看环境:
conda env list(conda info -e)
清华源命令:
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/pro/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2/
conda config --set show_channel_urls yes
安装命令:
conda install tensorflow-gpu==2.2.0
# 或者:
pip install tensorflow-gpu==2.2.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
一般需要cuda是10.1或者以上就可以了。
然后一句代码安装:
conda install cudatoolkit=10.1 cudnn=7.6.5
tensorflow-gpu对应的cuda版本网https://tensorflow.google.cn/install/source_windows
安装好后测试下,测试代码;
import tensorflow as tf
import timeit
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 代码用于忽略级别 2 及以下的消息(级别 1 是提示,级别 2 是警告,级别 3 是错误)。
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)
print('GPU', tf.test.is_gpu_available())
结果:
warmup: 1.1624844 1.8189751
run time: 1.1631149999999995 0.0005907000000000551
GPU True
这样就安装成功了!
另外推荐个自动补全插件,很好用,TabNine,安装方法链接如下:
Code Faster with AI Code Completions | Tabnine
参考:简单利用conda安装tensorflow-gpu=2.2.0_爱听许嵩歌的博客-CSDN博客_conda安装tensorflow gpu