Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to expand dimensions in Tensorflow

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading