简体   繁体   English

如何在Tensorflow中扩展维度

[英]How to expand dimensions in Tensorflow

I have this tensor A:我有这个张量 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) .我想创建一个掩码以添加到另一个形状为(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.也就是说,我想将每个数字扩展到 1000 个,例如,在张量 A 中,将每个 0 更改为 1000 个零的维度,并在每个 1 中,将每个更改为 1000 个 1 的维度。 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基本上,我想要做的是将张量 A 从形状(2, 18)转换为形状(2, 18, 1000) ,这 1000 个值为 0 或 1

Simply use tf.expand_dims只需使用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关于广播参见,例如,这个 numpy 教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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