Installing Keras for deep learning

The purpose of this blog post is to demonstrate how to install the Keras library for deep learning. The installation procedure will show how to install Keras:

  • With GPU support, so you can leverage your GPU, CUDA Toolkit, cuDNN, etc., for faster network training.
  • Without GPU support, so even if you do not have a GPU for training neural networks, you’ll still be able to follow along.

Let me start by saying that Keras is my favorite deep learning Python library. It’s a minimalist, modular neural network library that can use either TensorFlow or Theano as a backend.

Furthermore, the primary motivation behind Keras really resonates with me: you should be able to experiment super quickly — going from idea to result, as fast as possible.

Coming from a world that mixes both academia and entrepreneurship, the ability to iterate quickly is extremely valuable, especially in the deep learning world where it can take days to weeks to train just a single model.

I’ll be using Keras extensively in the coming PyImageSearch blog posts, so make sure you follow this tutorial to get Keras installed on your machine!

Installing Keras for deep learning

I’ll be making the assumption that you’ve been following along in this series of blog posts on setting up your deep learning development environment:

I’ll be using my same Amazon EC2 p2.xlarge instance running Ubuntu 16.04 as I have in previous tutorials — feel free to use the same machine you’ve been using to follow along as well.

Overall, installing Keras is a 4-step procedure, with three of these steps being optional.

The first optional step is whether or not you would like to use Python virtual environments — I suggest that you do, but that decision is entirely up to you.

The second optional step is whether or not you want to use the GPU to speedup training your neural networks — this is obviously dependent on whether you own a CUDA-compatible GPU. The Keras library can run on the CPU just fine, but if you really want to train deep neural networks, you’ll want to get a GPU installation setup.

The final optional step is whether or not you would like to have OpenCV bindings in your Python virtual environment along with your Keras installation. If you do, you’ll want to pay attention to Step #4.

With all that said, let’s get started!

Step #1: Create a separate Python virtual environment (optional)

If you’ve been following along in this series of posts, then you already know that I like using Python virtual environments. Utilizing virtual environments is especially important when we start working with various deep learning libraries (Keras, mxnet, TensorFlow, etc.) and versioning issues can easily occur (especially surrounding which version of TensorFlow is used).

Because of the problems related to conflicting library versions, I suggest creating a virtual environment exclusively for Keras-based projects:

This will create a Python virtual environment named keras . Anytime you would like to access this virtual environment, just use the workon  command followed by the name of the virtual environment:

In this case, we can access the keras  virtual environment by executing the following command:

Step #2: Install Keras

Installing Keras is a breeze — pip  can do all the hard work for us. First, we need to install a few dependencies:

We also need to install Tensorflow. You can certainly use pip  to install TensorFlow:

GPU users that have already installed CUDA and cuDNN can install the GPU version of TensorFlow with pip:

From there, we can use pip  to install Keras as well:

