gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:08 27 4
gpt4 key购买 nike

我是 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com