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()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。