[英]Dynamically build tensor from 1s and 0s in TensorFlow
Given an integer tensor like x = [2 0 1 0]
and a constant C = 3
I would like to build a tensor给定一个 integer 张量,例如
x = [2 0 1 0]
和一个常数C = 3
我想构建一个张量
[[1 1 0],
[0 0 0],
[1 0 0],
[0 0 0]]
So C
is the number of columns, len(x)
is the number of rows.所以
C
是列数, len(x)
是行数。 Each entry of x
specifies a number of 1s that a row should start with, while the remainder of that row is to be filled up with 0s. x
的每个条目指定一行应以 1 开头的数量,而该行的其余部分将用 0 填充。
The best TensorFlow code that I've come up with is this:我想出的最好的 TensorFlow 代码是这样的:
x = tf.constant([2, 0, 1, 0])
C = 3
r = tf.map_fn(fn=lambda i: tf.concat([tf.ones(i, dtype=tf.int32),
tf.zeros(C-i, dtype=tf.int32)],
axis=0),
elems=x)
This works OK:这工作正常:
In [6]: print(r)
tf.Tensor(
[[1 1 0]
[0 0 0]
[1 0 0]
[0 0 0]], shape=(4, 3), dtype=int32)
But is there a straightforward way to achieve the same result without tf.map_fn()
or any loops, but with vectorized ops like tf.scatter_nd()
or similar?但是有没有一种直接的方法可以在没有
tf.map_fn()
或任何循环的情况下实现相同的结果,但使用像tf.scatter_nd()
或类似的矢量化操作?
tf.sequence_mask()
produces the desired result: tf.sequence_mask()
产生所需的结果:
In [8]: s = tf.sequence_mask(x, maxlen=C, dtype=tf.int32)
In [9]: print(s)
tf.Tensor(
[[1 1 0]
[0 0 0]
[1 0 0]
[0 0 0]], shape=(4, 3), dtype=int32)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.