【问题标题】:What is the simplest way to create an upper triangle tensor with Tensorflow?用 Tensorflow 创建上三角张量的最简单方法是什么?
【发布时间】:2022-01-11 14:00:25
【问题描述】:

和这个question类似,我要转换这个张量

tensor = tf.ones((5, 5))
tf.Tensor(
[[1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]], shape=(5, 5), dtype=float32)

到其他地方都带有 1 和 0 的上三角张量:

tf.Tensor(
[[1. 1. 1. 1. 1.]
 [0. 1. 1. 1. 1.]
 [0. 0. 1. 1. 1.]
 [0. 0. 0. 1. 1.]
 [0. 0. 0. 0. 1.]], shape=(5, 5), dtype=float32)

有什么想法吗?

【问题讨论】:

    标签: tensorflow triangular


    【解决方案1】:

    你可以使用tf.linalg.band_part:

    >>> tensor = tf.ones((5, 5))
    >>> tf.linalg.band_part(tensor, 0, -1)
    <tf.Tensor: shape=(5, 5), dtype=float32, numpy=
    array([[1., 1., 1., 1., 1.],
           [0., 1., 1., 1., 1.],
           [0., 0., 1., 1., 1.],
           [0., 0., 0., 1., 1.],
           [0., 0., 0., 0., 1.]], dtype=float32)>
    

    请注意,您可以使用该函数从张量中提取任意数量的对角线。有用的案例包括:

    tf.linalg.band_part(input, 0, -1) ==> Upper triangular part.
    tf.linalg.band_part(input, -1, 0) ==> Lower triangular part.
    tf.linalg.band_part(input, 0, 0) ==> Diagonal.
    

    【讨论】:

      猜你喜欢
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多