Create a Random Float Number in TensorFlow – TensorFlow Tutorial

By | October 29, 2020

We may need to create a random float number in tensorflow. In this tutorial, we will introduce you how to create.

Preliminary

You should install tensorflow and import library.

import tensorflow as tf

We will use tf.random_uniform() to create a random float number.

Create a random float number in tensorflow

random_tensor = tf.random_uniform([], 0.2, 1. + 0.2)
init = tf.global_variables_initializer() 
init_local = tf.local_variables_initializer()
with tf.Session() as sess:
    sess.run([init, init_local])
    print(sess.run(random_tensor))

Run this code, you may get a float number:0.91324836

We should notice: tf.random_uniform() function also can generate a multiple dimension tensor. Such as 2 * 3.

tf.random_uniform(
    shape,
    minval=0,
    maxval=None,
    dtype=tf.float32,
    seed=None,
    name=None
)

This function will generate values follow a uniform distribution in the range [minval, maxval)

We also can create a random constant in tensorflow, here is an example:

Create a Random Constant Tensor in TensorFlow

Leave a Reply

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