【问题标题】:Tensorflow: create boolean matrix given True indicesTensorflow:给定真实索引创建布尔矩阵
【发布时间】:2019-04-06 05:42:15
【问题描述】:

假设我有以下两个向量,一个用于起始索引,另一个用于结束索引

start_index = [1, 1, 2]
end_index = [3, 4, 3]

下面是最终布尔矩阵的形状

shape = [3, 6]

我想生成下面的布尔矩阵

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 中做到这一点?谢谢!

【问题讨论】:

  • start_index 和 end_index 是列表还是张量?

标签: python tensorflow


【解决方案1】:

你可以这样做:

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]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2013-11-18
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 2013-06-30
    相关资源
    最近更新 更多