tf.where()用法

tenflow  中tf.where()用法

where(condition, x=None, y=None, name=None)
    
    
    
    

condition, x, y 相同维度,condition是bool型值,True/False

1,where(condition)的用法
    
    
    
    

condition是bool型值,True/False

返回值,是condition中元素为True对应的索引

看个例子:


    
    
    
    
  1. import tensorflow as tf
  2. a = [[ 1, 2, 3],[ 4, 5, 6]]
  3. b = [[ 1, 0, 3],[ 1, 5, 1]]
  4. condition1 = [[ True, False, False],
  5. [ False, True, True]]
  6. condition2 = [[ True, False, False],
  7. [ False, True, False]]
  8. with tf.Session() as sess:
  9. print(sess.run(tf.where(condition1)))
  10. print(sess.run(tf.where(condition2)))

结果1:


    
    
    
    
  1. [[ 0 0]
  2. [ 1 1]
  3. [ 1 2]]

结果2:


    
    
    
    
  1. [[ 0 0]
  2. [ 1 1]]
2, where(condition, x=None, y=None, name=None)的用法
    
    
    
    

condition, x, y 相同维度,condition是bool型值,True/False

返回值是对应元素,condition中元素为True的元素替换为x中的元素,为False的元素替换为y中对应元素

x只负责对应替换True的元素,y只负责对应替换False的元素,x,y各有分工

由于是替换,返回值的维度,和condition,x , y都是相等的。

看个例子:


    
    
    
    
  1. import tensorflow as tf
  2. x = [[ 1, 2, 3],[ 4, 5, 6]]
  3. y = [[ 7, 8, 9],[ 10, 11, 12]]
  4. condition3 = [[ True, False, False],
  5. [ False, True, True]]
  6. condition4 = [[ True, False, False],
  7. [ True, True, False]]
  8. with tf.Session() as sess:
  9. print(sess.run(tf.where(condition3,x,y)))
  10. print(sess.run(tf.where(condition4,x,y)))

结果:


    
    
    
    
  1. 1, [[ 1 8 9]
  2. [ 10 5 6]]
  3. 2, [[ 1 8 9]
  4. [ 4 5 12]]


你可能感兴趣的:(tf.where()用法)