【问题标题】:how to drop the lower triangle(include diag) of a 2d tensor in tensorflow1.x?如何在 tensorflow1.x 中删除 2d 张量的下三角形(包括 diag)?
【发布时间】:2020-06-19 01:17:48
【问题描述】:

例如我有一个张量:

import tensorflow.compat.v1 as tf
import numpy as np
a = tf.constant(np.array([[1,2,3,4,5],
                          [2,2,4,5,6],
                          [3,4,3,6,7],
                          [4,5,6,4,8],
                          [5,6,7,8,5]))

它是对称的。现在只想看abs(i-j)>s的部分,其中i,j表示行和col索引,s是para。

对称性等于 j - i >s。

所以如果设置 s = 2,我想将a 转换为:

        tf.constant(np.array([[0,0,0,4,5],
                              [0,0,0,0,6],
                              [0,0,0,0,0],
                              [0,0,0,0,0],
                              [0,0,0,0,0]))

在 tf1.x 中是否有任何令人信服的方法可以做到这一点?德克萨斯!

【问题讨论】:

标签: python tensorflow deep-learning


【解决方案1】:

你可以这样做:

import tensorflow.compat.v1 as tf
import numpy as np

a = tf.constant(np.array([[1, 2, 3, 4, 5],
                          [2, 2, 4, 5, 6],
                          [3, 4, 3, 6, 7],
                          [4, 5, 6, 4, 8],
                          [5, 6, 7, 8, 5]]))
s = 2
shape = tf.shape(a)
i, j = tf.meshgrid(tf.range(shape[0]), tf.range(shape[1]), indexing='ij')
mask = tf.math.abs(i - j) > s
result = a * tf.dtypes.cast(mask, a.dtype)
tf.print(result)
# [[0 0 0 4 5]
#  [0 0 0 0 6]
#  [0 0 0 0 0]
#  [4 0 0 0 0]
#  [5 6 0 0 0]]

结果与您显示的不同,但它对应于公式abs(i - j) > s。如果您只想要上部,请改为:

mask = j - i > s

【讨论】:

    猜你喜欢
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多