Clip Tensor Values to a Specified Min and Max with tf.clip_by_value – TensorFlow Example

By | May 29, 2019

tf.clip_by_value() can clip a tenser values to min and max number. In this tutorial, we will write an example to display the result in three situation.

Here is an example code:

import tensorflow as tf;
import numpy as np

A = tf.constant([[1,2,3],[1,3,3],[4,5,6],[7,8,9]], dtype=tf.float32)
B = tf.clip_by_value(A,2,7)
# the max number in A is smaller than 10
C = tf.clip_by_value(A,10,15)
# the min number in A is bigger than 0.5
D = tf.clip_by_value(A,0,0.5)

init = tf.global_variables_initializer() 
init_local = tf.local_variables_initializer()
with tf.Session() as sess:
    sess.run([init, init_local])
    np.set_printoptions(precision=4, suppress=True)
   
    b, c, d = sess.run([B, C, D])
    
    print 'b='
    print b
    print 'c='
    print c
    print 'b='
    print d

The result is:

Note: You must pay attention to minimum and maximum value in tensor whether is in min or max of tf.clip_by_value().

Leave a Reply