给定一个张量 [5,4,3,4],如何生成一个常量张量,其中每行有 n 个 1 和 m 个零,n=5,4,3,4,m=0,1,2,1。
Given a tensor [5,4,3,4], how to generate a constant tensor where each row has n ones and m zeros, n=5,4,3,4, and m=0,1,2,1.
给定一个张量 A:[5,4,3,4]
,我想创建一个张量 B:
[[1,1,1,1,1],
[1,1,1,1,0],
[1,1,1,0,0],
[1,1,1,1,0]]
B的每一行有n个,其中n = 5,4,3,4根据A。其余位置用零填充。
我可以在 tensorflow 中实现吗?如何实现?
您可以为此使用 tf.sequence_mask。
import tensorflow as tf
A = tf.constant([5,4,3,4], dtype=tf.int32)
max_len = tf.reduce_max(A)
B = tf.sequence_mask(A, max_len, dtype=tf.int32)
with tf.Session() as sess:
print(sess.run(B))
打印:
[[1 1 1 1 1]
[1 1 1 1 0]
[1 1 1 0 0]
[1 1 1 1 0]]
给定一个张量 A:[5,4,3,4]
,我想创建一个张量 B:
[[1,1,1,1,1],
[1,1,1,1,0],
[1,1,1,0,0],
[1,1,1,1,0]]
B的每一行有n个,其中n = 5,4,3,4根据A。其余位置用零填充。
我可以在 tensorflow 中实现吗?如何实现?
您可以为此使用 tf.sequence_mask。
import tensorflow as tf
A = tf.constant([5,4,3,4], dtype=tf.int32)
max_len = tf.reduce_max(A)
B = tf.sequence_mask(A, max_len, dtype=tf.int32)
with tf.Session() as sess:
print(sess.run(B))
打印:
[[1 1 1 1 1]
[1 1 1 1 0]
[1 1 1 0 0]
[1 1 1 1 0]]