python - 将张量的值传递给二维张量的下三角部分

标签 python r tensorflow keras

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

X=[x1,x2,x3]

并想将其转换为主对角线为1的下三角矩阵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 循环。有什么简短的解决方案吗?你知道吗?提前致谢。

最佳答案

您需要获取 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.]]

关于python - 将张量的值传递给二维张量的下三角部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57294276/

相关文章:

r - 如何找到每个因子级别的行元素从负数切换到正数(循环)的次数

tensorflow - 如何在 TensorFlow 图的开头执行 "append"Op?

Python -> 类型错误 : unsupported operand type(s) for ^

python - Google App Engine 上的替代 Python 图像库?

R 写入 stdout 非常慢。有什么改善方法吗?

python - 在 TensorFlow 中将 stop_gradient 与 AdamOptimizer 结合使用

python - 如何在 TF 2.2 中创建自定义 PreprocessingLayer

python - 以编程方式登录亚马逊

python - setGeometry() 紧接在 addWidget() 问题之后

r - databricks 上的 sql sparklyr sparkr 数据帧转换