简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM