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對應的索引

看個例子:

import tensorflow as tf
condition1 = [[True,False,False],
             [False,True,True]]
condition2 = [[True,False,False],
             [False,True,False]]
with tf.Session() as sess:
    print(sess.run(tf.where(condition1)))
    print(sess.run(tf.where(condition2)))

結果1:


[[0 0]
 [1 1]
 [1 2]]

表示第0行第0列,第1行第1列,第1行第2列這些位置上面的值爲真值;

結果2:

[[0 0]
 [1 1]]

表示第0行第0列,第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都是相等的。

import tensorflow as tf
x = [[1,2,3],[4,5,6]]
y = [[7,8,9],[10,11,12]]
condition3 = [[True,False,False],
             [False,True,True]]
condition4 = [[True,False,False],
             [True,True,False]]
with tf.Session() as sess:
    print(sess.run(tf.where(condition3,x,y)))
    print(sess.run(tf.where(condition4,x,y)))  
1, [[ 1  8  9]
    [10  5  6]]
2, [[ 1  8  9]
    [ 4  5 12]]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章