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 - 为什么函数 rbind.data.frame 在 do.call 中表现不同

python - Tensorflow 组合图像候选区域的非极大值抑制

python - 如何将 tokenizer.fit_on_texts() 应用于包含需要训练的两列对象/字符串的数据框?

python - Python中的NameError,名称未定义

python - Flask 应用程序从 mysql 连接拒绝访问

python - Pygame 显示更新故障?

r - 增加 R 中箱线图名称的大小

python - 如何确定python中的配置文件路径?

r - 如何快速将数据框中的时间列分组为间隔?

tensorflow - Tensorflow - Mac GPU 安装