【问题标题】:pass the values of a tensor to the lower traingular part of 2 dimentional tensor将张量的值传递给二维张量的下三角部分
【发布时间】:2019-07-31 15:29:10
【问题描述】:

我是 PythonTensorflow 的新手,我正在开发一个 Python 项目。假设我有向量 X,

X=[x1,x2,x3]

并希望将其转换为主对角线为一个的下三角矩阵A

A=[ [ 1, 0, 0] , [ x1, 1, 0], [ x2, x3, 1] ]。

R 中我使用了这个简单的代码:

A<-diag(3)
A[lower.tri(A)] <- X.

在我的项目中,X 是一个张量,作为 Tensorflow 中神经网络的输出。

X <- layer_dense(hidden layer, dec_dim)

所以,如果可能的话,我想像以前一样在 Keras 或 Tensorflow 中这样做。例如在 Keras 中,

from keras import backend as K
 A= K.eye(3)      

但我在 Tensorflow 或 Keras 中找不到第二个命令的解决方案。由于运行时间,我不想在这里使用 For 循环。有什么简短的解决方案吗?你对此有什么想法吗?先谢谢了。

【问题讨论】:

    标签: python r tensorflow keras


    【解决方案1】:

    您需要获取X 的所有索引并将它们应用到A

    from keras import backend as K
    import tensorflow as tf
    
    n = 3
    X = tf.constant([1,2,3],tf.float32)
    A = K.eye(n)
    
    column,row = tf.meshgrid(tf.range(n),tf.range(n))
    indices = tf.where(tf.less(column,row))
    # [[1 0]
    #  [2 0]
    #  [2 1]]
    
    A = tf.scatter_nd(indices,X,(n,n)) + A
    # if your lower triangular part of A not equal 0, you can use follow code.
    # tf.matrix_band_part(A, 0, -1)==> Upper triangular part
    # A = tf.scatter_nd(indices,X,(n,n)) + tf.matrix_band_part(A, 0, -1)
    
    print(K.eval(A))
    # [[1. 0. 0.]
    #  [1. 1. 0.]
    #  [2. 3. 1.]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-29
      • 2021-10-09
      • 1970-01-01
      • 2017-10-12
      • 2019-09-15
      • 2020-09-26
      • 1970-01-01
      • 2017-08-18
      相关资源
      最近更新 更多