在anaconda prompt程序中的base环境下:
# 创建名为 tf2 的虚拟环境,并根据预设环境名 tensorflow-gpu
# 自动安装 CUDA,cuDNN,TensorFlow GPU 等
conda create -n tf2 tensorflow-gpu==2.0.0
# 激活 tf2 虚拟环境 conda activate tf2
conda activate tf2
这种快捷安装方式称为极简版安装方法。这也是使用 Anaconda 发行版所带来的便捷 之处。通过极简版安装的 TensorFlow,使用时需要先激活对应的虚拟环境,这一点需要与 标准版区分。标准版安装在 Anaconda 的默认环境 base 中,一般不需要手动激活 base 环 境。
# 使用清华源安装常用 python 库
pip install -U ipython numpy matplotlib pillow pandas - i https://pypi.tuna.tsinghua.edu.cn/simple
TensorFlow 在运行时,默认会占用所有 GPU 显存资源,这是非常不友好的行为,尤其 是当计算机同时有多个用户或者程序在使用 GPU 资源时,占用所有 GPU 显存资源会使得 其他程序无法运行。因此,一般推荐设置 TensorFlow 的显存占用方式为增长式占用模式, 即根据实际模型大小申请显存资源,代码实现如下:
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
# 设置 GPU 为增长式占用
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
except RuntimeError as e:
# 打印异常
print(e)