📜  Python – tensorflow.GradientTape.jacobian()

📅  最后修改于: 2022-05-13 01:55:25.098000             🧑  作者: Mango

Python – tensorflow.GradientTape.jacobian()

TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。

jacobian()用于使用记录在该磁带上下文中的操作来计算 jacobian。

示例 1:

Python3
# Importing the library
import tensorflow as tf
  
x = tf.constant([[4, 2],[1, 3]], dtype=tf.dtypes.float32)
  
# Using GradientTape
with tf.GradientTape() as gfg:
  gfg.watch(x)
  y = x * x * x
  
# Computing jacobian
res  = gfg.jacobian(y, x) 
  
# Printing result
print("res: ",res)


Python3
# Importing the library
import tensorflow as tf
  
x = tf.constant([[4, 2],[1, 3]], dtype=tf.dtypes.float32)
  
# Using GradientTape
with tf.GradientTape() as gfg:
  gfg.watch(x)
  
  # Using nested GradientTape for calculating higher order jacobian
  with tf.GradientTape() as gg:
    gg.watch(x)
    y = x * x * x
  # Computing first order jacobian
  first_order = gg.jacobian(y, x)
  
# Computing Second order jacobian
second_order  = gfg.batch_jacobian(first_order, x) 
  
# Printing result
print("first_order: ",first_order)
print("second_order: ",second_order)


输出:

res:  tf.Tensor(
[[[[48.  0.]
   [ 0.  0.]]

  [[ 0. 12.]
   [ 0.  0.]]]


 [[[ 0.  0.]
   [ 3.  0.]]

  [[ 0.  0.]
   [ 0. 27.]]]], shape=(2, 2, 2, 2), dtype=float32)


示例 2:

Python3

# Importing the library
import tensorflow as tf
  
x = tf.constant([[4, 2],[1, 3]], dtype=tf.dtypes.float32)
  
# Using GradientTape
with tf.GradientTape() as gfg:
  gfg.watch(x)
  
  # Using nested GradientTape for calculating higher order jacobian
  with tf.GradientTape() as gg:
    gg.watch(x)
    y = x * x * x
  # Computing first order jacobian
  first_order = gg.jacobian(y, x)
  
# Computing Second order jacobian
second_order  = gfg.batch_jacobian(first_order, x) 
  
# Printing result
print("first_order: ",first_order)
print("second_order: ",second_order)

输出:

first_order:  tf.Tensor(
[[[[48.  0.]
   [ 0.  0.]]

  [[ 0. 12.]
   [ 0.  0.]]]


 [[[ 0.  0.]
   [ 3.  0.]]

  [[ 0.  0.]
   [ 0. 27.]]]], shape=(2, 2, 2, 2), dtype=float32)
second_order:  tf.Tensor(
[[[[[[24.  0.]
     [ 0.  0.]]

    [[ 0.  0.]
     [ 0.  0.]]]


   [[[ 0.  0.]
     [ 0.  0.]]

    [[ 0.  0.]
     [ 0.  0.]]]]



  [[[[ 0.  0.]
     [ 0.  0.]]

    [[ 0. 12.]
     [ 0.  0.]]]


   [[[ 0.  0.]
     [ 0.  0.]]

    [[ 0.  0.]
     [ 0.  0.]]]]]




 [[[[[ 0.  0.]
     [ 0.  0.]]

    [[ 0.  0.]
     [ 0.  0.]]]


   [[[ 0.  0.]
     [ 6.  0.]]

    [[ 0.  0.]
     [ 0.  0.]]]]



  [[[[ 0.  0.]
     [ 0.  0.]]

    [[ 0.  0.]
     [ 0.  0.]]]


   [[[ 0.  0.]
     [ 0.  0.]]

    [[ 0.  0.]
     [ 0. 18.]]]]]], shape=(2, 2, 2, 2, 2, 2), dtype=float32)