/TensorFlow Python

Constants, Sequences, and Random Values

Note: Functions taking Tensor arguments can also take anything accepted by tf.convert_to_tensor.

Constant Value Tensors

TensorFlow provides several operations that you can use to generate constants.


Random Tensors

TensorFlow has several ops that create random tensors with different distributions. The random ops are stateful, and create new random values each time they are evaluated.

The seed keyword argument in these functions acts in conjunction with the graph-level random seed. Changing either the graph-level seed using tf.set_random_seed or the op-level seed will change the underlying seed of these operations. Setting neither graph-level nor op-level seed, results in a random seed for all operations. See tf.set_random_seed for details on the interaction between operation-level and graph-level random seeds.


# Create a tensor of shape [2, 3] consisting of random normal values, with mean
# -1 and standard deviation 4.
norm = tf.random_normal([2, 3], mean=-1, stddev=4)

# Shuffle the first dimension of a tensor
c = tf.constant([[1, 2], [3, 4], [5, 6]])
shuff = tf.random_shuffle(c)

# Each time we run these ops, different results are generated
sess = tf.Session()

# Set an op-level seed to generate repeatable sequences across sessions.
norm = tf.random_normal([2, 3], seed=1234)
sess = tf.Session()
sess = tf.Session()

Another common use of random values is the initialization of variables. Also see the Variables How To.

# Use random uniform values in [0, 1) as the initializer for a variable of shape
# [2, 3]. The default type is float32.
var = tf.Variable(tf.random_uniform([2, 3]), name="var")
init = tf.global_variables_initializer()

sess = tf.Session()

© 2018 The TensorFlow Authors. All rights reserved.
Licensed under the Creative Commons Attribution License 3.0.
Code samples licensed under the Apache 2.0 License.