Create a Random Constant Tensor – TensorFlow Tutorial

By | June 12, 2019

In tensorflow, you can use tf.constant() function to create a constant tensor. However, if you want to create a random constant tensor, you must careful.

tf.constant(
    value,
    dtype=None,
    shape=None,
    name='Const',
    verify_shape=False
)

Note: in tf.constant, value parameter can not be a tensor, it can be a constant value, a list or a numpy of values of type dtype.

Look example code below:

import tensorflow as tf
import numpy as np
#value is a tensor
c_train = tf.constant(tf.random_uniform([2,3], -1, 1), dtype=tf.float32, name='c_train')

init = tf.global_variables_initializer() 
init_local = tf.local_variables_initializer()
with tf.Session() as sess:
    sess.run([init, init_local])
    c = sess.run([c_train])
    print c

You can get error:

TypeError: Expected float32, got list containing Tensors of type ‘_Message’ instead.

But if you use numpy.

import tensorflow as tf
import numpy as np
c_train = tf.constant(np.random.uniform(-1,1,[2,3]), dtype=tf.float32, name='c_train')

init = tf.global_variables_initializer() 
init_local = tf.local_variables_initializer()
with tf.Session() as sess:
    sess.run([init, init_local])

    c = sess.run([c_train])
    print c

The output is

[array([[-0.4548781 , 0.5711501 , 0.6640451 ],
[ 0.3127074 , -0.58692014, 0.5817746 ]], dtype=float32)]

Leave a Reply