Fix TensorFlow tf.get_variable() TypeError: Tensor objects are only iterable when eager execution is enabled

By | August 7, 2020

When you are using tensorflow tf.get_variable() function to create a new variable, you may get this TypeError: Tensor objects are only iterable when eager execution is enabled. In this tutorial, we will introduce you how to fix it.

Look at example code below:

import tensorflow as tf
import numpy as np   
  
w1 = tf.Variable(tf.random_normal(shape=[2,2], mean=0, stddev=1), name='w')  
w2 = tf.get_variable('w',tf.random_normal(shape=[3,3], mean=0, stddev=1))

with tf.Session() as sess:  
    sess.run(tf.global_variables_initializer())
    sess.run(tf.local_variables_initializer())
   
    print("w1 = ")
    print(w1.name)
    print(w1.eval())
    print("w2 = ")
    print(w2.name)

Run this code, you will find this code will report an error:

w2 = tf.get_variable(‘w’,tf.random_normal(shape=[3,3], mean=0, stddev=1))

The error message is:

Fix TensorFlow tf.get_variable() TypeError - Tensor objects are only iterable when eager execution is enabled

In order to fix this error, we should look at the initialized method of tf.get_variable().

The tf.get_variable() is defined as:

how tf.get_variable() initialize a tensor when its initializer is None

We can find the second parameter of it is a shape, which is an iterable object.

If you plan to know more about tf.get_variable(), you can read this tutorial:

Understand tf.get_variable(): A Beginner Guide

Look at code above:

w2 = tf.get_variable('w',tf.random_normal(shape=[3,3], mean=0, stddev=1))

It means the shape is tf.random_normal(shape=[3,3], mean=0, stddev=1). That is wrong.

How to fix this TypeError?

It is very easy, making the initializer of it.

Modify code above to:

w2 = tf.get_variable('w', initializer = tf.random_normal(shape=[3,3], mean=0, stddev=1))

Then you will find this TypeError is fixed.

Leave a Reply

Your email address will not be published. Required fields are marked *