python - Tensorflow:给定真实索引创建 bool 矩阵

标签 python tensorflow

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

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/

相关文章:

python - 导入错误 : No module named '_pywrap_tensorflow_internal'

python - keras loss 是否必须每批输出一个标量或整个批处理输出一个标量?

machine-learning - 如何记录 Tensorflow 中 sess.run 期间每次迭代的准确性?

python - 有什么好方法对时间序列股票数据进行分组吗?

python - cssutils parseString 媒体查询失败。 - 错误 CSSStyleDeclaration : Unexpected token

python - Keras 使用 set seed 得到不同的结果

tensorflow - 在神经网络中使用卷积层

python - Python方式不打印错误消息

python - Django 模板中的行着色基于 "ifchanged"?

Python - 通过 SSH 读取二进制文件