這裡分類和匯總了欣宸的全部原創(含配套源碼):https://github.com/zq2599/blog_demos
本篇概覽本篇記錄了自己在Ubuntu 16.04.7 LTS系統上搭建TensorFlow2開發環境的過程,用於將來重裝時的參考硬體是2018年購買的惠普暗隱精靈3代,顯卡GTX1060,已經安裝了Ubuntu16 LTS桌面版查看驅動信息,如下圖,可見CUDA版本是10.1版本匹配去tensorflow官網查看版本匹配關係,地址:https://tensorflow.google.cn/install/source如下圖,在我的電腦上有三個合適的版本:安裝下載anaconda3,地址:https://www.anaconda.com/products/individual,如下圖,可見官方最新版本對應的Python是3.8,符合前面的TensorFlow版本匹配表中的Python版本,所以,就下載最新版吧(此刻是2021.05版)
由於個人習慣,我的操作都是在MacBook上遠程SSH到Ubuntu16電腦上操作的,和在本地執行命令行並無區別,您可以隨意
chmod a+x Anaconda3-2021.05-Linux-x86_64.shbash Anaconda3-2021.05-Linux-x86_64.sh
按照提示輸入回車:翻閱文檔,按照要求輸入yes:是否初始化,輸入yes:安裝完成:退出ssh重新登錄,輸入python即可進入anaconda環境的python:(base) will@ubuntu-hp:~$ python
Python 3.8.8 (default, Apr 13 2021, 19:58:26)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.conda create -n py38 python=3.8.8conda activate py38
安裝指定版本的tensorflow,指定國內源以加快下載速度:pip install tensorflow-gpu==2.3.0 -i https://pypi.tuna.tsinghua.edu.cn/simpleconda install cudatoolkit=10.1 -c https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/linux-64/conda install cudnn=7.6.5
安裝完成,接下來驗證一下是否GPU版的TensorFlow是否安裝成功驗證查看有哪些conda環境,以及正在使用哪個,輸入命令conda info --e,如下,星號所在的行表示正在使用的是base環境,並非咱們要用的py38:(base) will@ubuntu-hp:~$ conda info --e
# conda environments:
#
base * /home/will/anaconda3
py38 /home/will/anaconda3/envs/py38
執行source activate py38即可切換到py38環境import tensorflow as tf2021-10-08 23:08:55.391471: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
以下代碼表示檢查tensorflow能否得到CUDA支持,支持就會返回True,否則返回false:tf.test.is_built_with_cuda()
以下代碼表示檢查tensorflow能否獲取到GPU:tf.test.is_gpu_available()
如果能獲取到會返回Ture,並且輸出的部分日誌信息如下,可見顯卡信息已成功取到:2021-10-08 23:09:34.367795: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:982] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2021-10-08 23:09:34.368110: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1402] Created TensorFlow device (/device:GPU:0 with 5088 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1060 6GB, pci bus id: 0000:01:00.0, compute capability: 6.1)
True
作為對比,下圖是MabBook上的CPU版本TensorFlow執行結果: