2 Ways to Expand a Tensor in Tensorflow 2

Last updated on August 24, 2021 A Goodman Loading... Post a comment

Expanding a tensor means adding a dimension (or an axis) to it.

The two examples below show you two different ways to expand a tenor in Tensorflow 2.

Example 1: Using tf.newaxis

The code:

import tensorflow as tf

rank_2_tensor = tf.constant([
                             [1, 2],
                             [3, 4]
])

rank_3_tensor = rank_2_tensor[..., tf.newaxis]
print('rank_3_tensor: ', rank_3_tensor)
print('shape: ', rank_3_tensor.shape)
print('ndim: ', rank_3_tensor.ndim)

Output:

rank_3_tensor:  tf.Tensor(
[[[1]
  [2]]

 [[3]
  [4]]], shape=(2, 2, 1), dtype=int32)
shape:  (2, 2, 1)
ndim:  3

Example 2: Using tf.expand_dims function

The Code:

import tensorflow as tf

rank_2_tensor = tf.constant([
                             [0, 2],
                             [5, 7]
])

# Expand the axis 0
rank_3_tensor = tf.expand_dims(rank_2_tensor, axis=0)
print('rank_3_tensor', rank_3_tensor)
print('shape', rank_3_tensor.shape)
print('ndim', rank_3_tensor.ndim)

# Expand the final axis
rank_3_tensor_final = tf.expand_dims(rank_2_tensor, axis=-0)
print('rank_3_tensor_final', rank_3_tensor)
print('shape', rank_3_tensor.shape)
print('ndim', rank_3_tensor.ndim)

Output:

rank_3_tensor tf.Tensor(
[[[0 2]
  [5 7]]], shape=(1, 2, 2), dtype=int32)
shape (1, 2, 2)
ndim 3

rank_3_tensor_final tf.Tensor(
[[[0 2]
  [5 7]]], shape=(1, 2, 2), dtype=int32)
shape (1, 2, 2)
ndim 3

You can find more information about tf.expand_dims at the Tensorflow’s documentation.

What’s Next?

Further reading:

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

You May Also Like