Open In App

Python – tensorflow.clip_by_norm()

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

<p><a href=”https://www.geeksforgeeks.org/introduction-to-tensorflow/”>TensorFlow</a> is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.

clip_by_norm() is used to clip tensor values to a maximum L2-norm.

Syntax: tensorflow.clip_by_norm(t, clip_norm, axes, name)

Parameters:

  • t: It is the input tensor that need to be clipped.
  • clip_norm: It is 0-D scalar tensor which defines the maximum clipping value.
  • axes(optional): It’s 1-D vector tensor which defines the dimension to be used for calculating L2norm. If none is provided all dimensions will be used.
  • name(optional): It defines the name for the operation.

Returns:

It returns a 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_norm = .8
 
# Printing the input tensor
print('t: ', t)
print('clip_norm: ', clip_norm)
 
# Calculating result
res = tf.clip_by_norm(t, clip_norm)
 
# Printing the result
print('Result: ', res)


Output:

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)

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_norm = 5.2
 
 
# Printing the input tensor
print('t: ', t)
print('clip_norm: ', clip_norm)
 
# Calculating result
res = tf.clip_by_norm(t, clip_norm)
 
# Printing the result
print('Result: ', res)


Output:

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)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads