gpt4 book ai didi

arrays - tensorflow 创建不同长度的掩码

转载 作者:行者123 更新时间:2023-12-04 01:24:45 25 4
gpt4 key购买 nike

我在 tensorflow 中有一个长度张量,假设它看起来像这样:

[4, 3, 5, 2]

我希望创建一个 1 和 0 的掩码,其 1 的数量对应于该张量的条目,由 0 填充至总长度为 8。即我想创建这个张量:
[[1,1,1,1,0,0,0,0],
[1,1,1,0,0,0,0,0],
[1,1,1,1,1,0,0,0],
[1,1,0,0,0,0,0,0]
]

我该怎么做?

最佳答案

这可以通过使用多种 TensorFlow transformations 来实现。 :

# Make a 4 x 8 matrix where each row contains the length repeated 8 times.
lengths = [4, 3, 5, 2]
lengths_transposed = tf.expand_dims(lengths, 1)

# Make a 4 x 8 matrix where each row contains [0, 1, ..., 7]
range = tf.range(0, 8, 1)
range_row = tf.expand_dims(range, 0)

# Use the logical operations to create a mask
mask = tf.less(range_row, lengths_transposed)

# Use the select operation to select between 1 or 0 for each value.
result = tf.select(mask, tf.ones([4, 8]), tf.zeros([4, 8]))

关于arrays - tensorflow 创建不同长度的掩码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34128104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com