Open In App

Python – tensorflow.clip_by_value()

Last Updated : 15 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.

clip_by_value()  is used to clip a Tensor values to a specified min and max.

Syntax: tensorflow.clip_by_value( t, clip_value_min, clip_value_max, name )

Parameter:

  • t: It is input Tensor.
  • clip_value_min: It defines the minimum clip value.
  • clip_value_max: It defines the maximum clip value.
  • name(optional): It defines the name for the operation.

Returns:

It returns a clipped Tensor.

Example 1:

Python3




# 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_value(t, clip_min, clip_max)
 
# Printing the result
print('Result: ', res)


Output:

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)

Example 2:

Python3




# 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)


Output:

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)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads