# 2 Ways to Expand a Tensor in Tensorflow 2

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``````

## What’s Next?

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

Subscribe
Notify of
Inline Feedbacks