Title: Ubuntu 18.04: Install TensorFlow and Keras for Deep Learning - PyImageSearch

URL Source: https://pyimagesearch.com/2019/01/30/ubuntu-18-04-install-tensorflow-and-keras-for-deep-learning/

Published Time: 2019-01-30T15:00:16+00:00

Markdown Content:
![Image 1](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20375'%3E%3C/svg%3E)

Inside this tutorial you will learn how to configure your Ubuntu 18.04 machine for deep learning with TensorFlow and Keras.

Configuring a deep learning rig is half the battle when getting started with computer vision and deep learning. I take pride in providing high-quality tutorials that can help you get your environment prepared to get to the fun stuff.

This guide will help you set up your Ubuntu system with the deep learning tools necessary for (1) your own projects and (2) my book, [_Deep Learning for Computer Vision with Python_](https://pyimagesearch.com/deep-learning-computer-vision-python-book/).

All that is required is Ubuntu 18.04, some time/patience, and _optionally_ an NVIDIA GPU.

If you’re an **Apple user,** you can follow my **[macOS Mojave deep learning installation instructions](https://pyimagesearch.com/2019/01/30/macos-mojave-install-tensorflow-and-keras-for-deep-learning/)!**

**To learn how to configure Ubuntu for deep learning with TensorFlow, Keras, and mxnet, _just keep reading_.**

On January 7th, 2019, I released version 2.1 of my [deep learning book](https://pyimagesearch.com/deep-learning-computer-vision-python-book/) to existing customers (free upgrade as always) and new customers.

Accompanying the code updates for compatibility are brand new pre-configured environments which remove the hassle of configuring your own system. In other words, I put the sweat and time into creating near-perfect, usable environments that you can fire up in less than 5 minutes.

This includes an updated (1) VirtualBox virtual machine, and (2) Amazon machine instance (AMI):

*   The [deep learning VM](https://pyimagesearch.com/2017/09/22/deep-learning-python-ubuntu-virtual-machine/) is self-contained and runs in isolation on your computer in any OS that will run VirtualBox.
*   My [deep learning AMI](https://pyimagesearch.com/2017/09/20/pre-configured-amazon-aws-deep-learning-ami-with-python/) is actually freely available to everyone on the internet to use (charges apply for AWS fees of course). It is a great option if you don’t have a GPU at home/work/school and you need to use one or many GPUs for training a deep learning model. This is the **_same exact system_** I use when deep learning in the cloud with GPUs.

While some people can get by with either the VM or the AMI, you’ve landed here because you need to configure your own deep learning environment on your Ubuntu machine.

The process of configuring your own system _isn’t for the faint of heart_, especially for first-timers. If you follow the steps carefully and take extra care with the _optional_ GPU setup, I’m sure you’ll be successful.

And if you get stuck, just [send me a message](https://pyimagesearch.com/contact) and I’m happy to help. DL4CV customers can use the companion website portal for faster responses.

Let’s begin!

### Step #1: Install Ubuntu dependencies

Before we start, fire up a terminal or SSH session. SSH users may elect to use a program called `screen` (if you are familiar with it) to ensure your session is not lost if your internet connection drops.

When you’re ready, go ahead and update your system:

$ sudo apt-get update
$ sudo apt-get upgrade

Let’s install development tools, image and video I/O libraries, GUI packages, optimization libraries, and other packages:

$ sudo apt-get install build-essential cmake unzip pkg-config
$ sudo apt-get install libxmu-dev libxi-dev libglu1-mesa libglu1-mesa-dev
$ sudo apt-get install libjpeg-dev libpng-dev libtiff-dev
$ sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
$ sudo apt-get install libxvidcore-dev libx264-dev
$ sudo apt-get install libgtk-3-dev
$ sudo apt-get install libopenblas-dev libatlas-base-dev liblapack-dev gfortran
$ sudo apt-get install libhdf5-serial-dev
$ sudo apt-get install python3-dev python3-tk python-imaging-tk

**CPU users:** Skip to **_“Step #5”_**.

**GPU users:** CUDA 9 requires gcc v6 but Ubuntu 18.04 ships with gcc v7 so we need to install gcc and g++ v6:

$ sudo apt-get install gcc-6 g++-6

### Step #2: Install latest NVIDIA drivers (GPU only)

[![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20288'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2019/01/ubuntu1804_dl_install_gpu_only.jpg)

**Figure 1:** Steps 2-4 require that you have an NVIDIA CUDA-capable GPU. A GPU with 8GB memory is recommended. _If you do not have a GPU, just skip to **Step #5.**_

This step is for **GPU users** only.

_**Note:**_ _This section differs quite a bit from my [Ubuntu 16.04 deep learning installation guide](https://pyimagesearch.com/2017/09/27/setting-up-ubuntu-16-04-cuda-gpu-for-deep-learning-with-python/) so make sure you follow it **carefully.**_

Let’s go ahead and add the NVIDIA PPA repository to Ubuntu’s Aptitude package manager:

$ sudo add-apt-repository ppa:graphics-drivers/ppa
$ sudo apt-get update

Now we can very conveniently install our NVIDIA drivers:

$ sudo apt install nvidia-driver-396

Go ahead and reboot so that the drivers will be activated as your machine starts:

$ sudo reboot now

Once your machine is booted and you’re back at a terminal or have re-established your SSH session, you’ll want to verify that NVIDIA drivers have been successfully installed:

$ nvidia-smi
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 396.54                 Driver Version: 396.54                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Tesla K80           Off  | 00000000:00:1E.0 Off |                    0 |
| N/A   58C    P0    61W / 149W |      0MiB / 11441MiB |     99%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|  No running processes found                                                 |
+-----------------------------------------------------------------------------+

In the first table, top row, we have the NVIDIA GPU driver version.

The next two rows display the type of GPU you have (in my case a Tesla K80) as well as how much GPU memory is being used — this idle K80 is using 0Mb of approximately 12GB.

The `nvidi-smi` command will also show you running processes using the GPU(s) in the next table. If you were to issue this command while Keras or mxnet is training, you’d see that Python is using the GPU.

Everything looks good here, so we can go ahead and move to **_“Step #3”_**.

### Step #3: Install CUDA Toolkit and cuDNN (GPU only)

This step is for **GPU users**.

Head to the NVIDIA developer website for CUDA 9.0 downloads. You can access the downloads via this direct link:

[https://developer.nvidia.com/cuda-90-download-archive](https://developer.nvidia.com/cuda-90-download-archive)

_**Note:** CUDA v9.0 is required for [TensorFlow](https://www.tensorflow.org/) v1.12 (unless you want to build TensorFlow from source which I do not recommend)._

Ubuntu 18.04 is not yet officially supported by NVIDIA, but Ubuntu 17.04 drivers will still work.

Make the following selections from the CUDA Toolkit download page:

1.  _“Linux”_
2.  _“x86\_64”_
3.  _“Ubuntu”_
4.  _“17.04”_ (will also work for 18.04)
5.  _“_runfile _(local)”_

…just like this:

![Image 3](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20888'%3E%3C/svg%3E)

**Figure 2:** Downloading the NVIDIA CUDA Toolkit 9.0 for Ubuntu 18.04.

You may just want to copy the link to your clipboard and use the wget command to download the runfile:

$ wget https://developer.nvidia.com/compute/cuda/9.0/Prod/local\_installers/cuda\_9.0.176\_384.81\_linux-run

Be sure to copy the full URL:

`https://developer.nvidia.com/compute/cuda/9.0/Prod/local_installers/cuda_9.0.176_384.81_linux-run`

From there install let’s go ahead and install the CUDA Toolkit. This requires that we first give the script _executable_ permissions via the `chmod` command and then that we use the super user’s credentials (you may be prompted for the root password):

$ chmod +x cuda\_9.0.176\_384.81\_linux-run
$ sudo ./cuda\_9.0.176\_384.81\_linux-run --override

_**Note:** The –override switch is required, otherwise the CUDA installer will complain about gcc-7 still being installed._

During installation, you will have to:

*   Use _“space”_ to scroll down and accept terms and conditions
*   Select y for _**“Install on an unsupported configuration”**_
*   Select n for _**“Install NVIDIA Accelerated Graphics Driver for Linux-x86\_64 384.81?”**_
*   Keep all other default values (some are `y` and some are `n` ). For paths, just press _“enter”_.

Now we need to update our ~/.bashrc file to include the CUDA Toolkit:

$ nano ~/.bashrc

The nano text editor is as simple as it gets, but feel free to use your preferred editor such as vim or emacs. Scroll to the bottom and add following lines:

\# NVIDIA CUDA Toolkit
export PATH=/usr/local/cuda-9.0/bin:$PATH
export LD\_LIBRARY\_PATH=/usr/local/cuda-9.0/lib64

[![Image 4](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20391'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2019/01/ubuntu1804_dl_install_bashrc_cuda.jpg)

**Figure 3:** Editing the `~/.bashrc` profile for the CUDA Toolkit. CUDA allows you to use your GPU for deep learning and other computation.

To save and exit with nano, simply press _“ctrl + o”_, then _“enter”_, and finally _“ctrl + x”_.

Once you’ve saved and closed your bash profile, go ahead and reload the file:

$ source ~/.bashrc

From there you can confirm that the CUDA Toolkit has been successfully installed:

$ nvcc -V
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2017 NVIDIA Corporation
Built on Fri\_Sep\_\_1\_21:08:03\_CDT\_2017
Cuda compilation tools, release 9.0, V9.0.176

### Step #4: Install cuDNN (CUDA Deep Learning Neural Network library) (GPU only)

For this step, you will need to create an account on the NVIDIA website + download cuDNN.

Here’s the link:

[https://developer.nvidia.com/cudnn](https://developer.nvidia.com/cudnn)

When you’re logged in and on that page, go ahead and make the following selections:

1.  _“Download cuDNN”_
2.  Login and check _“I agree to the terms of service fo the cuDNN Software License Agreement”_
3.  _“Archived cuDNN Releases”_
4.  **_“cuDNN v7.4.1 (Nov 8, 2018) for CUDA 9.0”_**
5.  _**“cuDNN Library for Linux”**_

Your selections should make your browser page look similar to this:

[![Image 5](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20735'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2019/01/ubuntu1804_dl_install_cudnn.jpg)

**Figure 4:** Downloading cuDNN from the NVIDIA developer website in order to set up our Ubuntu system for deep learning.

Once the files reside on your personal computer, you might need to place them to your GPU system. You may SCP the files to your GPU machine using this command (if you’re using an EC2 keypair):

$ scp -i EC2KeyPair.pem ~/Downloads/cudnn-9.0-linux-x64-v7.4.1.5.tgz \\
	username@your\_ip\_address:~

On the GPU system (via SSH or on the desktop), the following commands will install cuDNN in the proper locations on your Ubuntu 18.04 system:

$ cd ~
$ tar -zxf cudnn-9.0-linux-x64-v7.4.1.5.tgz
$ cd cuda
$ sudo cp -P lib64/\* /usr/local/cuda/lib64/
$ sudo cp -P include/\* /usr/local/cuda/include/
$ cd ~

Above, we have:

1.  Extracted the cuDNN 9.0 v7.4.1.5 file in our home directory.
2.  Navigated into the `cuda/` directory.
3.  Copied the `lib64/` directory and all of its contents to the path shown.
4.  Copied the `include/` folder as well to the path shown.

Take care with these commands as they can be a pain point later if cuDNN isn’t where it needs to be.

### Step #5: Create your Python virtual environment

This section is for _**both**_ **CPU and GPU** users.

I’m an advocate for Python virtual environments as they are a _best practice_ in the Python development world.

Virtual environments allow for the development of different projects on your system while managing Python package dependencies.

For example, I might have an environment on my GPU DevBox system called `dl4cv_21` corresponding to version 2.1 of my [deep learning book](https://pyimagesearch.com/deep-learning-computer-vision-python-book/).

But then when I go to release version 3.0 at a later date, I’ll be testing my code with different versions of TensorFlow, Keras, scikit-learn, etc. Thus, I just put the updated dependencies in their own environment called `dl4cv_30` . I think you get the idea that this makes development a lot easier.

Another example would be two independent endeavors such as (1) a blog post series — we’re working on [predicting home prices right now](https://pyimagesearch.com/2019/01/21/regression-with-keras/), and (2) some other project like [PyImageSearch Gurus](https://pyimagesearch.com/pyimagesearch-gurus/).

I have a `house_prices` virtual environment for the 3-part house prices series and a `gurus_cv4` virtual environment for my recent OpenCV 4 update to the entire Gurus course.

In other words, you can rack up as many virtual environments as you need without spinning resource hungry VMs to test code.

It’s a no-brainer for Python development.

I use and promote the following tools to get the job done:

*   **virtualenv**
*   **virtualenvwrapper**

_**Note:** I’m not opposed to alternatives (Anaconda, venv, etc.), but you’ll be on your own to fix any problems with these alternatives. Additionally, it may cause some headaches if you mix environment systems, so just be aware of what you’re doing when you follow tutorials you find online._

Without further ado, let’s setup virtual environments on your system — if you’ve done this before, just pick up where we actually create the new environment.

First, let’s install pip, a Python package management tool:

$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python3 get-pip.py

Now that pip is installed, let’s go ahead and install the two virtual environment tools that I recommend — virtualenv and virtualenvwrapper:

$ sudo pip install virtualenv virtualenvwrapper
$ sudo rm -rf ~/get-pip.py ~/.cache/pip

We’ll need to update our bash profile with some virtualenvwrapper settings to make the tools work together.

Go ahead and open your ~/.bashrc file using your preferred text editor again and add the following lines at the very bottom:

\# virtualenv and virtualenvwrapper
export WORKON\_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER\_PYTHON=/usr/bin/python3
source /usr/local/bin/virtualenvwrapper.sh

[![Image 6](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20385'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2019/01/ubuntu1804_dl_install_bashrc_virtualenvwrapper.jpg)

**Figure 5:** Using Python virtual environments is a necessity for deep learning development with Python on Ubuntu. In this screenshot, we have edited our `~/.bashrc` to use virtualenv and virtualenvwrapper (two of my preferred tools).

And let’s go ahead and reload our ~/.bashrc file:

$ source ~/.bashrc

The **virtualenvwrapper** tool now has support for the following terminal **commands:**

*   `mkvirtualenv` : Creates a virtual environment.
*   `rmvirtualenv` : Removes a virtual environment.
*   `workon` : Activates a specified virtual environment. If an environment isn’t specified all environments will be listed.
*   `deactivate` : Takes you to your system environment. You can activate any of your virtual environments again at any time.

#### Creating the `dl4cv` environment

Using the first command from the list above, let’s go ahead and create the dl4cv virtual environment with Python 3:

$ mkvirtualenv dl4cv -p python3

When your virtual environment is active, your terminal bash prompt will look like this:

[![Image 7](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20388'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2019/01/ubuntu1804_dl_install_workon_dl4cv.jpg)

**Figure 6:** My `dl4cv` environment is activated. The beginning of the bash prompt serves as my validation that I’m ready to install software for deep learning with Python.

If your environment is not active, simply use the `workon` command:

$ workon dl4cv

From there your bash prompt will change accordingly.

### Step #6: Install Python libraries

Now that our Python virtual environment is created and is currently active, let’s install NumPy and OpenCV using pip:

$ pip install numpy
$ pip install opencv-contrib-python

Alternatively, you can [install OpenCV from source](https://pyimagesearch.com/2018/08/15/how-to-install-opencv-4-on-ubuntu/) to get the full install with patented algorithms. But for my deep learning books, those additional algorithms are irrelevant to deep learning.

Let’s install libraries required for additional computer vision, image processing, and machine learning as well:

$ pip install scipy matplotlib pillow
$ pip install imutils h5py requests progressbar2
$ pip install scikit-learn scikit-image

#### Install TensorFlow for _Deep Learning for Computer Vision with Python_

You have two options to install [TensorFlow](https://www.tensorflow.org/):

**Option #1:** Install TensorFlow _**with**_ GPU support:

$ pip install tensorflow-gpu==1.12.0

_**Note:** Feedback from our readers has led us to realize that newer versions of CUDA don’t support the latest TensorFlow. We recommend installing version 1.12.0 as shown._

**Option #2:** Install TensorFlow _**without**_ GPU support:

$ pip install tensorflow

Arguably, a third option is to compile TensorFlow from source, but it is unnecessary for DL4CV.

Go ahead and verify that TensorFlow is installed in your `dl4cv` virtual environment:

$ python
>>> import tensorflow
>>>

#### Install Keras for _DL4CV_

We’ll employ pip again to install [Keras](https://keras.io/) into the `dl4cv` environment:

$ pip install keras

You can verify that Keras is installed via starting a Python shell:

$ python
>>> import keras
Using TensorFlow backend.
>>>

Now let’s go ahead and exit the Python shell and then deactivate the environment before we move on to _“Step #7”_:

\>>> exit()
$ deactivate

_**Note:** An issue was raised about DL4CV ImageNet Bundle Chapter 10 “Case Study: Emotion recognition”. The [solution](https://github.com/keras-team/keras/issues/10648) is that the following commit-ID from the Keras master branch needs to be installed for compatibility: `9d33a024e3893ec2a4a15601261f44725c6715d1` . To implement the fix, you can (1) clone the Keras repo using the commit-ID, and (2) use `setup.py` to install Keras. Eventually PyPi will be updated and the pip installation method described above will work. The bug/fix does not impact all chapters. **Reference:** Ticket #798 in the DL4CV issue tracker._

### Step #7: Install mxnet (_DL4CV_ _ImageNet Bundle_ only)

[![Image 8](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20400'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2017/11/mxnet_install_header.jpg)

**Figure 7:** mxnet is a great deep learning framework and is highly efficient for multi-GPU and distributed network training.

We use [mxnet](https://mxnet.apache.org/) in the _ImageNet Bundle_ of _Deep Learning for Computer Vision with Python_ due to both (1) its speed/efficiency and (2) its great ability to handle multiple GPUs.

When working with the ImageNet dataset as well as other large datasets, training with multiple GPUs is critical.

It is not to say that you can’t accomplish the same with Keras with the TensorFlow GPU backend, but mxnet does it more efficiently. The syntax is similar, but there are some aspects of mxnet that are less user-friendly than Keras. In my opinion, the tradeoff is worth it, and it is always good to be proficient with more than one deep learning framework.

Let’s get the ball rolling and install mxnet.

#### Installing mxnet requires OpenCV + mxnet compilation

In order to effectively use mxnet’s data augmentation functions and the im2rec utility we need to compile mxnet _from source_ rather than a simple pip install of mxnet.

**Since mxnet is a compiled C++ library (with Python bindings), it implies that we must compile OpenCV from source as _well_.**

Let’s go ahead and download OpenCV (we’ll be using version 3.4.4):

$ cd ~
$ wget -O opencv.zip https://github.com/opencv/opencv/archive/3.4.4.zip
$ wget -O opencv\_contrib.zip https://github.com/opencv/opencv\_contrib/archive/3.4.4.zip

And then unzip the archives:

$ unzip opencv.zip
$ unzip opencv\_contrib.zip

I like to rename the directories, that way our paths will be the same even if you are using a version of OpenCV other than 3.4.4:

$ mv opencv-3.4.4 opencv
$ mv opencv\_contrib-3.4.4 opencv\_contrib

And from there, let’s create a new virtual environment (assuming you followed the virtualenv and virtualenvwrapper instructions from _**Step #2**)._

The `mxnet` virtual environment will contain packages completely independent and sequestered from our `dl4cv` environment:

$ mkvirtualenv mxnet -p python3

Now that your mxnet environment has been created, notice your bash prompt:

[![Image 9](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20387'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2019/01/ubuntu1804_dl_install_workon_mxnet.jpg)

**Figure 8:** The virtualenvwrapper tool coupled with the `workon mxnet` command activates our `mxnet` virtual environment for deep learning.

We can go on to install packages we will need for DL4CV into the environment:

$ pip install numpy scipy matplotlib pillow
$ pip install imutils h5py requests progressbar2
$ pip install scikit-learn scikit-image

Let’s configure OpenCV with cmake:

$ cd ~/opencv
$ mkdir build
$ cd build
$ cmake -D CMAKE\_BUILD\_TYPE=RELEASE \\
	-D CMAKE\_INSTALL\_PREFIX=/usr/local \\
	-D INSTALL\_PYTHON\_EXAMPLES=ON \\
	-D INSTALL\_C\_EXAMPLES=OFF \\
	-D OPENCV\_EXTRA\_MODULES\_PATH=~/opencv\_contrib/modules \\
	-D PYTHON\_EXECUTABLE=~/.virtualenvs/mxnet/bin/python \\
	-D OPENCV\_ENABLE\_NONFREE=ON \\
	-D BUILD\_EXAMPLES=ON ..

[![Image 10](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20392'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2019/01/ubuntu1804_dl_install_cmake.jpg)

**Figure 9:** OpenCV’s CMake output shows us that we’re using a Python 3.6 interpreter inside the mxnet environment. NumPy in the mxnet environment is also being utilized.

Provided that your output matches mine, let’s go ahead and kick off the compile process:

$ make -j4

Compiling OpenCV can take quite a bit of time, but since you likely have a GPU, your system specs are probably already very capable of compiling OpenCV in less than 30 minutes. Nevertheless, this is the point where you’d want to go for a walk or grab a fresh cup of coffee.

When OpenCV has been 100% compiled, there are still a few remaining sub-steps to perform, beginning with our actual install commands:

$ sudo make install
$ sudo ldconfig

You can confirm that OpenCV has been successfully installed via:

$ pkg-config --modversion opencv
3.4.4

**And now for the critical sub-step.**

What we need to do is create a link from where OpenCV was installed into the virtual environment itself. This is known as a symbolic link.

Let’s go ahead and take care of that now:

$ cd /usr/local/python/cv2/python-3.6
$ ls
cv2.cpython-36m-x86\_64-linux-gnu.so

And now let’s rename the .so file to something that makes a little bit more sense + create a sym-link to our mxnet site-packages:

$ sudo mv cv2.cpython-36m-x86\_64-linux-gnu.so cv2.opencv3.4.4.so
$ cd ~/.virtualenvs/mxnet/lib/python3.6/site-packages
$ ln -s /usr/local/python/cv2/python-3.6/cv2.opencv3.4.4.so cv2.so

_**Note:** If you have multiple OpenCV versions ever installed in your system, you can use this same naming convention and symbolic linking method._

To test that OpenCV is installed + symbolically linked properly, fire up a Python shell inside the mxnet environment:

$ cd ~
$ workon mxnet
$ python
>>> import cv2
>>> cv2.\_\_version\_\_
'3.4.4'

We’re now ready to install mxnet into the environment.

#### Cloning and installing `mxnet`

We have gcc and g++ v7 installed for CUDA; _however, there is a problem_ — mxnet _requires_ **gcc v6** and **g++ v6** to compile from source.

The solution is to remove the gcc and g++ sym-links:

$ cd /usr/bin
$ sudo rm gcc g++

And then create new ones, this time pointing to gcc-6 and `g++-6` :

$ sudo ln -s gcc-6 gcc
$ sudo ln -s g++-6 g++

Let’s download and install mxnet now that we have the correct compiler tools linked up.

Go ahead and clone the mxnet repository as well as check out version 1.3:

$ cd ~
$ git clone --recursive --no-checkout https://github.com/apache/incubator-mxnet.git mxnet
$ cd mxnet
$ git checkout v1.3.x
$ git submodule update --init

With version 1.3 of mxnet ready to go, we’re going to compile mxnet with BLAS, OpenCV, CUDA, and cuDNN support:

$ workon mxnet
$ make -j4 USE\_OPENCV=1 USE\_BLAS=openblas USE\_CUDA=1 USE\_CUDA\_PATH=/usr/local/cuda USE\_CUDNN=1

The compilation process will likely finish in less than 40 minutes.

And then we’ll create a sym-link for mxnet into the virtual environment’s site-packages:

$ cd ~/.virtualenvs/mxnet/lib/python3.6/site-packages/
$ ln -s ~/mxnet/python/mxnet mxnet

_**Update 2019-06-04:** The sym-link is updated to support the `io` module of mxnet._

Let’s go ahead and test our mxnet install:

$ workon mxnet
$ cd ~
$ python
>>> import mxnet
>>>

_**Note:** Do not delete the ~/mxnet directory in your home folder. Not only do our Python bindings live there, but we also need the files in ~/mxnet/bin when creating serialized image datasets (i.e., the `im2rec` command)._

Now that mxnet is done compiling we can reset our gcc and g++ symlinks to use v7:

$ cd /usr/bin
$ sudo rm gcc g++
$ sudo ln -s gcc-7 gcc
$ sudo ln -s g++-7 g++

We can also go ahead and delete the OpenCV source code from our home folder:

$ cd ~
$ rm -rf opencv/
$ rm -rf opencv\_contrib/

From here you can deactivate this environment, `workon` a different one, or create another environment. In the supplementary materials page of the DL4CV companion website, I have instructions on how to setup environments for the TensorFlow Object Detection API, Mask R-CNN, and RetinaNet code.

### mxnet + OpenCV 4.1 workaround

_**Update 2019-08-08:**_ OpenCV 4.1 has been causing a number of readers issues with mxnet. In this section, I’m presenting a workaround by PyImageSearch reader, Gianluca. _Thank you, Gianluca!_

The problem is that the latest OpenCV (4.1.0) does not create the `opencv4.pc` file that is needed by pkg-config command (used in mxnet build) to identify the installed libs and folders.

The fix is to **add one more CMake flag** in addition to **a symlink later on.**

Let’s review the CMake flag:

$ cmake -D CMAKE\_BUILD\_TYPE=RELEASE \\
	-D CMAKE\_INSTALL\_PREFIX=/usr/local \\
	-D INSTALL\_PYTHON\_EXAMPLES=ON \\
	-D INSTALL\_C\_EXAMPLES=OFF \\
	-D OPENCV\_GENERATE\_PKGCONFIG=YES \\
	-D OPENCV\_EXTRA\_MODULES\_PATH=~/opencv\_contrib/modules \\
	-D PYTHON\_EXECUTABLE=~/.virtualenvs/mxnet/bin/python \\
	-D OPENCV\_ENABLE\_NONFREE=ON \\
	-D BUILD\_EXAMPLES=ON ..

Note that **Line 5** is highlighted.

Follow the instructions above from that point, however, there is one additional step.

Once installed (via the `make` command), we need to symlink the file `opencv4.pc` from `/usr/local/lib` to the default `/usr/share/pkgconfig` folder:

$ cd /usr/share/pkgconfig
$ ln -s /usr/local/lib/opencv4.pc opencv4.pc

Be sure to provide your comments in the form below if you have troubles with OpenCV 4.1 and mxnet.

### A job well-done

At this point, a “congratulations” in order — you’ve successfully configured your Ubuntu 18.04 box for deep learning!

Great work!

**Did you have any troubles configuring your deep learning system?**

If you struggled along the way, I encourage you to re-read the instructions again and try to debug. If you’re really stuck, you can reach out in the DL4CV companion website issue tracker (there’s a registration link in the front of your book) or by [contacting me](https://pyimagesearch.com/contact/).

I also want to take the opportunity to remind you about the pre-configured instances that come along with your book:

*   The [DL4CV VirtualBox VM](https://pyimagesearch.com/2017/09/22/deep-learning-python-ubuntu-virtual-machine/) is pre-configured and ready to go. It will help you through nearly all experiments in the _Starter_ and _Practitioner_ bundles. For the _ImageNet_ bundle a GPU is a necessity and this VM does not support GPUs.
*   My [DL4CV Amazon Machine Image](https://pyimagesearch.com/2017/09/20/pre-configured-amazon-aws-deep-learning-ami-with-python/) for the AWS cloud is freely open to the internet — no purchase required (other than AWS charges, of course). Getting started with a GPU in the cloud only takes about 4-6 minutes. For less than the price of a cup of coffee, you can use a GPU instance for an hour or two which is just enough time to complete some (definitely not all) of the more advanced lessons in DL4CV. The following environments are pre-configured: `dl4cv` , `mxnet` , `tfod_api` , `mask_rcnn` , and `retinanet` .

Azure users should consider the Azure DSVM. You can read [my review of the Microsoft Azure DSVM here](https://pyimagesearch.com/2018/03/21/my-review-of-microsofts-deep-learning-virtual-machine/). All code from one of the first releases of DL4CV in 2017 was tested using Microsoft’s DSVM. It is an option and a very good one at that, but at this time it is not ready to support the _Bonus Bundle_ of DL4CV without additional configuration. If Azure is your preferred cloud provider, I encourage you to stay there and take advantage of what the DSVM has to offer.

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024  
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled

**I strongly believe that if you had the right teacher you could _master_ computer vision and deep learning.**

Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?

That’s _not_ the case.

All you need to master computer vision and deep learning is for someone to explain things to you in _simple, intuitive_ terms. _And that’s exactly what I do_. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to _successfully_ and _confidently_ apply computer vision to your work, research, and projects. Join me in computer vision mastery.

**Inside PyImageSearch University you'll find:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ hours** of on-demand video
*   ✓ **Brand new courses released _regularly_**, ensuring you can keep up with state-of-the-art techniques
*   ✓ **Pre-configured Jupyter Notebooks in Google Colab**
*   ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
*   ✓ Access to **centralized code repos for _all_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

Summary
-------

Today we learned how to set up an Ubuntu 18.04 + CUDA + GPU machine (as well as a CPU-only machine) for deep learning with TensorFlow and Keras.

Keep in mind that you don’t need a GPU to learn how deep learning works! GPUs are great for deeper neural networks and training with tons of data, but if you just need to learn the fundamentals and get some practice on your laptop, your CPU is just fine.

We accomplished our goal of setting up the following tools into two separate virtual environments:

*   Keras + TensorFlow
*   mxnet

Each of these deep learning frameworks requires additional Python packages to be successful such as:

*   scikit-learn, SciPy, matplotlib
*   OpenCV, pillow, scikit-image
*   imutils (my personal package of convenience functions and tools)
*   _…and more!_

These libraries are now available in each of the virtual environments that we set up today. You’re now ready to train state-of-the-art models using TensorFlow, Keras, and mxnet. Your system is ready to hack with the code in my deep learning book as well as your own projects.

Setting up all of this software is definitely daunting, especially for novice users. If you encountered any issues along the way, I highly encourage you to check that you didn’t skip any steps. If you are still stuck, please get in touch.

I hope this tutorial helps you on your deep learning journey!

**To be notified when future blog posts are published here on PyImageSearch (and grab my 17-page Deep Learning and Computer Vision Resource Guide PDF), just _enter your email address in the form below!_**

![Image 11](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### Join the PyImageSearch Newsletter and Grab My FREE 17-page Resource Guide PDF

Enter your email address below to **join the PyImageSearch Newsletter** and **download my FREE 17-page Resource Guide PDF** on Computer Vision, OpenCV, and Deep Learning.