AttributeError: module 'tensorflow' has no attribute 'GraphDef' [SOLVED]

In this article, we have demonstrated how to fix the error "AttributeError: module 'tensorflow' has no attribute 'GraphDef'" while running a TensorFlow code.

Table of contents:

  1. Error
  2. Reason for Error
  3. Fix for the error

In short, there are two conversions:

tf.GraphDef()      => tf.compat.v1.GraphDef()
tf.gfile.GFile()   => tf.compat.v2.io.gfile.GFile()

Error

Error on running a TensorFlow code:

AttributeError: module 'tensorflow' has no attribute 'GraphDef'

Reason for Error

The reason for the error is that the code you are running is using an old TensorFlow API. The code follows the API of TensorFlow v1.x while the TensorFlow environment has version v2.x.

This particular API for Session has been renamed in TFv2.x / moved to compat.v1.

Fix for the error

Fix 1

To fix the error, replace the code line tf.GraphDef() and tf.gfile.GFile() with updated APIs.

tf.GraphDef()

to

tf.compat.v1.GraphDef()

Second conversion:

tf.gfile.GFile()

to

tf.compat.v2.io.gfile.GFile()

So, in short, there are two conversions:

tf.GraphDef()      => tf.compat.v1.GraphDef()
tf.gfile.GFile()   => tf.compat.v2.io.gfile.GFile()

Fix 2

If you do not want to update the code, then you can place the following code snippet at the top of the file:

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

This will update the API (note the use of compat.v1) and disable behaviour specific to version v2.

Fix 3

An alternative fix is to use TensorFlow version 1.x instead of 2.x. You can install the previous version of TensorFlow using pip command:

pip install tensorflow==1.15.5

If you want to build TensorFlow from source, clone the TensorFlow code and checkout to a previous version and then, build it.

git clone https://github.com/tensorflow/tensorflow.git
git checkout r1.15

Following the steps in this guide to build TensorFlow locally: build guide.

With this article at OpenGenus, you must have fixed the error easily. Continue working with TensorFlow code.