假设我有以下两个向量,一个用于开始索引,另一个用于结束索引
start_index = [1, 1, 2]
end_index = [3, 4, 3]
下面是最终 bool 矩阵的形状
shape = [3, 6]
我想生成以下 bool 矩阵
bool_mat = [[False, True, True, True, False, False]
[False, True, True, True, True, False]
[False, False, True, True, False, False]]
对于每一行,True 从 start_index 中的索引开始,到 end_index 中的索引结束,其他地方为 False,
bool_mat[i, start_index[i]:end_index[i]+1] = True
如何在 TensorFlow 中执行此操作?谢谢!
最佳答案
你可以这样做:
import tensorflow as tf
start_index = tf.constant([1, 1, 2])
end_index = tf.constant([3, 4, 3])
shape = tf.constant([3, 6])
col = tf.range(shape[1])
result = (col >= start_index[:, tf.newaxis]) & (col <= end_index[:, tf.newaxis])
with tf.Session() as sess:
print(sess.run(result))
输出:
[[False True True True False False]
[False True True True True False]
[False False True True False False]]
关于python - Tensorflow:给定真实索引创建 bool 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53110770/