After Keras has finished installing, you can verify the install by opening up a terminal, accessing the keras  virtual environment, and then importing the library (see Step #3 for an example on how to do this).

Step #3: Sym-link in OpenCV (optional)

If you want to have access to your OpenCV bindings from the keras  virtual environment, you’ll need to sym-link in the  file into the site-packages  directory of keras :

As I detailed in last week’s tutorial, after compiling and installing OpenCV, my  bindings were found in /usr/local/lib/python3.6/site-packages/ . Depending on how you installed OpenCV on your own system, your  bindings may be in a different location. If you cannot remember where your  bindings are, or if you no longer have your CMake output (which does indicate where the bindings will be stored), you can use the find  utility program to help locate them:

Again, this is a totally optional step and only needs to be done if you want to have access to OpenCV from the keras  virtual environment.

Step #4: Test out the installation

To verify that Keras has been installed, access the keras  virtual environment, open up a Python shell, and import it:

Below follows a screenshot from my own EC2 instance:

Figure 1: Installing the Keras Python library for deep learning.

Notice that the TensorFlow backend is being used.

Also notice that the GPU is being used, in this case the K80 that is installed on the Amazon EC2 p2.xlarge instance. For more information on how I installed the CUDA Toolkit and cuDNN, please see this blog post.

Optionally, if you performed Step #3 and want to test your OpenCV sym-link, try to import your OpenCV bindings into the keras  virtual environment as well:

Figure 2: Importing OpenCV and Keras together for deep learning with Python.

At this point, you should now be able to import Keras and OpenCV into the same Python virtual environment. Take a second to congratulate yourself — you now have all the building blocks in place to start constructing deep neural networks!


In today’s blog post, I demonstrated how to install the Keras Python package for deep learning.

We’ll be using the Keras library extensively in future PyImageSearch blog posts, so I highly encourage you to get Keras installed on your machine, even if it’s just the CPU version — this will enable you to follow along in future PyImageSearch tutorials on deep learning.

Next week, we’ll take another step in our deep learning journey by studying convolutions, what they are, how they work, and how you’re already using them in your computer vision applications (whether you realize it or not).

Be sure to signup for the PyImageSearch Newsletter using the form below — you won’t want to miss when this upcoming post on convolutions goes live!

, ,

77 Responses to Installing Keras for deep learning

  1. Manish July 19, 2016 at 1:39 am #

    Signing up for newsletters.

    • Adrian Rosebrock July 19, 2016 at 12:28 pm #

      Thanks Manish! 🙂

  2. John Knae July 19, 2016 at 3:04 pm #


    I’m a retired Soc PhD with time on my hands so I’m researching/reviewing AGI and Deep Machine Learning and I wanted to express my gratitude for the tutorials you’ve put together on the Web. They have been a wonderful help for ol’ duffers like me and I’m sure for the better informed as well. Thank you

    • Adrian Rosebrock July 20, 2016 at 2:39 pm #

      Thanks for the kind words John 🙂 I’ll be doing a lot more deep learning and machine learning tutorials in coming posts.

  3. Kenny July 20, 2016 at 11:51 am #

    Cool Adrian 😉 As always, you never fail to keep me excited to learn more about CV 🙂 Keep going!

  4. Niki July 27, 2016 at 3:51 pm #

    Thank you for such a nice tutorial. I had to install Keras and this tutorial really helped me out. I have a question about graphs. I know about NetworkX library in python which is used for graph analysis. But, didn’t find any good tutorial on image and video processing or computer vision that uses this library to build the graphs. I was wondering if you have had any experience using NetworkX and could suggest any good tutorial or perhaps you have a plan to post something about that in future.

    • Adrian Rosebrock July 29, 2016 at 8:42 am #

      I personally haven’t used NetworkX before. Most of my work doesn’t involve graphs. If I ever do work in graphs, I’ll look into NetworkX and consider doing a tutorial on that.

  5. Hilman July 31, 2016 at 8:35 am #

    I really think you are stepping out this website Adrian. Keep posting something like this. You are really making education accessible freely on the web! Can’t wait to get my hands dirtier with deep learning!

    • Adrian Rosebrock July 31, 2016 at 10:34 am #

      Thanks Hilman! You’ll really enjoying next week’s blog post.

  6. Claude August 5, 2016 at 11:29 am #

    Great post! Thanks!

    • Adrian Rosebrock August 7, 2016 at 8:18 am #

      I’m glad it helped Claude! 🙂

  7. Navdeep August 7, 2016 at 7:03 am #

    Hey! thanks for the great post 😀

    I have a doubt..

    you said we need to edit or create “.theanorc” file in the home directory, what exactly is that home directory ??

    • Adrian Rosebrock August 7, 2016 at 8:08 am #

      Hey Navdeep — before continuing with this tutorial, I would suggest brushing up on a bit of Unix basics to ensure you don’t run into any problems down the line. You can learn more about the home directory here.

  8. Ethan August 7, 2016 at 2:22 pm #

    I get to the final step:
    >>> import keras
    Using Theano backend.

    and it hangs forever. Thoughts?

    • Adrian Rosebrock August 8, 2016 at 6:39 pm #

      It might not be hanging. In some cases it can take 10-60 seconds if you’re using the GPU. Also, be sure to run “top” and see if anything GPU-like is executing, indicating that Theano is working in the background.

    • saeed February 27, 2017 at 1:04 am #

      The solution for this problem is to add to the following to .theanorc file
      root = /usr/local/cuda-8.0

  9. Marc-Philippe Huget August 12, 2016 at 11:57 am #

    Hello Adrian,

    Apparently, installing Keras on CPU is little bit longer, I agree on all the steps you described, I did and it worked well on examples provided by Keras but on the blog post you submitted this week, apparently one needs to install BLAS, I have to investigate this point


    • Adrian Rosebrock August 14, 2016 at 9:29 am #

      Either BLAS or LAPACK can be used to speedup the Linear Algebra computations. I’ll make note of this.

  10. Jason Scott August 20, 2016 at 1:02 am #

    Note if you are doing this on a mac the install of opencv seems to create the binary as instead of just
    You can safely symlink it into your new anaconda or virtualenv environment as though…

    • Adrian Rosebrock August 22, 2016 at 1:34 pm #

      You can also rename to simply as well.

  11. MaxWeiss August 20, 2016 at 5:45 pm #

    Thank you very much! All is clear and in simply words
    I have read your article regardfully and will try tomorrow!

  12. Geoffrey Anderson August 25, 2016 at 1:02 pm #

    Looking for Keras examples directory. The website, the find command, the pip show Keras command, this blog post by Adrian, but still no examples. Particularly the CIFAR10 (sp?) is the example I want, which was mentioned but not shown on the Keras website. The reason is I am tired of loading toy programs I see everywhere else which presume images are all contained in some monolithic data file so conveniently. In the real world we have image files like jpg and all the Keras and all the H2O examples use some silly little monolithic file load. OK that’s fine for a toy. Now lets really do something with actual images. CIFAR I hope has example of loading image files which are not contained somehow in a CSV file (!).

    Thanks for any info! Sorry I’m so dumb if any of you know the answer and I don’t. (The question is, in case I wrote too much, is where is the examples directory of Keras, particularly the CIFAR example which I hope loads jpg files not some convenient monolithic CSV or other file.)

    • Adrian Rosebrock August 30, 2016 at 12:52 pm #

      We normally distribute the CIFAR10 file as a compressed archive since the images files are tiny (32 x 32 pixels). These images were never meant to be “visually appealing”, only instead used for training data. Again, as I mentioned in reply to another one of your comments, I’ll be doing more advanced tutorials that train networks from scratch later this year.

  13. Nun YoBiz August 30, 2016 at 4:56 pm #

    What absolute crap keras “installs” in a breeze but then never is usable

    • Adrian Rosebrock August 31, 2016 at 1:41 pm #

      Hmmm…why do you say that it’s “unusable”? I’m not sure I agree with that.

  14. Damian September 8, 2016 at 5:03 am #

    Hi Adrian,

    firstly I want to thank you for your entire contribution and reviling cv depths 🙂 I have prior experience with cv, although in more academic way, not in the practical you’re showing here.

    I have a question regarding deep learning and GPU support. I’m using win10 on my daily basis, but all the cv work I’m doing on Ubuntu 16.04 Guest OS (via VirtualBox).

    Have you used GPU support for Deep Learning on VM? I struggled with that and I don’t feel sure if I should follow that path further or just to leave it and use CPU only.

    • Adrian Rosebrock September 8, 2016 at 1:14 pm #

      Most VMs, without a lot of special configuration, will not allow you to access the GPU directly. I recall seeing something about a Docker instance that could access the GPU, but I honestly can’t remember where I saw that. In either case, if you intend on using the GPU for deep learning, make sure you configure the host system rather than the guest OS for optimal performance.

  15. Xi Chen September 11, 2016 at 1:45 am #

    Hi Adrian,

    I followed your steps.

    At last, I can import theano (with GPU)
    I can import cv2 (2.4.x)

    But I cannot import keras

    It says no module named keras
    But I do installed keras

    • Adrian Rosebrock September 12, 2016 at 12:52 pm #

      It sounds like you might not have installed Keras into the Python virtual environment or you have installed Keras into the the Python virtual environment and are forgetting to use the workon command to access the virtual environment.

  16. Peter Hirt September 22, 2016 at 4:05 am #

    Nice tutorial indeed!

    After my install and testing, it comes back and says that Tensorflow module is missing.
    I would like to stay for the moment with Theano and don’t know what I need to do to force keras to use Theano.
    Thanks for helping

    • Adrian Rosebrock September 23, 2016 at 6:59 am #

      Keras should work out of the box by default with Theano. Provided you followed the instructions in this post Keras should be using Theano. Did you already have TensorFlow installed on your system? Either way, try editing your configuration file and setting the backend to be theano.

  17. HV318 October 1, 2016 at 8:58 pm #

    Thanks for this tutorial Adrian!. It is very helpful. Could you please guide me to install tensorflow so that I can use Keras with tensorflow backend instead of Theano.

    • Adrian Rosebrock October 2, 2016 at 8:57 am #

      I don’t have any tutorials dedicated to install TensorFlow, but I’ll certainly consider it for a future tutorial.

  18. Marcus October 3, 2016 at 3:00 pm #

    Does this all work on windows, or do I need a vm. Also it would be good if you created docker containers with all this in !

    • Adrian Rosebrock October 4, 2016 at 6:57 am #

      I don’t recommend using Windows for deep learning (nor do I support Windows on the PyImageSearch blog). If you use a VM you’ll be limited to CPU only, I’m not sure if that is a big problem for you. Otherwise, you might want to look into Amazon EC2 instances that are GPU enabled.

      • Tim October 8, 2017 at 12:23 pm #

        Hi Adrian, would you mind elaborating a bit, why do you prefer Unix-based systems for machine learning?

        • Adrian Rosebrock October 9, 2017 at 12:23 pm #

          Unix-based environments tend to be (1) easier to configure and (2) obtain reproducible results. Most state-of-the-art implementations also used Unix-based environments (as opposed to Windows). I would highly suggest you use a Unix-based environment for computer vision or machine learning.

  19. Harry October 16, 2016 at 12:45 pm #

    Hello Adrian,
    Will you please tell me does it take long to install theano?? When i run this command sudo python install it is taking too much time. more than 15 minutes to install. I am out of my patience.

    • Adrian Rosebrock October 17, 2016 at 4:06 pm #

      Is it just Theano that is taking a long time to install? Run top and see the processes consuming the most CPU. You should see a process related to either Python or C++ compiling and installing. 15 minutes does sound like a long time though.

  20. Johnson October 18, 2016 at 4:16 am #

    hi adrian,
    thanks for the wonderful post..keeps my interest building.
    i keep following your post without fail, but being a newbie i found some difficulties
    i have installed keras, but when importing it, the error tensorflow backend comes.

    though you have mentioned to change the backend from tensor flow to theano, ia int sure of how to do it. could you please help

    • Adrian Rosebrock October 20, 2016 at 9:00 am #

      You need to edit your ~/keras/keras.json file:

      $ nano ~/.keras/keras.json

      And then update the “backend” to “theano”. You might also need to change “image_dim_ordering” to “th”.

      • kara November 4, 2016 at 5:53 am #

        i found the same issue. and now i got the answer 😀
        but if I configure the GPU it cause error also, I solved it simply by removing the theanorc file. I hope it wont matter in the future 🙁

        but what does it mean with th and tf in image dim ordering?

        • Adrian Rosebrock November 4, 2016 at 9:57 am #

          The “th” ordering refers to “Theano” ordering (depth, height, width) whereas “tf” is for “TensorFlow” ordering (height, depth, width).

  21. Abderrahmane October 22, 2016 at 6:11 pm #

    Thanks this is very helpful <3

    • Adrian Rosebrock October 23, 2016 at 10:09 am #

      I’m glad I could help 🙂

  22. T.k November 8, 2016 at 11:19 am #

    Thanks Adrian .
    very helpful post

    you are genius

    • Adrian Rosebrock November 10, 2016 at 8:44 am #

      Thank you for the kind words T.k 🙂

  23. Dattaprasad January 24, 2017 at 3:57 am #

    Dear Adrian,
    You have written excellent blogs on machine learning.
    I am new to keras and opencv. Please guide me.

    For installing keras, we create one virtual environment and complete all the steps given in this blog. My question is to install Opencv, do we create a new virtual environment named “cv”? (Ref. to your blog:
    Can we work in the virtualenv named as keras and inside it create another virtual env. named “cv”?
    Do we need to create two separate virtual envs.? If so, how to link both.
    I mean to say, in a single pyhton code (like the one you have given in the blog: how do we import keras and opencv?
    I need your guidance on the same.

    • Adrian Rosebrock January 24, 2017 at 2:20 pm #

      I would suggest creating a different virtual environment for Keras. From there, sym-link in the bindings into the site-packages directory of your new environment. From there you’ll be able to import both Keras and OpenCV into the same virtual environment.

  24. Debojit February 1, 2017 at 12:47 pm #

    Hi Adrian,
    I am getting the error “fatal error: hdf5.h: no such file or directory” while trying to install h5py in windows. Any suggestion?

    • Adrian Rosebrock February 1, 2017 at 1:01 pm #

      Hi Debojit — I don’t support the Windows OS here on PyImageSearch so I’m not sure regarding the specific HDF5 error. If at all possible I would recommend using a Unix-based environment such as Linux (Ubuntu) or macOS for computer vision development.

  25. Alexander March 13, 2017 at 3:23 pm #

    hi Adrian, great post! Does this instructions work with Python3? I’m referring “venv,pip3” , etc…

    • Adrian Rosebrock March 15, 2017 at 9:07 am #

      Yes, these instructions work for Python 3 as well.

  26. Hesham khalil March 17, 2017 at 5:58 pm #

    you used python 2 to install karas.

    did you used only python 2 in the course ( deep-learning-computer-vision-python-book)?

    and if yes . thats mean Keras , TensorFlow , Theano and mxnet are compatible with python 2.

    which one do you suggest to learn? python 2 or 3 . if i want to dive deep in (deep learning)(covolutional neural network) ? because im confused. i cant choose which one of them

    should i learn.(which one of them is more supperted in AI)

    is there other libraries you suggest for covolutional neural network and machine?

    sorry for my many quistions im a newbie

    • Hesham khalil March 17, 2017 at 6:02 pm #

      same quistion for computer vision. which python version should i use

    • Adrian Rosebrock March 21, 2017 at 7:42 am #

      You can use either Python 2.7 or Python 3. Both are compatible with Keras, TensorFlow, and Theano.

      Python 3 is the future of the Python programming language and Python 2.7 will eventually be phased out. For that reason alone, you should consider learning Python 3. But in all honestly, the just get started learning. The differences between Python 2.7 and Python 3 are minor. Right now you need to start learning — that’s the most important part.

      I would suggest going through Practical Python and OpenCV so you can learn the basics of computer vision and OpenCV. The book is compatible with both Python 2.7 and Python 3.

  27. Rishik Mani May 30, 2017 at 5:04 pm #

    The virtual environment setup had been successfully done. Although, importing keras for the first time did not create the keras.json file.
    So, I went ahead and tried to manually create the file. Again when I try to import keras, it fails saying “No module name keras”. To assure you, I am into the virtual environment.

    • Rishik Mani May 30, 2017 at 5:45 pm #

      My mistake that I did not create the virtual environment in the first place. I first did the whole setup thing and later only created the virtual environment.

      Thanks a lot for this post as I have been struggling for more than a week now setting up keras. I highly appreciate your work.

      • Adrian Rosebrock May 31, 2017 at 1:07 pm #

        Congrats on resolving the issue Rishik! 🙂

  28. Rajib August 14, 2017 at 9:06 pm #

    Great help Adrian. I have been through many tutorials they just assume you have a GPU. You steps show you have thought of various possibilities. Keep it up, Man.

  29. kaisar khatak September 23, 2017 at 5:28 pm #

    Doesn’t pygpu and libgpuarray need to be installed for GPU utilization???

    New syntax for .theanorc:
    Use device=cuda*


    • Adrian Rosebrock September 24, 2017 at 8:45 am #

      For the new version of Theano, yes. At this point I am recommending users to use TensorFlow over Theano.

  30. Ray Van Raamsdonk January 24, 2018 at 1:53 pm #

    For me, a complete beginner, even the first step didn’t work. c:\Users\Ray Van\Anaconda3)> C:\User\Ray Van>mKvirtualenv keras

    I got the message’mkvirtualenv’ is not recognized as internal or external command, operable program or batch file.

    When I saw $ mkvirtualenv keras, I ddin’t even know where to type that in since I never saw the $ prompt anywhere so I just tried it in the Anaconda prompt Window which didn’t work of course. So for a complete beginner it’s definitely not easy. I have Windows 10.

    • Adrian Rosebrock January 24, 2018 at 4:48 pm #

      Hey Ray — it can be pretty challenging to configure your first development environment. In general, I do not recommend using Windows for deep learning or computer vision. Using a Unix-based machine such as Ubuntu or macOS is significantly easier to configure your own development environment. I would recommend using VirtualBox to spin up an Ubuntu machine so you can play around with Ubuntu without having to actually install Ubuntu on your system.

  31. jorgher February 22, 2018 at 11:58 pm #

    Hi Adrian.

    I did the sim-link with no error, but when do the import cv2 in python it doesn’t find it.

    Any guess why.

    I try with two separete environments an the reults are the same.


    • Adrian Rosebrock February 26, 2018 at 2:14 pm #

      Hey jorgher — can you check the “build/lib” directory of your OpenCV compile? It may be the case that the bindings were not compiled.

      • jorgher February 26, 2018 at 10:09 pm #

        I’m not shure about the question you ask, but it is installed in the virtual environmet from where I try to sym-link to the keras environment.

        (cv) jorgher@jorgher:~/.virtualenvs/cv/lib/python3.5/site-packages$ ls *.so

        • Adrian Rosebrock February 27, 2018 at 11:32 am #

          Can you try doing a “ls -l” and see if it points to a valid file? It could be that the sym-link is pointing to a non-existent file.

          • jorgher February 27, 2018 at 9:34 pm #

            I did it and have:

            $ ls -l cv2.solrwxrwxrwx 1 jorgher jorgher 45 ago 27 2017 -> /usr/local/lib/python3.5/site-packages/

            seam that the is not in the virtualenv, so do I need to sym-link from this to the kera virtualenv?

          • jorgher February 28, 2018 at 9:31 am #

            Ok your right I change the path to the one shown for the “ls -l ” and it works.


          • Adrian Rosebrock March 2, 2018 at 11:00 am #

            Awesome, I’m glad it worked jorgher! 🙂

  32. andy April 9, 2018 at 12:08 am #

    youer the best

    • Adrian Rosebrock April 10, 2018 at 12:15 pm #

      Thanks Andy 🙂


  1. ImageNet classification with Python and Keras - PyImageSearch - August 10, 2016

    […] To configure your system to use the state-of-the-art VGG16, VGG19, and ResNet50 networks, make sure you follow my previous tutorial on installing Keras. […]

  2. A simple neural network with Python and Keras - PyImageSearch - September 26, 2016

    […] start, you’ll want to follow this tutorial to ensure you have Keras and the associated prerequisites installed on your […]

  3. Installing Keras with TensorFlow backend - PyImageSearch - November 14, 2016

    […] A few months ago I demonstrated how to install the Keras deep learning library with a Theano backend. […]

Before you leave a comment...

Hey, Adrian here, author of the PyImageSearch blog. I'd love to hear from you, but before you submit a comment, please follow these guidelines:

  1. If you have a question, read the comments first. You should also search this page (i.e., ctrl + f) for keywords related to your question. It's likely that I have already addressed your question in the comments.
  2. If you are copying and pasting code/terminal output, please don't. Reviewing another programmers’ code is a very time consuming and tedious task, and due to the volume of emails and contact requests I receive, I simply cannot do it.
  3. Be respectful of the space. I put a lot of my own personal time into creating these free weekly tutorials. On average, each tutorial takes me 15-20 hours to put together. I love offering these guides to you and I take pride in the content I create. Therefore, I will not approve comments that include large code blocks/terminal output as it destroys the formatting of the page. Kindly be respectful of this space.
  4. Be patient. I receive 200+ comments and emails per day. Due to spam, and my desire to personally answer as many questions as I can, I hand moderate all new comments (typically once per week). I try to answer as many questions as I can, but I'm only one person. Please don't be offended if I cannot get to your question
  5. Do you need priority support? Consider purchasing one of my books and courses. I place customer questions and emails in a separate, special priority queue and answer them first. If you are a customer of mine you will receive a guaranteed response from me. If there's any time left over, I focus on the community at large and attempt to answer as many of those questions as I possibly can.

Thank you for keeping these guidelines in mind before submitting your comment.

Leave a Reply