當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python tensorflow.GradientTape.jacobian()用法及代碼示例

TensorFlow是Google設計的開源Python庫,用於開發機器學習模型和深度學習神經網絡。

jacobian()用於使用在此磁帶上下文中記錄的操作來計算jacobian。

用法:jacobian( target, source, unconnected_gradients, parallel_iterations, experimental_use_pfor )

參數:

  • target:它是最低等級為2的張量。
  • source:它是最低等級為2的張量。
  • unconnected_gradients(可選):它的值可以為零或無。默認值為“無”。
  • parallel_iterations(可選):它用於控製並行迭代和內存使用。
  • experimental_use_pfor(可選):它是一個布爾值,默認值為True。設置為true時,它將使用pfor來計算jacobian,否則將使用tf.while_loop。

返回值:它返回張量。



範例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)

輸出:



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)







相關用法


注:本文由純淨天空篩選整理自aman neekhara大神的英文原創作品 Python – tensorflow.GradientTape.jacobian()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。