Python ``tensorflow.clip_by_global_norm()`` 方法详解与使用示例


发布日期 : 2021-01-22 08:07:33 UTC

访问量: 10 次浏览

Python – tensorflow.clip\_by\_global\_norm()

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

clip\_by\_global\_norm()用于按照多个张量的规范之和的比率来剪辑它们的值。

语法

tensorflow.clip_by_global_norm( t_list, clip_norm, use_norm, name)

参数

  • t\_list :它是混合的Tensors、IndexedSlices的元组或列表。
  • clip\_norm :它是0-D标量张量。它定义了剪裁比率,必须大于0。
  • use\_norm (可选):它是0-D标量张量。它定义了要使用的规范。如果没有传递global\_norm(),则用它来计算规范。
  • name (可选):它定义了该操作的名称。

返回值:

  • list\_clipped :它是与 t\_list 相同类型的剪切张量的列表。
  • global\_norm :它是代表 global\_norm 的0-D张量。

示例

示例 1:

# Importing the library
import tensorflow as tf

# Initializing the input tensor
t_list = [tf.constant([1, 2, 3, 4], dtype = tf.float64), tf.constant([5, 6, 7, 8], dtype = tf.float64)]
clip_norm = .8
use_norm = tf.constant(1.0, dtype = tf.float64)

# Printing the input tensor
print('t_lis: ', t_list)
print('clip_norm: ', clip_norm)
print('use_norm: ', use_norm)

# Calculating tangent
res = tf.clip_by_global_norm(t_list, clip_norm, use_norm)

# Printing the result
print('Result: ', res)

输出:

t_lis: [<tf.Tensor: shape=(4, ), dtype=float64, numpy=array([1., 2., 3., 4.])>, <tf.Tensor: shape=(4, ), dtype=float64, numpy=array([5., 6., 7., 8.])>]
clip_norm: 0.8
use_norm: tf.Tensor(1.0, shape=(), dtype=float64)
Result: ([<tf.Tensor: shape=(4, ), dtype=float64, numpy=array([0.8, 1.6, 2.4, 3.2])>, <tf.Tensor: shape=(4, ), dtype=float64, numpy=array([4., 4.8, 5.6, 6.4])>], <tf.Tensor: shape=(), dtype=float64, numpy=1.0>)

例子2:
在这个例子中,没有给 use\_norm 传递任何信息,所以将使用 global\_norm() 来寻找法线。

# Importing the library
import tensorflow as tf

# Initializing the input tensor
t_list = [tf.constant([1, 2, 3, 4], dtype = tf.float64), tf.constant([5, 6, 7, 8], dtype = tf.float64)]
clip_norm = .8

# Printing the input tensor
print('t_lis: ', t_list)
print('clip_norm: ', clip_norm)

# Calculating tangent
res = tf.clip_by_global_norm(t_list, clip_norm)

# Printing the result
print('Result: ', res)

输出:

t_lis: [<tf.Tensor: shape=(4, ), dtype=float64, numpy=array([1., 2., 3., 4.])>, <tf.Tensor: shape=(4, ), dtype=float64, numpy=array([5., 6., 7., 8.])>]
clip_norm: 0.8
Result: ([<tf.Tensor: shape=(4, ), dtype=float64, numpy=array([0.0560112, 0.11202241, 0.16803361, 0.22404481])>, <tf.Tensor: shape=(4, ), dtype=float64, numpy=array([0.28005602, 0.33606722, 0.39207842, 0.44808963])>], <tf.Tensor: shape=(), dtype=float64, numpy=14.2828568570857>)