3 Ways to Create Random Tensors in Tensorflow 2

Last updated on August 23, 2021 Guest Contributor Loading... Post a comment

This article shows you a couple of different ways to create random tensors with Tensorflow 2.

Using tf.random.Generator

Example:

import tensorflow as tf

test = tf.random.Generator.from_seed(123)
test = test.normal(shape=(2, 3, 4))
print(test)

Output:

tf.Tensor(
[[[ 0.8673864  -0.29899067 -0.93103355 -1.5828488 ]
  [ 1.2481192  -0.67706424  0.01912649 -0.29333332]
  [-0.35438988  0.07048975 -0.4882456  -0.56108433]]

 [[-0.9890895  -0.47498497 -1.3177569  -1.748288  ]
  [-1.6292503   0.48826346 -1.8867823   0.18151656]
  [ 0.24483992  0.37554735  1.6184237   0.34223038]]], shape=(2, 3, 4), dtype=float32)

Shuffling the Order of Elements in a Tensor

Another technique to produce a random tensor is to shuffle an existing tensor along its first dimension. The randomness is not high as using tf.random.Generator is in the example above but it is quite useful in some scenarios.

Example:

import tensorflow as tf

original = tf.constant([
                               [1, 2],
                               [3, 4],
                               [5, 6],
                               [7, 8],
                               [9, 10]
])

# Setting seed to get the same result everytime we run the code
tf.random.set_seed(123)
shuffled = tf.random.shuffle(original)
print(shuffled)

Output:

tf.Tensor(
[[ 3  4]
 [ 7  8]
 [ 5  6]
 [ 1  2]
 [ 9 10]], shape=(5, 2), dtype=int32)

Creating Random Tensors from Numpy Arrays

You may not like this method but it’s good to know that it works.

Example:

import tensorflow as tf
import numpy as np

np.random.seed(10)
a = np.random.randint(1, 100, size=24)
b = tf.constant(a, shape=(2, 3, 4))
print(b)

Output:

tf.Tensor(
[[[10 16 65 29]
  [90 94 30  9]
  [74  1 41 37]]

 [[17 12 55 89]
  [63 34 73 79]
  [50 52 55 78]]], shape=(2, 3, 4), dtype=int64)

Conclusion

The examples above demonstrated how to make random tensors with Tensorflow. Add an additional resource, you can visit Tensorflow’s official documentation on tf.random.

If you’d like to learn more about the basics of Python and machine learning stuff, take a look at the following articles:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles