Error in Tensorflow using variables: List of Tensors when single Tensor expected

1. Background:

import tensorflow as tf
a = tf.constant(tf.random_normal([2, 2]))    # Wrong
print(a)

An error occurred when passing tf.random_normal to tf.constant:
TypeError: List of Tensors when single Tensor expected

 

2. The cause of the problem:

See how tf.constant() and tf.random_normal() are used

2.1 tf.random_normal function definition:

def random_normal(shape,
                  mean=0.0,
                  stddev=1.0,
                  dtype=dtypes.float32,
                  seed=None,
                  name=None):
  • Returns: A tensor of the specified shape filled with random normal values.

2.2 tf.constant function definition:

def constant(value, dtype=None, shape=None, name="Const", verify_shape=False)
  • value: A constant value (or list) of output type dtype.
  • Returns: A Constant Tensor.

2.3 The cause of the problem:

Conclusion: Because the return value of tf.random_normal is a Tensor, but the parameter passed in by tf.constat is that the two types of the list do not match, an error occurs.

3. How to solve:

3.1 Method 1:

Use NumPy to generate the random value and put it in a tf.constant()

some_test = tf.constant(
    np.random.normal(loc=0.0, scale=1.0, size=(2, 2)).astype(np.float32))

3.2 Method 2:

Potentially faster, as it can use the GPU to generate the random numbers,Use TensorFlow to generate the random value and put it in a tf.Variable

some_test = tf.Variable(
    tf.random_normal([2, 2], mean=0.0, stddev=1.0, dtype=tf.float32)
sess.run(some_test.initializer)

View the definition of the tf.Variable function:

def __init__(self,
               initial_value=None,
               trainable=True,
               collections=None,
               validate_shape=True,
               caching_device=None,
               name=None,
               variable_def=None,
               dtype=None,
               expected_shape=None,
               import_scope=None,
               constraint=None):
               ...
               )

args: initial_value: A Tensor, or Python object convertible to a Tensor,which is the initial value for the Variable.
Next time you encounter this kind of function parameter problem, you must check how the function is used, and what the formal parameters and return values ​​are.


Read More:

Leave a Reply

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