tensorflow 中向量Jacobian

vsnjm48y  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(128)

我想这个问题从来没有得到过正确的回答(8see How to calculate the Jacobian of a vector function with tensorflow or Computing Jacobian in TensorFlow 2.0),所以我将再试一次:
我想计算向量值函数z = [x**2 + 2*y, y**2]的雅可比矩阵,也就是说,我想得到偏导数的矩阵

[[2x, 0],
 [2, 2y]]

(由于是自动微分,该矩阵将用于特定点)。

with tf.GradientTape() as g:
    x  = tf.Variable(1.0)
    y = tf.Variable(4.0)
    z = tf.convert_to_tensor([x**2 + 2*y, y**2])

    jacobian = g.jacobian(z, [x, y])
    print(jacobian)

获取

[<tf.Tensor: shape=(2,), dtype=float32, numpy=array([2., 0.], dtype=float32)>, <tf.Tensor: shape=(2,), dtype=float32, numpy=array([2., 8.], dtype=float32)>]

我想自然地得到Tensor

[[2., 0.],
 [2., 8.]]

而不是中间结果。它能做到吗?

pdsfdshx

pdsfdshx1#

试试这样

import numpy as np
import tensorflow as tf
with tf.GradientTape() as g:
    x  = tf.Variable(1.0)
    y = tf.Variable(4.0)
    z = tf.convert_to_tensor([x**2 + 2*y, y**2])

    jacobian = g.jacobian(z, [x, y])
    print(np.array([jacob.numpy() for jacob in jacobian]))

测试结果

[[2. 0.]
 [2. 8.]]

相关问题