ubuntu下通过docker安装TensorFlow-GPU

概述

由于不同设备和不同环境在配置TensorFlow的过程中,会出现多种不兼容的问题,故想借用Docker来解决这个问题。也发现TensorFlow官方也提供有TensorFlow的官方docker镜像。这里,我在Ubuntu 18.04 基于Docker构建TensorFlow环境。

1. docker

简介

参考定义:Docker 可以让开发者打包他们的应用以及依赖包到一个轻量级、可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化。

容器是完全使用沙箱机制,相互之间不会有任何接口(类似 iPhone 的 app),更重要的是容器性能开销极低。

Docker 从 17.03 版本之后分为 CE(Community Edition: 社区版) 和 EE(Enterprise Edition: 企业版),我们用社区版就可以了。
https://www.runoob.com/docker/docker-tutorial.html

我将docker理解为容器,对于不同的平台(win or mac or linux),都可以运行这个容器,并且在容器中安装不同的镜像(类似于虚拟机的集成好的开发环境),就可以使得镜像在不同的平台运行,并且所有的依赖项在镜像中都封装好了。

安装

1. 安装docker engine

Docker 从 17.03 版本之后分为 CE(Community Edition: 社区版) 和 EE(Enterprise Edition: 企业版),我们用社区版就可以了。
这里作者直接采用官方的教程:https://docs.docker.com/engine/install/ubuntu/

安裝完毕后,使用sudo docker run hello-world进行测试安装结果

2. 安装NVIDIA-docker toolkit

具体的安装过程可以参考Github
这里指向了官方的安装指导

Setup the stable repository and the GPG key:

distribution=$(. /etc/os-release;echo $ID$VERSION_ID) \
   && curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add - \
   && curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list

Install the nvidia-docker2 package (and dependencies) after updating the package listing:

sudo apt-get update
sudo apt-get install -y nvidia-docker2

Restart the Docker daemon to complete the installation after setting the default runtime:

sudo systemctl restart docker

At this point, a working setup can be tested by running a base CUDA container:

sudo docker run --rm --gpus all nvidia/cuda:11.0-base nvidia-smi

下载TensorFlow image并运行

在docker hub中查看相应的版本
这里我选择的是TensorFlow2.4.0 gpu jupyter,
在终端中使用如下命令下载

使用如下命令运行一个容器

docker run -it --rm --gpus all -v /home/crazyjackkong/Desktop/:/tf/Desktop -v /etc/localtime:/etc/localtime:ro -p 8888:8888 tensorflow/tensorflow:2.4.0rc1-gpu-jupyter

其中

--rm代表使用完毕container后删除相应的中间文件

--gpus all代表使用GPU 这个可以参照NVIDIA docker的

-it 启动交互式终端

-v /home/crazyjackkong/Desktop/:/tf/Desktop 将主机的Desktop挂载到容器中的tf/Desktop目录下。这里我理解tf就是这个镜像的jupyter的启动路径

-v /etc/localtime:/etc/localtime:ro 把主机的目录:ro的只读(readonly)挂载到虚拟机目录

说明

这时就启动了一个容器并且启动了jupyter-notebook

note:这里的jupyter-notebook 需要自己提前安装好

修改image:增加OpenCV包并保存

2. jupyter

在容器中安装的是jupyter-notebook 同时常用的用于深度学习的IDE也是notebook,所以对于一些使用方法做记录。

notebook 中运行py文件

在.ipynb文件中可以使用%开头的魔法函数运行.py文件

  1. %run xx.py 这种方法是直接运行py文件
  2. %load xx.py 这种方法是载入代码片段,相当于在ipynb中打开py文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值