Python ``tensorflow.clip_by_norm()`` 函数用法详解与示例


发布日期 : 2021-07-15 20:22:40 UTC

访问量: 10 次浏览

Python – tensorflow.clip\_by\_norm()

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

clip\_by\_norm()用于将张量值剪辑成最大的L2-norm。

语法:
tensorflow.clip_by_norm(t, clip_norm, axes, name)

参数:

  • t:它是需要被剪切的输入张量。
  • clip\_norm :它是0-D标量张量,定义了最大剪裁值。
  • axes(可选):它是一个一维矢量张量,定义了计算L2norm时使用的维度。如果没有提供,将使用所有维度。
  • name(可选):它定义了该操作的名称。

返回值:

它返回一个张量。

示例 1:

# Importing the library
import tensorflow as tf

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

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

# Calculating tangent
res = tf.clip_by_norm(t, clip_norm)

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

输出:

t: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)
clip_norm: 0.8
Result: tf.Tensor([0.14605935 0.2921187 0.43817805 0.58423739], shape=(4, ), dtype=float64)

示例 2:

# Importing the library
import tensorflow as tf

# Initializing the input tensor
t = tf.constant([1, 2, 3, 4], dtype = tf.float64)
clip_norm = 5.2


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

# Calculating tangent
res = tf.clip_by_norm(t, clip_norm)

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

输出:

t: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)
clip_norm: 5.2
Result: tf.Tensor([0.94938577 1.89877153 2.8481573 3.79754307], shape=(4, ), dtype=float64)