logo

TensorFlow Env

王哲峰 / 2022-07-01


目录

TensorFlow 支持的硬件平台

PC

Mobile

TensorFlow 系统要求

安装 TensorFlow 2

使用 pip 安装 TensorFlow 2

必须使用最新版本的 pip, 才能安装 TensorFlow 2

Virtualenv 安装

# Requires the latest pip
(venv) $ pip install --upgrade pip

# Current stable release for CPU and GPU
(venv) $ pip install --upgrade tensorflow
(venv) $ python -c "import tensorflow as tf;print(tf.reduce_sum(tf.random.normal([1000, 1000])))"
$ pip3 install pydot

系统安装

# Requires the latest pip
$ pip3 install --upgrade pip

# Current stable release for CPU and GPU
$ pip3 install --user --upgrade tensorflow
$ python3 -c "import tensorflow as tf; print(tf.reduce_sum(tf.random.normal([1000, 1000])))"
$ pip3 install pydot

使用 Conda 安装 TensorFlow 2

  1. 安装 Python 环境
    • 建议安装 Anaconda 的 Python 3.7 64 位版本
  2. 使用 Anaconda/Miniconda 自带的 conda 包管理器建立一个 conda 虚拟环境,并进入虚拟环境
$ conda create --name tf2 python=3.7
$ conda activate tf2
  1. 使用 Python 包管理器 pip 安装 TensorFlow
$ pip install tensorflow

使用 Docker 安装 TensorFlow 2

Docker 安装 TensorFlow 2

TensorFlow Docker 映像已经配置,可运行 TensorFlow。 Docker 容器可在虚拟环境中运行,是设置 GPU 支持的最简单方法

# Download latest stable image
$ docker pull tensorflow/tensorflow:latest-py3

# Start Jupyter server
$ docker run -it -p 8888:8888 tensorflow/tensorflow:latest-py3-jupyter

TensorFlow Docker Image

小技巧

GPU 版本的 TensorFlow 安装

GPU 版本的 TensorFlow 可以利用 NVIDIA GPU 强大的加速计算能力, 使 TensorFlow 运行更加高效,尤其是可以成倍提升模型的训练速度. 在安装 GPU 版本的 TensorFlow 前,需要有一块“不太旧”的 NVIDIA 显卡, 并正确安装 NVIDIA 显卡驱动程序、CUDA Toolkit 和 cuDNN.

GPU 硬件的准备

TensorFlow 对 NVIDIA 显卡的支持较为完备。对于 NVIDIA 显卡, 要求其 CUDA 的算力(compute capability) 不低于 3.5。 可以到 NVIDIA 的官网查询自己所用显卡的 CUDA 算力

目前 AMD 显卡也开始对 TensorFlow 提供支持

NVIDIA 驱动程序的安装

Windows 下安装 NVIDIA 驱动程序:

Linux 下安装 NVIDIA 驱动程序:

NVIDIA 驱动程序安装完成后,可以在命令行下使用 nvidia-smi 命令检查是否安装成功, 若成功,则会打印当前系统安装的 NVIDIA 驱动信息:

$ nvidia-sim

CUDA Toolkit 和 cuDNN 的安装

在 Anaconda/Miniconda 环境下,推荐使用 conda 安装 CUDA Toolkit 和 cuDNN

  1. 搜索 conda 源中可用的 CUDA Toolkit 和 cuDNN 版本号
$ conda search cudatoolkit
$ conda search cudnn
  1. 安装 CUDA Toolkit 和 cuDNN
conda install cudatoolkit=X.X
conda install cudnn=X.X.X

在 使用 Python pip 安装时:

Google Colab