Python ``tensorflow.clip_by_value()`` 方法:张量数值裁剪用法与示例


发布日期 : 2022-07-20 12:33:39 UTC

访问量: 9 次浏览

Python – tensorflow.clip\_by\_value()

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

clip\_by\_value() 用于将一个张量值剪切到指定的最小值和最大值。

语法:
tensorflow.clip_by_value( t, clip_value_min, clip_value_max, name )

参数:

  • t:它是输入张量。
  • clip\_value\_min : 它定义了最小剪辑值。
  • clip\_value\_max :它定义了最大的剪辑值。
  • name(可选):它定义了该操作的名称。

返回值:

返回一个剪裁过的张量。

示例 1:

# Importing the library
import tensorflow as tf

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

# Printing the input tensor
print('t: ', t)
print('clip_min: ', clip_value_min)
print('clip_max: ', clip_value_max)

# Calculating result
res = tf.clip_by_vlaue(t, clip_min, clip_max)

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

输出:

t: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)
clip_min: 2
clip_max: 5
Result: tf.Tensor([2. 2. 3. 4.], 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_value_min = [2, 3]
clip_value_max = [5, 7]

# Printing the input tensor
print('t: ', t)
print('clip_min: ', clip_value_min)
print('clip_max: ', clip_value_max)

# Calculating result
res = tf.clip_by_value(t, clip_value_min, clip_value_max)

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

输出:

t: tf.Tensor(
[[1. 2.]
[3. 4.]], shape=(2, 2), dtype=float64)
clip_min: [2, 3]
clip_max: [5, 7]
Result: tf.Tensor(
[[2. 3.]
[3. 4.]], shape=(2, 2), dtype=float64)