tensorflow - 创建张量,其中给定索引之前的所有元素均为 1,其余元素均为 0

标签 tensorflow mask tensor one-hot-encoding

我有一个占位符 lengths = tf.placeholder(tf.int32, [10])。分配给此占位符的 10 个值中的每一个都 <= 25。我现在想要创建一个二维张量,称为 masks,形状为 [10, 25],其中 10 个向量中的每一个长度 25 将前 n 元素设置为 1,其余设置为 0 - 其中 nlengths 中的相应值。

使用 TensorFlow 的内置方法执行此操作的最简单方法是什么?

例如:

lengths = [4, 6, 7, ...]

-> masks = [[1, 1, 1, 1, 0, 0, 0, 0, ..., 0],
            [1, 1, 1, 1, 1, 1, 0, 0, ..., 0],
            [1, 1, 1, 1, 1, 1, 1, 0, ..., 0],
            ...
           ]

最佳答案

您可以将长度 reshape 为 (10, 1) 张量,然后将其与另一个序列/索引 0,1,2,3,...,25 进行比较,由于广播,这将导致 <如果索引小于长度,则为 true,否则为 False;然后您可以将 bool 结果转换为 10:

lengths = tf.constant([4, 6, 7])
n_features = 25
​
import tensorflow as tf
​
masks = tf.cast(tf.range(n_features) < tf.reshape(lengths, (-1, 1)), tf.int8)

with tf.Session() as sess:
    print(sess.run(masks))

#[[1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
# [1 1 1 1 1 1 0 0 0 0 0 0 0 0 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]]

关于tensorflow - 创建张量,其中给定索引之前的所有元素均为 1,其余元素均为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46792988/

相关文章:

tensorflow - TensorFlow 中图像张量的形状是什么

tensorflow - Keras 中基于 F1/AUC 纪元的指标

xcode - Swift (Xcode) 中带有标签蒙版的多色渐变

python - Numpy/PyTorch - 如何用不同维度的索引分配值?

machine-learning - 我的问题属于机器学习或深度学习的哪一类?

python - 二元分类问题的准确率高得令人怀疑

python - 如何使用非大写 p 的 TensorFlow tf.print?

ios - 旋转时自动调整 UITableView 标题的大小(iPad 上的 MoSTLy)

javascript - webkit mask

matlab - 如何在 MATLAB 中将张量的维度折叠为标量