【问题标题】:Get the diagonal of a matrix in TensorFlow在TensorFlow中获取矩阵的对角线
【发布时间】:2016-02-15 11:10:58
【问题描述】:

有没有办法在 TensorFlow 中提取方阵的对角线?也就是说,对于这样的矩阵:

[
 [0, 1, 2],
 [3, 4, 5],
 [6, 7, 8]
]

我要获取元素:[0, 4, 8]

在 numpy 中,这通过np.diag 非常简单:

在TensorFlow中,有一个diag function,但它只在对角线上用参数中指定的元素形成一个新矩阵,这不是我想要的。

我可以想象如何通过跨步来做到这一点......但我没有看到 TensorFlow 中的张量跨步。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    这可能是一种解决方法,但有效。

    >> sess = tensorflow.InteractiveSession()
    >> x = tensorflow.Variable([[1,2,3],[4,5,6],[7,8,9]])
    >> x.initializer.run()
    >> z = tensorflow.pack([x[i,i] for i in range(3)])
    >> z.eval()
    array([1, 5, 9], dtype=int32)
    

    【讨论】:

    • 不幸的是,此操作可能非常缓慢,但不知道为什么。
    【解决方案2】:

    目前可以使用tf.diag_part 提取对角线元素。这是他们的例子:

    """
    'input' is [[1, 0, 0, 0],
                [0, 2, 0, 0],
                [0, 0, 3, 0],
                [0, 0, 0, 4]]
    """
    
    tf.diag_part(input) ==> [1, 2, 3, 4]
    

    旧答案(当 diag_part 时)不可用(如果您想实现现在不可用的东西,仍然相关):

    看了math operationstensor transformations之后,好像没有这样的操作。即使您可以使用矩阵乘法提取此数据,它也不会有效(获取对角线为O(n))。

    你有三种方法,从易到难。

    1. 评估张量,用 numpy 提取对角线,用 TF 构建变量
    2. 以 Anurag 建议的方式使用 tf.pack(也使用 tf.shape 提取值 3
    3. 编写自己的op in C++,重新构建 TF 并在本地使用它。

    【讨论】:

    • 听起来很合理。谢谢!
    【解决方案3】:

    使用gather 操作。

    x = tensorflow.Variable([[1,2,3],[4,5,6],[7,8,9]])
    x_flat = tf.reshape(x, [-1])  # flatten the matrix
    x_diag = tf.gather(x, [0, 3, 6])
    

    【讨论】:

      【解决方案4】:

      根据上下文,掩码可能是“取消”矩阵的对角元素的好方法,尤其是如果您打算无论如何都减少它:

      mask = tf.diag(tf.ones([n]))
      y = tf.mul(mask,y)
      cost = -tf.reduce_sum(y)
      

      【讨论】:

        【解决方案5】:

        使用 tensorflow 0.8 可以使用 tf.diag_part() 提取对角线元素(参见 documentation

        更新

        对于 tensorflow >= r1.12 它的tf.linalg.tensor_diag_part(参见documentation

        【讨论】:

        • 我更新了链接。似乎他们将函数重命名/移动到 linalg-package
        【解决方案6】:

        使用 tf.diag_part()

        with tf.Session() as sess:
            x = tf.ones(shape=[3, 3])
            x_diag = tf.diag_part(x)
            print(sess.run(x_diag ))
        

        【讨论】:

          猜你喜欢
          • 2023-04-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多