Home > Net >  How to expand dimensions in Tensorflow
How to expand dimensions in Tensorflow

Time:02-18

I have this tensor A:

<tf.Tensor: shape=(2, 18), dtype=float32, numpy=
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1.,
        1., 1.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0.]], dtype=float32)>

I want to create a mask to add to another tensor with shape (2, 18, 1000). That is, I want to expand each number to 1000 of them, so for example, in tensor A, change each 0 to a dimension of 1000 zeros, and in each 1, change each of them to a dimension of 1000 ones. How could I do it?

Edit

Basically, what I want to do is transform tensor A from shape (2, 18) to shape (2, 18, 1000) with those 1000 values being 0 or 1

CodePudding user response:

Simply use tf.expand_dims

import tensorflow as tf

a = tf.constant([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1.,
        1., 1.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0.]])
b = tf.random.normal(shape=[2, 18, 1000])
c = tf.expand_dims(a, axis=2)   b
c.shape
# TensorShape([2, 18, 1000])

About broadcasting see, for example, this numpy tutorial

  • Related